@memberjunction/ng-conversations 6.1.0-edge.6 → 6.1.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.
- package/dist/lib/components/dialogs/input-dialog.component.d.ts.map +1 -1
- package/dist/lib/components/dialogs/input-dialog.component.js +3 -3
- package/dist/lib/components/dialogs/input-dialog.component.js.map +1 -1
- package/dist/lib/components/message/message-input.component.js +4 -4
- package/dist/lib/components/message/message-input.component.js.map +1 -1
- package/dist/lib/components/realtime/realtime-activity-rail.component.d.ts +1 -1
- package/dist/lib/components/realtime/realtime-activity-rail.component.d.ts.map +1 -1
- package/dist/lib/components/realtime/realtime-activity-rail.component.js +2 -2
- package/dist/lib/components/realtime/realtime-activity-rail.component.js.map +1 -1
- package/dist/lib/components/realtime/realtime-agent-picker.component.d.ts +16 -1
- package/dist/lib/components/realtime/realtime-agent-picker.component.d.ts.map +1 -1
- package/dist/lib/components/realtime/realtime-agent-picker.component.js +39 -7
- package/dist/lib/components/realtime/realtime-agent-picker.component.js.map +1 -1
- package/dist/lib/components/realtime/realtime-delegation-card.component.d.ts +2 -2
- package/dist/lib/components/realtime/realtime-delegation-card.component.d.ts.map +1 -1
- package/dist/lib/components/realtime/realtime-delegation-card.component.js +159 -107
- package/dist/lib/components/realtime/realtime-delegation-card.component.js.map +1 -1
- package/dist/lib/components/realtime/realtime-session-state.d.ts +9 -4
- package/dist/lib/components/realtime/realtime-session-state.d.ts.map +1 -1
- package/dist/lib/components/realtime/realtime-session-state.js +95 -19
- package/dist/lib/components/realtime/realtime-session-state.js.map +1 -1
- package/dist/lib/services/delegation-result-parser.d.ts +5 -0
- package/dist/lib/services/delegation-result-parser.d.ts.map +1 -1
- package/dist/lib/services/delegation-result-parser.js +12 -0
- package/dist/lib/services/delegation-result-parser.js.map +1 -1
- package/dist/lib/services/realtime-session-review.service.d.ts +31 -1
- package/dist/lib/services/realtime-session-review.service.d.ts.map +1 -1
- package/dist/lib/services/realtime-session-review.service.js +63 -8
- package/dist/lib/services/realtime-session-review.service.js.map +1 -1
- package/dist/lib/services/realtime-session.service.d.ts +15 -8
- package/dist/lib/services/realtime-session.service.d.ts.map +1 -1
- package/dist/lib/services/realtime-session.service.js +62 -14
- package/dist/lib/services/realtime-session.service.js.map +1 -1
- package/package.json +31 -31
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message-input.component.js","sourceRoot":"","sources":["../../../../src/lib/components/message/message-input.component.ts","../../../../src/lib/components/message/message-input.component.html"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,SAAS,EAA8D,MAAM,eAAe,CAAC;AAE9I,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,EAAsB,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACvE,OAAO,EAA8B,2BAA2B,EAAE,kBAAkB,EAAE,cAAc,EAAE,wBAAwB,EAA6B,MAAM,+BAA+B,CAAC;AAKjM,OAAO,EAAE,wBAAwB,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAK7F,OAAO,EAAE,gCAAgC,EAAE,MAAM,oCAAoC,CAAC;AACtF,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAC9D,OAAO,EAA8G,mBAAmB,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAG7N,OAAO,EAAE,0BAA0B,EAAE,MAAM,6CAA6C,CAAC;AAIzF,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AAEtE,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAIzE,OAAO,EACL,gCAAgC,EAChC,sBAAsB,EACtB,mBAAmB,EACnB,mBAAmB,EACpB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,UAAU,EAAqB,MAAM,wBAAwB,CAAC;;;;;;;;;;;;;;;;;ICjCnE,8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K;;kBAyBL,KAAK;;kBAEL,MAAM;;kBACN,MAAM;;kBASN,MAAM;;kBAON,MAAM;;kBAKN,MAAM;;kBACN,MAAM;;kBACN,MAAM;;kBACN,MAAM;;kBACN,MAAM;;kBACN,MAAM;;kBACN,MAAM;;kBACN,MAAM;;kBACN,MAAM;;kBACN,MAAM;;kBACN,MAAM;;kBAEN,SAAS;mBAAC,UAAU;;kBAoCpB,KAAK;;kBAkBL,MAAM;;kBAON,MAAM;;kBAGN,MAAM;;kFAhSI,qBAAqB","sourcesContent":["import { Component, Input, Output, EventEmitter, ViewChild, OnInit, OnDestroy, OnChanges, SimpleChanges, AfterViewInit } from '@angular/core';\nimport { ConnectedPosition } from '@angular/cdk/overlay';\nimport { BaseAngularComponent } from '@memberjunction/ng-base-types';\nimport { UserInfo, Metadata, LogStatusEx } from '@memberjunction/core';\nimport { MJConversationDetailEntity, MJEnvironmentEntityExtended, ConversationEngine, UserInfoEngine, TaskGraphSubmitOperation, type TaskGraphSubmitInput } from '@memberjunction/core-entities';\nimport { MJAIAgentEntityExtended, MJAIAgentRunEntityExtended, AppContextSnapshot } from \"@memberjunction/ai-core-plus\";\nimport { DialogService } from '../../services/dialog.service';\nimport { ToastService } from '../../services/toast.service';\nimport { ConversationAgentService } from '../../services/conversation-agent.service';\nimport { BeforeAgentTurnEventArgs, AfterAgentTurnEventArgs } from '../../events/chat-events';\nimport { DataCacheService } from '../../services/data-cache.service';\nimport { ActiveTasksService } from '../../services/active-tasks.service';\nimport { ConversationStreamingService, MessageProgressUpdate, MessageProgressMetadata } from '../../services/conversation-streaming.service';\nimport { GraphQLDataProvider, GraphQLAIClient } from '@memberjunction/graphql-dataprovider';\nimport { GenerateAndApplyConversationName } from '../../services/conversation-naming';\nimport { AIEngineBase } from '@memberjunction/ai-engine-base';\nimport { ExecuteAgentResult, AgentExecutionProgressCallback, AgentResponseForm, ActionableCommand, AutomaticCommand, ConversationUtility, agentFailureDisposition, agentFailureMessage } from '@memberjunction/ai-core-plus';\nimport { PendingAttachment } from '@memberjunction/ng-composer';\nimport { AiComposerComponent } from '../composer/ai-composer.component';\nimport { MentionAutocompleteService } from '../../services/mention-autocomplete.service';\nimport { MentionParserService } from '../../services/mention-parser.service';\nimport { ConversationAttachmentService } from '../../services/conversation-attachment.service';\nimport { Mention, MentionParseResult } from '../../models/conversation-state.model';\nimport { PlanModePreference } from '../../utils/plan-mode-preference';\nimport { LazyArtifactInfo } from '../../models/lazy-artifact-info';\nimport { MJNotificationService } from '@memberjunction/ng-notifications';\nimport { ConversationBridgeService } from '../../services/conversation-bridge.service';\nimport { RealtimeSessionService } from '../../services/realtime-session.service';\nimport { RealtimeAgentPick } from '../realtime/realtime-agent-picker.component';\nimport {\n BuildRealtimeConfigOverridesJson,\n FilterRealtimeCoAgents,\n LoadCoAgentPairings,\n PairingsAllowTarget\n} from '../../services/realtime-pairing';\nimport { Subscription } from 'rxjs';\nimport { UUIDsEqual, CleanAndParseJSON } from '@memberjunction/global';\n\n@Component({\n standalone: false,\n selector: 'mj-message-input',\n templateUrl: './message-input.component.html',\n styleUrl: './message-input.component.css'\n})\nexport class MessageInputComponent extends BaseAngularComponent implements OnInit, OnDestroy, OnChanges, AfterViewInit {\n // Default artifact type ID for JSON (when agent doesn't specify DefaultArtifactTypeID)\n private readonly JSON_ARTIFACT_TYPE_ID = 'ae674c7e-ea0d-49ea-89e4-0649f5eb20d4';\n\n @Input() conversationId!: string;\n @Input() conversationName?: string | null; // For task tracking display\n @Input() currentUser!: UserInfo;\n @Input() disabled: boolean = false;\n @Input() placeholder: string = 'Type a message... (Ctrl+Enter to send)';\n @Input() parentMessageId?: string; // Optional: for replying in threads\n @Input() enableAttachments: boolean = true; // Whether to show attachment button (based on agent modality support)\n @Input() enableMentions: boolean = true; // Whether to enable @-mention autocomplete (agents/users). Hosts addressing a single fixed agent (e.g. Form Builder cockpit) typically set false.\n // Per-type caps under enableMentions (all default true) — forwarded to the AI composer's\n // EnableAgentMentions/EnableEntityMentions/EnableSkillCommands. Let a host keep '/' skill\n // commands while dropping '@' agent mentions (which would override a pinned default agent).\n @Input() enableAgentMentions: boolean = true;\n @Input() enableEntityMentions: boolean = true;\n @Input() enableSkillCommands: boolean = true;\n @Input() enablePlanMode: boolean = true; // Whether the composer shows the Plan Mode toggle. Hosts that don't expose plan-mode workflows set false.\n @Input() enableRealtime: boolean = true; // Whether the composer shows the realtime voice-call launcher/options. Hosts without a voice experience set false.\n @Input() maxAttachments: number = 10; // Maximum number of attachments per message\n @Input() maxAttachmentSizeBytes: number = 20 * 1024 * 1024; // Maximum size per attachment (20MB default)\n @Input() acceptedFileTypes: string = 'image/*'; // Accepted MIME types pattern\n @Input() artifactsByDetailId?: Map<string, LazyArtifactInfo[]>; // Pre-loaded artifact data for performance\n @Input() systemArtifactsByDetailId?: Map<string, LazyArtifactInfo[]>; // Pre-loaded system artifact data (Visibility='System Only')\n @Input() agentRunsByDetailId?: Map<string, MJAIAgentRunEntityExtended>; // Pre-loaded agent run data for performance\n @Input() emptyStateMode: boolean = false; // When true, emits emptyStateSubmit instead of creating messages directly\n @Input() appContext: Record<string, unknown> | null = null; // Application context for AI agent awareness\n\n /**\n * Plan Mode toggle state — sticky PER CONVERSATION, OFF by default (no behavior change unless\n * the user turns it on). When on, the user's next message(s) in THIS conversation request Plan\n * Mode: the routed root agent must present a plan for approval before executing Actions/\n * Sub-Agents. The toggle is always shown and the server enforces the `AIAgent.SupportsPlanMode`\n * capability — a plan-mode request to an agent that doesn't support it simply no-ops the gate\n * (see resolvePlanModeGate), so we don't need to resolve \"the current agent\" client-side.\n *\n * IMPORTANT: this is a GETTER over {@link PlanModePreference} (UserInfoEngine-backed), NOT a\n * local field. The composer is mounted in multiple places at once (empty-state, chat-area,\n * thread panel) — a local boolean per instance goes stale the moment another instance toggles.\n * On the new-conversation composer (no conversationId yet) the value lives in a pending bucket\n * that transfers to the real conversation on its first message. Approving a plan turns the\n * conversation's flag OFF automatically (see message-item's plan-decision handling).\n */\n public get PlanModeEnabled(): boolean {\n return PlanModePreference.IsEnabled(this.conversationId);\n }\n\n /**\n * Skill IDs the user requested via `/skill-name` mentions in the message being routed. Collected\n * once per send from the composer's mention chips and forwarded to every agent-invocation path so\n * whichever agent handles the message receives them as `RequestedSkillIDs`. The server intersects\n * them with the agent's accepted skills AND the user's Run permission before any activate, so a\n * skill the user can't run (or the agent doesn't accept) is silently dropped. Reset each send.\n */\n private _pendingRequestedSkillIDs: string[] = [];\n\n /**\n * Collects the skill IDs from `/skill` mention chips currently in the composer. Called at the\n * start of routing so the value is stable for the whole message dispatch.\n */\n private collectRequestedSkillIDs(): string[] {\n const chipData = this.inputBox?.getMentionChipsData() || [];\n return chipData.filter(chip => chip.type === 'skill').map(chip => chip.id);\n }\n\n /**\n * Optional default agent ID for the conversation. When set, the FIRST\n * message routes directly to this agent — skipping Sage's default\n * delegation — provided the user did not @mention a different agent\n * and there is no prior agent in the conversation history. After the\n * first message, the existing \"last non-Sage agent\" continuity rule\n * keeps subsequent messages on the same agent.\n *\n * Used by embedded chat surfaces (Form Builder cockpit, future\n * domain-specific chats) that have an obvious specialist agent for the\n * context and don't need Sage to route. Leave unset to preserve the\n * standard Sage-fronted UX of the main Chat app.\n */\n @Input() defaultAgentId: string | null = null;\n\n /**\n * Per-conversation pinned default agent — sourced from the loaded\n * `MJConversationEntity.DefaultAgentID`. When set, this agent is used in\n * preference to the embedder-supplied {@link defaultAgentId} so a user\n * who pins a conversation to e.g. Research Agent gets that routing even\n * inside an embedded surface whose embedder defaults to a different\n * specialist. Routing precedence:\n * 1. @mention\n * 2. continuity (last responder)\n * 3. **conversationDefaultAgentId** (this input — user's per-conversation pin)\n * 4. defaultAgentId (embedder-supplied)\n * 5. Sage fallback\n */\n @Input() conversationDefaultAgentId: string | null = null;\n\n /**\n * The `MJ: AI Agent Configurations.ID` selected via the chat header's\n * mode picker (Draft / Standard / High). Applied to **non-mention**\n * routes — when the user types without `@mention`, this preset rides\n * along on the next `invokeSubAgent` call so the server resolves the\n * agent's Fast / Standard / High Power AI configuration accordingly.\n *\n * Mentioned-route turns still use the preset embedded in the mention\n * (e.g. `@Form Builder /high`) because that's a per-message intent\n * the user just expressed. Continuity-route turns (last responder\n * agent) also honor this input as the fallback when the prior\n * message itself doesn't carry an explicit configuration preset.\n *\n * Picker writes are forward-only: changing the mode does NOT re-route\n * messages already in flight or already in history. Affects \"what\n * happens next.\"\n */\n @Input() agentConfigurationPresetId: string | null = null;\n\n // Initial message to send automatically - using getter/setter for precise control\n private _initialMessage: string | null = null;\n private _initialAttachments: PendingAttachment[] | null = null;\n private _isComponentReady = false; // Track if component is ready to send\n /** Conversation this input has already auto-sent its pending first message for. */\n private _autoSentForConversationId: string | null = null;\n\n @Input()\n set initialMessage(value: string | null) {\n // Handle case where an object with {text, attachments} is passed instead of just a string\n // This can happen if there's a type mismatch in the binding chain\n let actualValue = value;\n if (value && typeof value === 'object' && 'text' in value) {\n actualValue = (value as { text: string }).text;\n }\n\n const previousValue = this._initialMessage;\n this._initialMessage = actualValue;\n\n // If component is ready and we have a new non-null message, trigger send\n if (this._isComponentReady && actualValue && actualValue !== previousValue) {\n this.triggerInitialSend();\n }\n }\n get initialMessage(): string | null {\n return this._initialMessage;\n }\n\n @Input()\n set initialAttachments(value: PendingAttachment[] | null) {\n this._initialAttachments = value;\n }\n get initialAttachments(): PendingAttachment[] | null {\n return this._initialAttachments;\n }\n\n private _conversationHistory: MJConversationDetailEntity[] = [];\n @Input()\n public get conversationHistory(): MJConversationDetailEntity[] {\n return this._conversationHistory;\n }\n public set conversationHistory(value: MJConversationDetailEntity[]) {\n this._conversationHistory = value;\n }\n\n // Message IDs that are in-progress and need streaming reconnection\n // Using getter/setter to react immediately when value changes (avoids timing issues with ngOnChanges)\n private _inProgressMessageIds?: string[];\n @Input()\n set inProgressMessageIds(value: string[] | undefined) {\n this._inProgressMessageIds = value;\n // React immediately when input changes (after component initialized)\n // This ensures callbacks are registered without relying on ngOnChanges timing\n if (this.streamingService && value && value.length > 0) {\n this.reconnectInProgressMessages();\n } else if (this.streamingService) {\n // Empty/undefined — e.g. this input was backgrounded by a conversation swap\n // ([] is bound to non-active inputs). Drop any streaming callbacks so a hidden\n // input isn't left subscribed; reconnectInProgressMessages re-registers when it\n // becomes active again with a non-empty list.\n this.unregisterAllCallbacks();\n }\n }\n get inProgressMessageIds(): string[] | undefined {\n return this._inProgressMessageIds;\n }\n\n /**\n * Application context for the current conversation. Threaded through from the\n * chat-area component for inclusion in the {@link beforeAgentTurn} event payload —\n * lets listeners reason about which app's chat surface is invoking the agent.\n * Optional; defaults to null for surfaces with no app context.\n */\n @Input() applicationId: string | null = null;\n\n @Output() messageSent = new EventEmitter<MJConversationDetailEntity>();\n @Output() agentResponse = new EventEmitter<{message: MJConversationDetailEntity, agentResult: any}>();\n\n /**\n * Cancelable — fired BEFORE `agentService.processMessage()` is called for a user turn.\n * Listeners may set `event.Cancel = true` to halt the agent invocation (e.g., a\n * client-side guardrail blocking the turn). When canceled, the corresponding\n * {@link afterAgentTurn} event is NOT fired and the running task is cleared.\n * Follows MJ's established Before/After cancelable event pattern.\n */\n @Output() beforeAgentTurn = new EventEmitter<BeforeAgentTurnEventArgs>();\n\n /**\n * Fired AFTER a successful agent turn completes. Carries the agent run id and the\n * full agent result. Not fired when {@link beforeAgentTurn} was canceled or when\n * the underlying `processMessage` errored.\n */\n @Output() afterAgentTurn = new EventEmitter<AfterAgentTurnEventArgs>();\n // conversationId is carried on every agent-lifecycle event so the parent chat-area can drop\n // events emitted by a BACKGROUND conversation's (hidden, still-streaming) input after the user\n // has swapped conversations — preventing cross-conversation state/cache bleed. Sourced from the\n // ConversationDetail entity's ConversationID (the captured, immutable value), never this.conversationId.\n @Output() agentRunDetected = new EventEmitter<{conversationId: string; conversationDetailId: string; agentRunId: string}>();\n @Output() agentRunUpdate = new EventEmitter<{conversationId: string; conversationDetailId: string; agentRun?: any, agentRunId?: string}>(); // Emits when agent run data updates during progress\n @Output() messageComplete = new EventEmitter<{conversationId: string; conversationDetailId: string; agentId?: string}>(); // Emits when message completes (success or error)\n @Output() artifactCreated = new EventEmitter<{conversationId: string; artifactId: string; versionId: string; versionNumber: number; conversationDetailId: string; name: string}>();\n @Output() conversationRenamed = new EventEmitter<{conversationId: string; name: string; description: string}>();\n @Output() intentCheckStarted = new EventEmitter<{conversationId: string}>(); // Emits when intent checking starts\n @Output() intentCheckCompleted = new EventEmitter<{conversationId: string}>(); // Emits when intent checking completes (carries conversationId so the parent can drop a background conversation's completion after a swap — symmetric with intentCheckStarted)\n @Output() initialMessageAutoSendStarted = new EventEmitter<{conversationId: string}>(); // Emitted when this input latches the pending first message for auto-send\n @Output() initialMessageAutoSendFailed = new EventEmitter<{conversationId: string}>(); // Emitted when a latched pending first message fails before messageSent\n @Output() emptyStateSubmit = new EventEmitter<{text: string; attachments: PendingAttachment[]}>(); // Emitted when in emptyStateMode\n @Output() uploadStateChanged = new EventEmitter<{isUploading: boolean; message: string}>(); // Emits when attachment upload state changes\n\n @ViewChild('inputBox') inputBox!: AiComposerComponent;\n\n private _messageText: string = '';\n /**\n * The composer's text. An accessor pair rather than a plain field because every write reaches the\n * editor through `[value]` -> `ngModel.writeValue`, which rebuilds or empties the chip DOM WITHOUT\n * emitting `valueChange` — so a write is exactly the event {@link mentionedAgentId} has to hear\n * about, and the setter is the one place that cannot be bypassed.\n *\n * Bypassing it is not hypothetical: `handleSuccessfulSend` and the empty-state submit clear the\n * text without touching the editor, and `conversation-chat-area` assigns `messageText` on this\n * component from the outside (three call sites). Invalidating at the individual call sites instead\n * would leave every future one to remember.\n *\n * Read is a plain field read; there is no two-way `ngModel` on this property (the template binds\n * `[value]=\"messageText\"` one-way), so the pair is transparent to callers.\n */\n public get messageText(): string {\n return this._messageText;\n }\n public set messageText(value: string) {\n this._messageText = value;\n this.mentionedAgentId = undefined;\n }\n\n /**\n * Prefills the composer with draft text WITHOUT sending (unlike pendingMessage,\n * which auto-sends) and focuses the input — e.g. the omnibar's '@agent' flow\n * lands in chat with '@AgentName ' staged so the user just types their ask.\n */\n /**\n * Draft text to stage in the composer when this input mounts (NOT sent — unlike\n * pendingMessage). Applied once per distinct value, view-readiness-proof: if the\n * view isn't up yet, ngAfterViewInit applies it. Emits initialDraftApplied so the\n * host can clear its pending state.\n */\n @Input()\n set initialDraft(value: string | null) {\n if (value && value !== this.appliedInitialDraft) {\n this.appliedInitialDraft = value;\n if (this.inputBox) {\n this.SetDraft(value, true);\n this.initialDraftApplied.emit();\n } else {\n this.pendingInitialDraft = value;\n }\n }\n }\n get initialDraft(): string | null {\n return this.appliedInitialDraft;\n }\n private appliedInitialDraft: string | null = null;\n private pendingInitialDraft: string | null = null;\n\n @Output() initialDraftApplied = new EventEmitter<void>();\n\n /**\n * Live draft-state signal: fires on every composer value change with the\n * SERIALIZED content (mention pills encoded via getPlainTextWithJsonMentions,\n * so hosts can persist drafts losslessly). Empty string = draft cleared.\n */\n @Output() DraftStateChanged = new EventEmitter<string>();\n\n /** The composer lost focus — hosts flush persisted drafts on this. */\n @Output() ComposerBlurred = new EventEmitter<void>();\n\n /** Handles the composer's value stream: keeps messageText in sync + emits draft state. */\n public OnComposerValueChanged(value: string): void {\n this.messageText = value;\n this.DraftStateChanged.emit(this.GetSerializedDraft());\n }\n\n /** Current composer content in the lossless serialized form ('' when empty). */\n public GetSerializedDraft(): string {\n const serialized = this.inputBox?.getPlainTextWithJsonMentions() ?? this.messageText ?? '';\n return serialized.trim().length === 0 ? '' : serialized;\n }\n\n /**\n * Pre-addresses the composer to an agent as a RESOLVED mention pill (+ trailing\n * space, caret after, focused) — identical to the user typing '@agent' and picking\n * it from the dropdown. Resolves the agent through MentionAutocompleteService so\n * the chip carries the agent's real id/icon/presets; falls back to a plain-text\n * '@Name ' draft when the agent can't be resolved (e.g. name mismatch).\n *\n * @returns false while the composer view isn't mounted yet — callers may retry.\n */\n public async InsertAgentMention(agentName: string, focus: boolean = true, clearExisting: boolean = true): Promise<boolean> {\n if (!this.inputBox) {\n console.log(`[Omnibar→Chat] InsertAgentMention('${agentName}'): input box not mounted yet — caller will retry`);\n return false;\n }\n if (clearExisting) {\n // Pre-addressing REPLACES any un-sent draft (tagging agent B after agent A\n // must not stack pills).\n this.inputBox.mentionEditor?.clear();\n this.messageText = '';\n }\n try {\n if (!this.mentionAutocomplete.IsInitialized && this.currentUser) {\n console.log(`[Omnibar→Chat] InsertAgentMention('${agentName}'): initializing mention autocomplete…`);\n await this.mentionAutocomplete.initialize(this.currentUser);\n }\n const wanted = agentName.trim().toLowerCase();\n const suggestion = this.mentionAutocomplete\n .getSuggestions(agentName, false, '@')\n .find(s => s.type === 'agent' && s.name.trim().toLowerCase() === wanted);\n if (suggestion) {\n const inserted = this.inputBox.InsertMention(suggestion, focus);\n console.log(`[Omnibar→Chat] InsertAgentMention('${agentName}'): resolved to pill (id=${suggestion.id}) — insert ${inserted ? 'OK' : 'FAILED (editor view not ready)'}`);\n if (inserted) {\n if (focus) {\n this.scheduleFocusReassert(agentName);\n }\n return true;\n }\n return false; // editor view not mounted — caller retries\n }\n console.warn(`[Omnibar→Chat] InsertAgentMention('${agentName}'): agent NOT found in autocomplete (initialized=${this.mentionAutocomplete.IsInitialized}) — falling back to plain text`);\n } catch (e) {\n console.warn(`[Omnibar→Chat] InsertAgentMention('${agentName}'): resolution error — falling back to plain text`, e);\n }\n const mention = agentName.includes(' ') ? `@\"${agentName}\" ` : `@${agentName} `;\n this.SetDraft(mention, focus);\n return true;\n }\n\n /**\n * The insert happens mid-tab-mount; late-arriving chat UI (lists, empty-state\n * autofocus, tab chrome) can steal focus AFTER we set it. Re-assert at settle\n * points — only when focus genuinely left the editor, so we never fight the user.\n */\n private scheduleFocusReassert(context: string): void {\n for (const delay of [300, 900, 1800]) {\n setTimeout(() => {\n const editor = this.inputBox?.mentionEditor;\n if (editor && !editor.HasFocus) {\n const ok = editor.FocusCaretAtEnd();\n console.log(`[Omnibar→Chat] focus re-assert (+${delay}ms) for '${context}': ${ok ? 'refocused' : 'editor gone'}`);\n }\n }, delay);\n }\n }\n\n public SetDraft(text: string, focus: boolean = true): void {\n this.messageText = text;\n if (focus) {\n // The composer mounts/binds on the next tick after messageText flows down.\n setTimeout(() => this.inputBox?.focus(), 50);\n }\n }\n public isSending: boolean = false;\n public isProcessing: boolean = false; // True when waiting for agent/naming response\n public processingMessage: string = 'AI is responding...'; // Message shown during processing\n public isUploadingAttachments: boolean = false; // True when uploading attachments to server\n public uploadingMessage: string = 'Uploading attachments...'; // Message shown during upload\n public converationManagerAgent: MJAIAgentEntityExtended | null = null;\n\n // Track completion timestamps to prevent race conditions with late progress updates\n private completionTimestamps = new Map<string, number>();\n // Track registered streaming callbacks for cleanup\n private registeredCallbacks = new Map<string, (progress: MessageProgressUpdate) => Promise<void>>();\n // After a post-ACK disconnect, keep observing ConversationDetail.Status until\n // the *server* writes Complete/Error (MaxTimePerRun terminates the run).\n // Back off 5s → 15s → 60s so we bound polling cost, not invent a client\n // verdict. Do not paint Error here — that would unregister the streaming\n // callback and make a later server Complete sticky-wrong until reload.\n private static readonly IN_FLIGHT_WATCH_BACKOFF_MS = [5_000, 15_000, 60_000] as const;\n private inFlightWatches = new Map<string, ReturnType<typeof setTimeout>>();\n\n // Track pending attachments from the input box\n private pendingAttachments: PendingAttachment[] = [];\n\n private engine = ConversationEngine.Instance;\n // Shared AI mention/suggestion engine (BaseSingleton — same instance the composer plugins use)\n private mentionAutocomplete = MentionAutocompleteService.Instance;\n\n constructor(\n private dialogService: DialogService,\n private toastService: ToastService,\n private agentService: ConversationAgentService,\n private dataCache: DataCacheService,\n private activeTasks: ActiveTasksService,\n private streamingService: ConversationStreamingService,\n private mentionParser: MentionParserService,\n private attachmentService: ConversationAttachmentService,\n private bridge: ConversationBridgeService,\n private realtimeSession: RealtimeSessionService\n ) {\n super();}\n\n // ── Voice session (Realtime Co-Agent) ───────────────────────────────\n /** True while a live voice session is active — drives the overlay + mic state. */\n public voiceActive: boolean = false;\n private realtimeActiveSub?: Subscription;\n\n async ngOnInit() {\n // Bind provider-aware services to this component's provider.\n const p = this.ProviderToUse;\n this.agentService.Provider = p;\n this.dataCache.Provider = p;\n this.activeTasks.Provider = p;\n this.attachmentService.Provider = p;\n this.realtimeSession.Provider = p;\n\n // Reflect the live voice-session Active flag into a local field for the template.\n this.realtimeActiveSub = this.realtimeSession.Active$.subscribe(active => {\n this.voiceActive = active;\n });\n\n this.converationManagerAgent = await this.agentService.getConversationManagerAgent();\n\n // Warm UserInfoEngine so the PlanModeEnabled getter has the cached settings available\n // (no-op when already loaded; failure just leaves the toggle at its default OFF).\n PlanModePreference.Warm();\n\n // Initialize mention autocomplete (needed for parsing mentions in messages)\n await this.mentionAutocomplete.initialize(this.currentUser);\n\n // Reconnect to any in-progress messages for streaming updates (via global streaming service)\n this.reconnectInProgressMessages();\n }\n\n ngOnChanges(changes: SimpleChanges) {\n // When conversation changes, focus the input\n if (changes['conversationId'] && !changes['conversationId'].firstChange) {\n this.focusInput();\n }\n // Note: initialMessage/initialAttachments handled by setters, inProgressMessageIds handled by setter\n }\n\n ngAfterViewInit() {\n if (this.pendingInitialDraft) {\n const draft = this.pendingInitialDraft;\n this.pendingInitialDraft = null;\n // next tick — the composer's own view finishes mounting first\n setTimeout(() => {\n this.SetDraft(draft, true);\n this.initialDraftApplied.emit();\n }, 50);\n }\n // Focus input on initial load\n this.focusInput();\n\n // Mark component as ready\n this._isComponentReady = true;\n\n // If there's an initial message to send (from empty state), send it automatically\n if (this._initialMessage || (this._initialAttachments && this._initialAttachments.length > 0)) {\n this.triggerInitialSend();\n }\n }\n\n /**\n * Triggers sending of initial message and attachments.\n * Called from setter or ngAfterViewInit when conditions are met.\n */\n private triggerInitialSend(): void {\n const message = this._initialMessage;\n const attachments = this._initialAttachments;\n const hasContent = !!message || !!(attachments && attachments.length > 0);\n\n if (!hasContent || !this.conversationId || UUIDsEqual(this._autoSentForConversationId, this.conversationId)) {\n return;\n }\n this._autoSentForConversationId = this.conversationId;\n\n // Set pending attachments before sending\n if (attachments && attachments.length > 0) {\n this.pendingAttachments = [...attachments];\n }\n\n Promise.resolve().then(() => {\n this.initialMessageAutoSendStarted.emit({ conversationId: this.conversationId });\n });\n\n // Use setTimeout to ensure we're outside of change detection cycle\n setTimeout(async () => {\n const sent = await this.sendMessageWithText(message || '');\n if (!sent) {\n this._autoSentForConversationId = null;\n this.initialMessageAutoSendFailed.emit({ conversationId: this.conversationId });\n }\n }, 100);\n }\n\n ngOnDestroy() {\n // Unregister all streaming callbacks\n this.unregisterAllCallbacks();\n this.clearInFlightWatches();\n this.realtimeActiveSub?.unsubscribe();\n // If the user navigates away mid-call, tear the session down.\n if (this.realtimeSession.IsActive) {\n void this.realtimeSession.EndRealtimeSession();\n }\n }\n\n /**\n * Resolve the agent the voice session should front for THIS conversation.\n * Mirrors the routing precedence used for text turns ({@link routeMessage}):\n * 1. last non-Sage agent (continuity)\n * 2. per-conversation pinned default\n * 3. embedder-supplied default\n * 4. Sage fallback\n * Returns null only if Sage itself failed to load.\n */\n public resolveCurrentAgentId(): string | null {\n return this.findLastNonSageAgentId()\n ?? this.conversationDefaultAgentId\n ?? this.defaultAgentId\n ?? this.converationManagerAgent?.ID\n ?? null;\n }\n\n /**\n * The agent the '/' skill picker should narrow to. Mirrors routing's priority: an explicit\n * `@agent` chip already in the draft wins (routeMessage's Priority 1), else the agent the message\n * would otherwise go to ({@link resolveCurrentAgentId}). Bound to `mj-ai-composer`'s\n * `TargetAgentId`; null = unknown, no narrowing.\n */\n public get pickerTargetAgentId(): string | null {\n if (this.mentionedAgentId === undefined) {\n const chips = this.inputBox?.getMentionChipsData() || [];\n this.mentionedAgentId = chips.find(chip => chip.type === 'agent')?.id ?? null;\n }\n return this.mentionedAgentId ?? this.resolveCurrentAgentId();\n }\n\n /**\n * Memo for the first `@agent` chip in the draft, so the template-bound\n * {@link pickerTargetAgentId} does not walk the editor DOM on every change-detection cycle.\n *\n * `undefined` = dirty, recompute on next read; `null` = computed, no `@agent` chip present.\n * The two are NOT interchangeable — collapsing them to `null` is what makes a cleared or restored\n * draft read as \"no chip\" forever.\n *\n * Invalidated from {@link messageText}'s setter, which is the only choke point every chip change\n * passes through. Chips reach the editor by two kinds of path and only one announces itself:\n *\n * - user editing (autocomplete insert, backspace-delete, `InsertMention`) and `clear()` all end\n * in the editor's `onInput()`, which emits `valueChange` -> {@link OnComposerValueChanged},\n * which assigns `messageText`;\n * - a programmatic write — a restored draft (`[initialDraft]` -> {@link SetDraft}), a post-send\n * reset, or a host assigning `messageText` directly — goes `[value]` ->\n * `ngModel.writeValue` -> `setEditorContent`, which rebuilds the chips with `appendChild` (or\n * empties the editor) and never calls `onInput()`. No `valueChange`, so no hook fires.\n *\n * Invalidate-and-lazy rather than eager refresh, because an eager read in the setter would be too\n * early: `ngModel` writes the editor on a later change-detection pass, so the read would predate\n * the chips it wants. Marking dirty is timing-independent — the recompute happens on the next\n * read, by which point the editor holds the new content.\n *\n * The picker can be opened by the Skills button as well as by typing `/`, so \"the next keystroke\n * would repair it\" is not a defence: the button path takes whatever the memo holds.\n */\n private mentionedAgentId: string | null | undefined = undefined;\n\n /** True when the mic button should be enabled (have an agent + not disabled). */\n public get canStartRealtime(): boolean {\n return !this.disabled && !this.voiceActive && !!this.resolveCurrentAgentId();\n }\n\n /**\n * Display name of the agent the voice session fronts. Resolved here (this component\n * owns the conversation's routing context) and passed to RealtimeSessionService at\n * session start so the chat-area-hosted overlay can read it from the service.\n */\n private resolveRealtimeAgentName(): string {\n const agentId = this.resolveCurrentAgentId();\n if (agentId) {\n const match = this.mentionAutocomplete\n .getAvailableAgents()\n .find(a => UUIDsEqual(a.ID, agentId));\n if (match?.Name) {\n return match.Name;\n }\n }\n return this.converationManagerAgent?.Name ?? 'Sage';\n }\n\n /** True while the \"Start a voice call with…\" agent picker popover is open. */\n public showRealtimeAgentPicker: boolean = false;\n\n /**\n * CDK connected-overlay positions for the voice agent picker. Preferred: open UPWARD,\n * right edge aligned to the composer's right edge (matching the old absolute placement).\n * Fallback: open downward when there isn't room above. Because the popover renders in the\n * body-level CDK overlay container (with `cdkConnectedOverlayPush`), it escapes the chat\n * overlay's `overflow: hidden` border and can never clip at the top of a narrow overlay.\n */\n public readonly pickerOverlayPositions: ConnectedPosition[] = [\n { originX: 'end', originY: 'top', overlayX: 'end', overlayY: 'bottom', offsetY: -8 },\n { originX: 'end', originY: 'bottom', overlayX: 'end', overlayY: 'top', offsetY: 8 },\n ];\n\n /**\n * `MJ: User Settings` key persisting the user's co-agent choice for realtime calls\n * (server-side, cross-device — never localStorage). Stored shape: `{\"coAgentId\":\n * string | null}` — `null` is an explicit \"Auto\" choice that overwrites an older pick.\n */\n private static readonly CoAgentPrefKey = 'mj.realtimeVoice.coAgent.v1';\n\n /**\n * The persisted co-agent preference, loaded just before the picker opens (and read by\n * the instant-start path). `null` = no preference / explicit \"Auto\".\n */\n public voicePickerDefaultCoAgentId: string | null = null;\n\n /**\n * Agents the voice picker offers — the same cached set the @mention\n * autocomplete and {@link resolveRealtimeAgentName} use, so the picker can\n * never offer an agent the conversation couldn't otherwise route to.\n */\n public get voicePickerAgents(): MJAIAgentEntityExtended[] {\n return this.mentionAutocomplete.getAvailableAgents();\n }\n\n /**\n * The ACTIVE Realtime-type co-agent candidates — the same run-permission-filtered\n * cached set as {@link voicePickerAgents}, narrowed to the Realtime agent type. The\n * picker shows its co-agent selector only when more than one exists.\n */\n public get voicePickerCoAgents(): MJAIAgentEntityExtended[] {\n return FilterRealtimeCoAgents(this.mentionAutocomplete.getAvailableAgents());\n }\n\n /** The agent the default resolution would call — preselected in the picker. */\n public get voicePickerDefaultAgentId(): string | null {\n return this.resolveCurrentAgentId();\n }\n\n /**\n * Start a real-time voice session fronting the conversation's current agent.\n * Client-direct: the RealtimeSessionService mints an ephemeral token and connects\n * the browser straight to the realtime provider over WebRTC. The \"call mode\"\n * overlay itself is hosted by the conversation chat area (driven by Active$).\n *\n * NEW vs EXISTING conversation:\n * - When an agent has already participated (a prior non-Sage AI turn exists),\n * start immediately with the resolved agent — zero added friction.\n * - When the conversation has NO prior agent participation (new / empty\n * conversation), the resolution would silently fall through to a default\n * the user never chose — so show a compact agent picker instead and start\n * with whichever agent they pick.\n */\n public async onStartRealtime(): Promise<void> {\n if (!this.canStartRealtime) {\n return;\n }\n // New/empty conversation (no prior agent turn): let the user choose who\n // to call. Falls through to the immediate path if the agent cache is\n // empty (nothing to pick from — the resolved default is the only option).\n if (!this.findLastNonSageAgentId() && this.voicePickerAgents.length > 0) {\n await this.openRealtimeAgentPicker();\n return;\n }\n const targetAgentId = this.resolveCurrentAgentId();\n if (!targetAgentId) {\n this.toastService.error('No agent available for a voice session.');\n return;\n }\n const coAgentId = await this.resolveInstantCoAgentId(targetAgentId);\n await this.startRealtimeWithAgent(targetAgentId, this.resolveRealtimeAgentName(), null, coAgentId);\n }\n\n /**\n * Caret-next-to-the-phone click: open the agent/co-agent/model picker ON DEMAND, even\n * when the conversation already has agent history (where the plain phone click\n * instant-starts). The resolved agent is preselected, so \"open → Start\" matches the\n * instant path while keeping the co-agent (and, for authorized users, voice-model)\n * choice one click away. Falls through to the instant path when there is nothing to\n * pick from.\n */\n public async onRealtimeOptions(): Promise<void> {\n if (!this.canStartRealtime) {\n return;\n }\n if (this.voicePickerAgents.length > 0) {\n await this.openRealtimeAgentPicker();\n return;\n }\n void this.onStartRealtime();\n }\n\n /** Loads the persisted co-agent preference, then shows the picker (pref preselected). */\n private async openRealtimeAgentPicker(): Promise<void> {\n this.voicePickerDefaultCoAgentId = await this.loadPersistedCoAgentId();\n this.showRealtimeAgentPicker = true;\n }\n\n /** User confirmed an agent (+ optional co-agent / voice model) in the voice picker — start the call. */\n public async onRealtimeAgentPicked(pick: RealtimeAgentPick): Promise<void> {\n this.showRealtimeAgentPicker = false;\n this.persistCoAgentChoice(pick.CoAgentId);\n await this.startRealtimeWithAgent(\n pick.Agent.ID,\n pick.Agent.Name || this.resolveRealtimeAgentName(),\n pick.PreferredModelId,\n pick.CoAgentId,\n BuildRealtimeConfigOverridesJson(pick.PreferredModelId, pick.PreferredVoice),\n pick.RecordingConsent\n );\n }\n\n /**\n * Reads the persisted co-agent preference from `MJ: User Settings` (via\n * `UserInfoEngine`'s cached settings). Defensive: any failure or malformed payload\n * resolves to `null` (Auto — the server's co-agent resolution chain).\n */\n private async loadPersistedCoAgentId(): Promise<string | null> {\n try {\n await UserInfoEngine.Instance.Config();\n const raw = UserInfoEngine.Instance.GetSetting(MessageInputComponent.CoAgentPrefKey);\n if (!raw) {\n return null;\n }\n const parsed = JSON.parse(raw) as { coAgentId?: string | null };\n return typeof parsed.coAgentId === 'string' && parsed.coAgentId.length > 0 ? parsed.coAgentId : null;\n } catch {\n return null;\n }\n }\n\n /** Persists the user's co-agent choice (including explicit \"Auto\" = null) cross-device. */\n private persistCoAgentChoice(coAgentId: string | null): void {\n try {\n UserInfoEngine.Instance.SetSettingDebounced(\n MessageInputComponent.CoAgentPrefKey,\n JSON.stringify({ coAgentId: coAgentId ?? null })\n );\n } catch (error) {\n console.warn('[MessageInput] Failed to persist co-agent preference:', error);\n }\n }\n\n /**\n * Co-agent for the INSTANT start path (plain phone click, no picker): the persisted\n * preference is honored when it's still a valid candidate AND its pairing rows (if\n * any) allow the resolved target. Anything else falls back to `null` — the server's\n * co-agent resolution chain — so a stale/deactivated/incompatible preference can never\n * block the friction-free start (pairings constrain a chosen co-agent; they never\n * mandate one).\n */\n private async resolveInstantCoAgentId(targetAgentId: string): Promise<string | null> {\n const preferred = await this.loadPersistedCoAgentId();\n if (!preferred) {\n return null;\n }\n const isValidCandidate = this.voicePickerCoAgents.some(a => UUIDsEqual(a.ID, preferred));\n if (!isValidCandidate) {\n return null;\n }\n const pairings = await LoadCoAgentPairings(this.ProviderToUse, preferred);\n return PairingsAllowTarget(pairings, targetAgentId) ? preferred : null;\n }\n\n /** User dismissed the voice picker without starting a call. */\n public onRealtimeAgentPickerCancelled(): void {\n this.showRealtimeAgentPicker = false;\n }\n\n /**\n * Shared session-start path for both the immediate (existing conversation)\n * and picker (new conversation / caret options) flows. The agent NAME is passed\n * through to RealtimeSessionService so the chat-area-hosted overlay banner (AgentName$)\n * shows who the call fronts without re-resolving. An explicit voice-model choice\n * (authorization-gated, picker only) rides along as `preferredModelId` — the server\n * uses exactly that model or fails with a clear reason (no silent fallback) — and is\n * mirrored into `configOverridesJson` (`{\"realtime\":{\"modelPreference\":…}}`, the\n * pinned override envelope). An explicit co-agent choice (picker pick or persisted\n * preference) rides along as `coAgentId`.\n *\n * Interactive-channel tools (e.g. the live whiteboard's `Whiteboard_*` set) are NOT\n * passed here — the session service resolves the active channel plugins from the\n * `MJ: AI Agent Channels` registry and aggregates their tool sets at mint itself.\n */\n private async startRealtimeWithAgent(\n agentId: string,\n agentName: string,\n preferredModelId?: string | null,\n coAgentId?: string | null,\n configOverridesJson?: string | null,\n recordingConsent?: boolean | null\n ): Promise<void> {\n try {\n await this.realtimeSession.StartRealtimeSession(\n agentId,\n this.conversationId,\n null,\n agentName,\n preferredModelId ?? null,\n null,\n coAgentId ?? null,\n configOverridesJson ?? null,\n recordingConsent ?? null,\n null,\n // App awareness: the app the session runs in + the live app-context snapshot (where the\n // user is, what they see, capability manifest) — drives the server-side app cascade + the\n // mint-time prompt injection, and seeds the ClientContextChannel's streaming.\n this.applicationId,\n this.appContext as AppContextSnapshot | null\n );\n } catch (error) {\n console.error('Failed to start voice session:', error);\n this.toastService.error('Could not start the voice session.');\n }\n }\n\n /**\n * Focus the message input textarea\n */\n private focusInput(): void {\n // Use setTimeout to ensure DOM is ready\n setTimeout(() => {\n if (this.inputBox) {\n this.inputBox.focus();\n }\n }, 100);\n }\n\n /**\n * Reconnect to in-progress messages for streaming updates via global streaming service.\n * This is called when:\n * 1. Component initializes (ngOnInit)\n * 2. Conversation changes (ngOnChanges)\n * 3. User returns to a conversation with in-progress messages\n * 4. Parent component explicitly triggers reconnection\n */\n public reconnectInProgressMessages(): void {\n if (!this.inProgressMessageIds || this.inProgressMessageIds.length === 0) {\n return;\n }\n\n // Unregister any previously registered callbacks for this component\n this.unregisterAllCallbacks();\n\n // Register new callbacks for each in-progress message\n for (const messageId of this.inProgressMessageIds) {\n // Create callback bound to this message ID\n const callback = this.createMessageProgressCallback(messageId);\n\n // Store reference for cleanup\n this.registeredCallbacks.set(messageId, callback);\n\n // Register with streaming service\n this.streamingService.registerMessageCallback(messageId, callback);\n }\n }\n\n /**\n * Create a progress callback for a specific message ID.\n * This callback will be invoked by the streaming service when progress updates arrive.\n */\n private createMessageProgressCallback(messageId: string): (progress: MessageProgressUpdate) => Promise<void> {\n // Resolve the message once and reuse it for the callback's lifetime: streamed\n // final-response updates arrive per content delta, and re-awaiting the cache on\n // every delta both wastes work and (on a cold cache) races concurrent loads.\n let resolvedMessage: Awaited<ReturnType<DataCacheService['getConversationDetail']>> = null;\n return async (progress: MessageProgressUpdate) => {\n try {\n // Get message from cache (single source of truth)\n const message = (resolvedMessage ??= await this.dataCache.getConversationDetail(messageId, this.currentUser));\n\n if (!message) {\n console.warn(`[StreamingCallback] Message ${messageId} not found in cache`);\n return;\n }\n\n // Skip if already complete or errored\n if (message.Status === 'Complete' || message.Status === 'Error') {\n console.log(`[StreamingCallback] Message ${messageId} is ${message.Status}, ignoring progress update`);\n return;\n }\n\n // Check if message was marked as completed (prevents race condition)\n const completionTime = this.completionTimestamps.get(messageId);\n if (completionTime) {\n console.log(`[StreamingCallback] Message ${messageId} marked complete at ${new Date(completionTime).toISOString()}, ignoring late progress update`);\n return;\n }\n\n // Streamed final-response content: the service accumulates deltas, so\n // progress.streaming.content is always the full reply text so far — assign it.\n // The completion flow (above guards + the 'complete' path) reconciles the\n // bubble with the server-saved final message, so no append/merge is needed here.\n if (progress.streaming) {\n message.Message = progress.streaming.content;\n this.messageSent.emit(message);\n // Keep the tasks dropdown on a stable status line rather than the growing reply text.\n this.activeTasks.updateStatusByConversationDetailId(message.ID, 'Responding…');\n return;\n }\n\n // Default: plain message (used by RunAIAgentResolver and TaskOrchestrator without step info)\n message.Message = progress.message;\n\n // TaskOrchestrator with step info: add formatted header\n // Prefer hierarchical step (e.g., \"2.1.3\") over flat stepCount\n if (progress.resolver === 'TaskOrchestrator') {\n const stepDisplay = progress.metadata?.progress?.hierarchicalStep || progress.stepCount;\n if (stepDisplay != null) {\n message.Message = `**Step ${stepDisplay}**\\n\\n${progress.message}`;\n }\n }\n\n // Server now saves progress - client only updates in-memory and emits for UI\n // (Prevents race condition where client's late save overwrites server's final Status)\n\n // CRITICAL: Emit update to trigger UI refresh\n this.messageSent.emit(message);\n\n // CRITICAL: Update ActiveTasksService to keep the tasks dropdown in sync\n this.activeTasks.updateStatusByConversationDetailId(message.ID, progress.message);\n\n console.log(`[StreamingCallback] Updated message ${messageId}: ${progress.taskName || 'Agent'}`);\n } catch (error) {\n console.error(`[StreamingCallback] Error updating message ${messageId}:`, error);\n }\n };\n }\n\n /**\n * Unregister all callbacks registered by this component.\n * Called during cleanup and when switching conversations.\n */\n private unregisterAllCallbacks(): void {\n if (this.registeredCallbacks.size === 0) {\n return;\n }\n\n console.log(`🧹 Unregistering ${this.registeredCallbacks.size} message callbacks`);\n\n for (const [messageId, callback] of this.registeredCallbacks) {\n this.streamingService.unregisterMessageCallback(messageId, callback);\n }\n\n this.registeredCallbacks.clear();\n }\n\n get canSend(): boolean {\n return !this.disabled && !this.isSending && this.messageText.trim().length > 0;\n }\n\n /**\n * Handle attachments changed from the input box\n */\n onAttachmentsChanged(attachments: PendingAttachment[]): void {\n this.pendingAttachments = attachments;\n }\n\n /**\n * Handle attachment errors from the input box\n */\n onAttachmentError(error: string): void {\n this.toastService.error(error);\n }\n\n /**\n * Handle text submitted from the input box\n */\n async onTextSubmitted(text: string): Promise<void> {\n // Check if we have either text or attachments\n const hasText = text && text.trim().length > 0;\n const hasAttachments = this.pendingAttachments.length > 0;\n\n if (!hasText && !hasAttachments) {\n return;\n }\n\n // In empty state mode, just emit the data and let parent handle conversation creation\n if (this.emptyStateMode) {\n const attachmentsToEmit = [...this.pendingAttachments];\n this.pendingAttachments = [];\n this.messageText = '';\n this.emptyStateSubmit.emit({ text: text?.trim() || '', attachments: attachmentsToEmit });\n return;\n }\n\n this.isSending = true;\n\n // Store attachments locally since we'll clear them after send\n const attachmentsToSave = [...this.pendingAttachments];\n\n try {\n const messageDetail = await this.createMessageDetailFromText(text?.trim() || '');\n\n const saved = await messageDetail.Save();\n\n if (saved) {\n // Save attachments if any were pending\n // Attachments are stored in ConversationDetailAttachment table and loaded\n // separately when building AI messages - no need to add tokens to Message field\n if (attachmentsToSave.length > 0) {\n // Show upload indicator for attachments\n this.isUploadingAttachments = true;\n this.uploadingMessage = `Uploading ${attachmentsToSave.length} attachment${attachmentsToSave.length > 1 ? 's' : ''}...`;\n this.uploadStateChanged.emit({ isUploading: true, message: this.uploadingMessage });\n\n let attachmentRejection: string | null = null;\n try {\n await this.attachmentService.saveAttachments(\n messageDetail.ID,\n attachmentsToSave,\n this.currentUser\n );\n } catch (attachmentError) {\n console.error('Failed to save attachments:', attachmentError);\n attachmentRejection = attachmentError instanceof Error\n ? attachmentError.message\n : 'Some attachments could not be saved';\n } finally {\n this.isUploadingAttachments = false;\n this.uploadStateChanged.emit({ isUploading: false, message: '' });\n }\n\n // Plan §6: when attachments are rejected, the message itself must\n // not go through. Roll back the ConversationDetail and notify the\n // user with the server's rejection message so they can see exactly\n // why and either remove the file or upload a supported one. The\n // text and pending attachments stay in the input so the user can edit.\n if (attachmentRejection) {\n MJNotificationService.Instance?.CreateSimpleNotification(attachmentRejection, 'error', 5000);\n try {\n await messageDetail.Delete();\n } catch (rollbackErr) {\n console.error('Failed to roll back conversation detail after attachment rejection:', rollbackErr);\n }\n this.isSending = false;\n return;\n }\n }\n\n // Clear pending attachments after successful send\n this.pendingAttachments = [];\n\n await this.handleSuccessfulSend(messageDetail);\n } else {\n this.handleSendFailure(messageDetail);\n }\n } catch (error) {\n this.handleSendError(error);\n } finally {\n this.isSending = false;\n }\n }\n\n /**\n * Toggle sticky Plan Mode for THIS conversation (or the pending-new bucket on the\n * new-conversation composer). Writes through {@link PlanModePreference} — the\n * {@link PlanModeEnabled} getter reads the same cached setting, so ALL live composer\n * instances flip together, and the value survives component recreation and sessions\n * until the user turns it off or approves a plan.\n */\n public TogglePlanMode(): void {\n PlanModePreference.Set(this.conversationId, !this.PlanModeEnabled);\n }\n\n async onSend(): Promise<void> {\n if (!this.canSend) return;\n\n this.isSending = true;\n try {\n const messageDetail = await this.createMessageDetail();\n const saved = await messageDetail.Save();\n\n if (saved) {\n await this.handleSuccessfulSend(messageDetail);\n } else {\n this.handleSendFailure(messageDetail);\n }\n } catch (error) {\n this.handleSendError(error);\n } finally {\n this.isSending = false;\n }\n }\n\n /**\n * Send a message with custom text WITHOUT modifying the visible messageText input\n * Used for suggested responses and initial messages from empty state.\n * Also saves any pending attachments.\n *\n * `extraAttachments` is an escape hatch for callers that programmatically\n * attached something via `AddArtifactAttachment` and want to send in the same\n * tick — the `attachmentsChanged` event chain hasn't propagated yet, so\n * `this.pendingAttachments` may not contain the attachment. Pass it in\n * explicitly and we merge + dedupe (by `id`) before saving.\n */\n public async sendMessageWithText(text: string, extraAttachments?: PendingAttachment[]): Promise<boolean> {\n const merged: PendingAttachment[] = (() => {\n if (!extraAttachments || extraAttachments.length === 0) {\n return [...this.pendingAttachments];\n }\n const seen = new Set<string>();\n const out: PendingAttachment[] = [];\n for (const a of [...this.pendingAttachments, ...extraAttachments]) {\n if (seen.has(a.id)) continue;\n seen.add(a.id);\n out.push(a);\n }\n return out;\n })();\n\n const hasText = text && text.trim().length > 0;\n const hasAttachments = merged.length > 0;\n\n if (!hasText && !hasAttachments) {\n return false;\n }\n\n if (this.isSending) {\n return false;\n }\n\n this.isSending = true;\n const attachmentsToSave = merged;\n\n try {\n const detail = await this.dataCache.createConversationDetail(this.currentUser);\n detail.ConversationID = this.conversationId;\n detail.Message = text?.trim() || '';\n detail.Role = 'User';\n detail.UserID = this.currentUser.ID; // Set the user who sent the message\n\n if (this.parentMessageId) {\n detail.ParentID = this.parentMessageId;\n }\n\n const saved = await detail.Save();\n\n if (saved) {\n // Save attachments if any were pending\n if (attachmentsToSave.length > 0) {\n // Show upload indicator for attachments\n this.isUploadingAttachments = true;\n this.uploadingMessage = `Uploading ${attachmentsToSave.length} attachment${attachmentsToSave.length > 1 ? 's' : ''}...`;\n this.uploadStateChanged.emit({ isUploading: true, message: this.uploadingMessage });\n\n let attachmentRejection: string | null = null;\n try {\n await this.attachmentService.saveAttachments(\n detail.ID,\n attachmentsToSave,\n this.currentUser\n );\n } catch (attachmentError) {\n console.error('Failed to save attachments:', attachmentError);\n attachmentRejection = attachmentError instanceof Error\n ? attachmentError.message\n : 'Some attachments could not be saved';\n } finally {\n this.isUploadingAttachments = false;\n this.uploadStateChanged.emit({ isUploading: false, message: '' });\n }\n\n // Plan §6: roll back the message when attachments are rejected so\n // the user sees the rejection clearly instead of the agent answering\n // a question that was supposed to include the file.\n if (attachmentRejection) {\n MJNotificationService.Instance?.CreateSimpleNotification(attachmentRejection, 'error', 5000);\n try {\n await detail.Delete();\n } catch (rollbackErr) {\n console.error('Failed to roll back conversation detail after attachment rejection:', rollbackErr);\n }\n this.isSending = false;\n return false;\n }\n }\n\n // Clear pending attachments after successful send\n this.pendingAttachments = [];\n\n // Also clear the mention editor's content + its own attachments list.\n // The user-initiated send path (MessageInputBoxComponent.onSendClick)\n // calls mentionEditor.clear() — we bypass that path here, so the chips\n // would otherwise stay on screen after the message goes out.\n this.inputBox?.mentionEditor?.clear();\n\n this.messageSent.emit(detail);\n\n const mentionResult = this.parseMentionsFromMessage(detail.Message);\n const isFirstMessage = this.conversationHistory.length === 0;\n await this.routeMessage(detail, mentionResult, isFirstMessage);\n return true;\n } else {\n this.handleSendFailure(detail);\n return false;\n }\n } catch (error) {\n this.handleSendError(error);\n return false;\n } finally {\n this.isSending = false;\n }\n }\n\n /**\n * Creates and configures a new conversation detail message\n */\n private async createMessageDetail(): Promise<MJConversationDetailEntity> {\n const detail = await this.dataCache.createConversationDetail(this.currentUser);\n\n detail.ConversationID = this.conversationId;\n detail.Message = this.messageText.trim();\n detail.Role = 'User';\n detail.UserID = this.currentUser.ID; // Set the user who sent the message\n\n if (this.parentMessageId) {\n detail.ParentID = this.parentMessageId;\n }\n\n return detail;\n }\n\n /**\n * Creates and configures a new conversation detail message from provided text\n */\n private async createMessageDetailFromText(text: string): Promise<MJConversationDetailEntity> {\n const detail = await this.dataCache.createConversationDetail(this.currentUser);\n\n detail.ConversationID = this.conversationId;\n detail.Message = text;\n detail.Role = 'User';\n detail.UserID = this.currentUser.ID; // Set the user who sent the message\n\n if (this.parentMessageId) {\n detail.ParentID = this.parentMessageId;\n }\n\n return detail;\n }\n\n /**\n * Handles successful message send - routes to appropriate agent\n */\n private async handleSuccessfulSend(messageDetail: MJConversationDetailEntity): Promise<void> {\n this.messageSent.emit(messageDetail);\n this.messageText = '';\n\n const mentionResult = this.parseMentionsFromMessage(messageDetail.Message);\n const isFirstMessage = this.conversationHistory.length === 0;\n\n await this.routeMessage(messageDetail, mentionResult, isFirstMessage);\n this.refocusTextarea();\n }\n\n /**\n * Parses mentions from the message for routing decisions\n */\n private parseMentionsFromMessage(message: string): MentionParseResult {\n const mentionResult = this.mentionParser.parseMentions(\n message,\n this.mentionAutocomplete.getAvailableAgents(),\n this.mentionAutocomplete.getAvailableUsers()\n );\n\n return mentionResult;\n }\n\n /**\n * Routes the message to the appropriate agent or Sage based on context.\n * Priority: explicit @mention > prior-agent continuity > embedder-supplied\n * default agent > Sage fallback.\n */\n private async routeMessage(\n messageDetail: MJConversationDetailEntity,\n mentionResult: MentionParseResult,\n isFirstMessage: boolean\n ): Promise<void> {\n // A Plan Mode choice made on the new-conversation composer (no conversation yet) lives in a\n // pending bucket — the FIRST routed message claims it onto the real conversation so the\n // toggle carries across the empty-state → chat-area transition without bleeding into other\n // conversations.\n if (isFirstMessage && messageDetail.ConversationID) {\n PlanModePreference.ClaimPendingNew(messageDetail.ConversationID);\n }\n\n // Snapshot user-requested skills once, before any routing branch, so every invocation path\n // forwards the same set for this message. Derived from the SAVED MESSAGE TEXT via the shared\n // MentionParser (`@{\"type\":\"skill\",…}` JSON mentions — same encoding as @agent/#entity), so the\n // source of truth is the message itself, not composer DOM state. Chip-DOM read is the fallback\n // for any path where the parsed result isn't available.\n this._pendingRequestedSkillIDs = mentionResult.skillMentions?.length\n ? mentionResult.skillMentions.map(m => m.id)\n : this.collectRequestedSkillIDs();\n\n // Priority 1: Direct @mention\n if (mentionResult.agentMention) {\n await this.handleDirectMention(messageDetail, mentionResult.agentMention, isFirstMessage);\n return;\n }\n\n // Priority 2: Check for previous agent with intent check\n const lastAgentId = this.findLastNonSageAgentId();\n if (lastAgentId) {\n await this.handleAgentContinuity(messageDetail, lastAgentId, mentionResult, isFirstMessage);\n return;\n }\n\n // Priority 3: User's per-conversation pinned default agent — sourced\n // from MJConversationEntity.DefaultAgentID. Wins over the embedder's\n // default because it represents an explicit user choice on this\n // conversation (e.g. \"always route to Research Agent for this thread\").\n if (this.conversationDefaultAgentId) {\n await this.handleAgentContinuity(\n messageDetail, this.conversationDefaultAgentId, mentionResult, isFirstMessage,\n );\n return;\n }\n\n // Priority 4: Embedder-supplied default agent. Set by chat surfaces\n // that have a specialist agent for the context (e.g. Form Builder\n // cockpit). Only kicks in when nothing more explicit is present —\n // @mention always wins, conversation continuity always wins. The\n // intent is to skip Sage's default delegation when the embedder\n // already knows what agent owns this conversation.\n if (this.defaultAgentId) {\n await this.handleAgentContinuity(\n messageDetail, this.defaultAgentId, mentionResult, isFirstMessage,\n );\n return;\n }\n\n // Priority 5: Check if Sage was explicitly @mentioned with a config preset\n // If so, treat it like agent continuity so the config preset is preserved\n if (this.converationManagerAgent?.ID) {\n const sageConfigPreset = this.conversationId\n ? await this.agentService.FindConfigurationPresetForAgent(\n this.conversationId,\n this.converationManagerAgent.ID\n )\n : undefined;\n if (sageConfigPreset) {\n // User explicitly @mentioned Sage with a config - use the shared execution helper directly\n // Pass the already-found config preset to avoid redundant history search\n await this.executeRouteWithNaming(\n () => this.executeAgentContinuation(\n messageDetail,\n this.converationManagerAgent!.ID,\n this.converationManagerAgent!.Name || 'Sage',\n messageDetail.ConversationID,\n null, // Sage doesn't use payload continuity\n null, // Sage doesn't use artifact info\n sageConfigPreset // Pass the already-found config preset\n ),\n messageDetail.Message,\n isFirstMessage,\n messageDetail.ConversationID\n );\n return;\n }\n }\n\n // Priority 6: No context - use Sage with default config\n await this.handleNoAgentContext(messageDetail, mentionResult, isFirstMessage);\n }\n\n /**\n * Handles routing when user directly mentions an agent with @\n */\n private async handleDirectMention(\n messageDetail: MJConversationDetailEntity,\n agentMention: Mention,\n isFirstMessage: boolean\n ): Promise<void> {\n // The agentMention already has configurationId from JSON parsing\n // If it wasn't in JSON (legacy format), try to get from chip data\n if (!agentMention.configurationId) {\n const chipData = this.inputBox?.getMentionChipsData() || [];\n const agentChip = chipData.find(chip => chip.id === agentMention.id && chip.type === 'agent');\n if (agentChip?.presetId) {\n agentMention.configurationId = agentChip.presetId;\n }\n }\n\n if (agentMention.configurationId) {\n //console.log(`🎯 Agent mention has configuration ID: ${agentMention.configurationId}`);\n }\n\n await this.executeRouteWithNaming(\n () => this.invokeAgentDirectly(messageDetail, agentMention, messageDetail.ConversationID),\n messageDetail.Message,\n isFirstMessage,\n messageDetail.ConversationID\n );\n }\n\n /**\n * Handles routing when there's a previous non-Sage agent in the conversation.\n *\n * LATENCY OPTIMIZATION (PR #2309 / plans/agent-latency-optimization.md — Opt #1):\n * Previously, this method made a separate LLM call via checkContinuityIntent() to decide\n * whether the user's new message was still directed at the previous agent or should be\n * routed to Sage. That call added ~300ms of latency on every message in a conversation\n * with an active agent — the single largest source of non-inference overhead on the client.\n *\n * The heuristic replacement is simple: if a previous non-Sage agent exists, always continue\n * with it. The user can @mention a different agent (or Sage) to explicitly switch. This is\n * more predictable and eliminates a common source of confusion where the intent check\n * incorrectly rerouted messages away from the active agent.\n *\n * The checkContinuityIntent() method and the underlying checkAgentContinuityIntent() service\n * method are preserved (not deleted) so we can reintroduce intent checking in the future\n * when browser-local inference is fast enough (~20-50ms) to do this without blocking the\n * user. See PR #2309 for the full discussion.\n */\n private async handleAgentContinuity(\n messageDetail: MJConversationDetailEntity,\n lastAgentId: string,\n mentionResult: MentionParseResult,\n isFirstMessage: boolean\n ): Promise<void> {\n // COMMENTED OUT — LLM intent check removed for latency optimization (see JSDoc above).\n // const intentResult = await this.checkContinuityIntent(lastAgentId, messageDetail.Message);\n //\n // if (intentResult.decision === 'YES') {\n // await this.executeRouteWithNaming(\n // () => this.continueWithAgent(\n // messageDetail,\n // lastAgentId,\n // this.conversationId,\n // intentResult.targetArtifactVersionId\n // ),\n // messageDetail.Message,\n // isFirstMessage\n // );\n // } else {\n // await this.executeRouteWithNaming(\n // () => this.processMessageThroughAgent(messageDetail, mentionResult),\n // messageDetail.Message,\n // isFirstMessage\n // );\n // }\n\n // Always continue with the previous agent — user can @mention another agent to switch.\n await this.executeRouteWithNaming(\n () => this.continueWithAgent(\n messageDetail,\n lastAgentId,\n messageDetail.ConversationID,\n undefined // artifact version targeting unavailable without intent check\n ),\n messageDetail.Message,\n isFirstMessage,\n messageDetail.ConversationID\n );\n }\n\n /**\n * Handles routing when there's no previous agent context\n */\n private async handleNoAgentContext(\n messageDetail: MJConversationDetailEntity,\n mentionResult: MentionParseResult,\n isFirstMessage: boolean\n ): Promise<void> {\n await this.executeRouteWithNaming(\n () => this.processMessageThroughAgent(messageDetail, mentionResult),\n messageDetail.Message,\n isFirstMessage,\n messageDetail.ConversationID\n );\n }\n\n /**\n * Finds the last agent ID that isn't Sage\n */\n private findLastNonSageAgentId(): string | null {\n const lastAIMessage = this.conversationHistory\n .slice()\n .reverse()\n .find(msg =>\n msg.Role === 'AI' &&\n msg.AgentID &&\n !UUIDsEqual(msg.AgentID, this.converationManagerAgent?.ID)\n );\n\n return lastAIMessage?.AgentID || null;\n }\n\n /**\n * Checks if message should continue with the previous agent\n * Emits events to show temporary intent checking message in conversation\n */\n private async checkContinuityIntent(agentId: string, message: string) {\n // FAST PATH: If message contains form response syntax, skip the intent check entirely\n // Form responses always continue with the agent that requested the form\n // Don't show \"Analyzing intent...\" message for this obvious case\n if (ConversationUtility.ContainsFormResponse(message)) {\n console.log('✅ Form response detected, skipping intent check UI (fast path)');\n return {\n decision: 'YES' as const,\n reasoning: 'User submitted a form response to the previous agent'\n };\n }\n\n // Emit event to show temporary \"Analyzing intent...\" message in conversation\n this.intentCheckStarted.emit({ conversationId: this.conversationId });\n\n try {\n // The pre-loaded artifact/agent-run maps are no longer passed: they are scoped to the\n // loaded transcript window, and the service now queries for this agent's artifacts so\n // the classifier reasons over the whole conversation. A conversation id is what it\n // needs instead, and without one there is nothing to query.\n if (!this.conversationId) {\n console.warn('⚠️ No conversation id available for intent check');\n return { decision: 'UNSURE' as const, reasoning: 'Conversation not available' };\n }\n\n const intent = await this.agentService.checkAgentContinuityIntent(\n this.conversationId,\n agentId,\n message,\n this.conversationHistory\n );\n return intent;\n } catch (error) {\n console.error('❌ Intent check failed, defaulting to UNSURE:', error);\n return { decision: 'UNSURE' as const, reasoning: 'Intent check failed with error' };\n } finally {\n // Emit event to remove temporary intent checking message\n this.intentCheckCompleted.emit({ conversationId: this.conversationId });\n }\n }\n\n /**\n * Executes a routing function, optionally with conversation naming for first message\n *\n * IMPORTANT: Conversation naming runs asynchronously in the background and does NOT\n * block the agent invocation. This prevents UI blocking if naming times out.\n */\n private async executeRouteWithNaming(\n routeFunction: () => Promise<void>,\n userMessage: string,\n isFirstMessage: boolean,\n conversationId: string\n ): Promise<void> {\n if (isFirstMessage) {\n // Fire conversation naming in background (don't await)\n // This prevents 2+ minute UI blocking if naming times out\n this.nameConversation(userMessage, conversationId);\n\n // Execute route immediately (don't wait for naming)\n await routeFunction();\n } else {\n await routeFunction();\n }\n }\n\n /**\n * Returns focus to the message textarea\n */\n private refocusTextarea(): void {\n setTimeout(() => {\n if (this.inputBox) {\n this.inputBox.focus();\n }\n }, 100);\n }\n\n /**\n * Handles message send failure\n */\n private handleSendFailure(messageDetail: MJConversationDetailEntity): void {\n console.error('Failed to send message:', messageDetail.LatestResult?.Message);\n this.toastService.error('Failed to send message. Please try again.');\n }\n\n /**\n * Handles message send error\n */\n private handleSendError(error: unknown): void {\n console.error('Error sending message:', error);\n this.toastService.error('Error sending message. Please try again.');\n }\n\n /**\n * Create a progress callback for agent execution\n * This callback updates both the active task and the ConversationDetail message\n * IMPORTANT: Filters by agentRunId to prevent cross-contamination when multiple agents run in parallel\n */\n private createProgressCallback(\n conversationDetail: MJConversationDetailEntity,\n agentName: string\n ): AgentExecutionProgressCallback {\n // Use closure to capture the agent run ID from the first progress message\n // This allows us to filter out progress messages from other concurrent agents\n let capturedAgentRunId: string | null = null;\n\n return async (progress) => {\n const metadata = progress.metadata as MessageProgressMetadata | undefined;\n const progressAgentRun = metadata?.agentRun;\n const progressAgentRunId = metadata?.agentRun?.ID || metadata?.agentRunId;\n\n // Capture the agent run ID from the first progress message\n if (!capturedAgentRunId && progressAgentRunId) {\n capturedAgentRunId = progressAgentRunId;\n }\n\n // Filter out progress messages from other concurrent agents\n // This prevents cross-contamination when multiple agents run in parallel\n if (capturedAgentRunId && progressAgentRunId && progressAgentRunId !== capturedAgentRunId) {\n return;\n }\n\n // Format progress message with visual indicator\n const progressText = progress.message;\n\n // Update the active task with progress details (if it exists)\n this.activeTasks.updateStatusByConversationDetailId(conversationDetail.ID, progressText);\n\n // Update the ConversationDetail message in real-time\n try {\n if (conversationDetail) {\n // Check 1: Skip if message is already complete or errored\n if (conversationDetail.Status === 'Complete' || conversationDetail.Status === 'Error') {\n return;\n }\n\n // Check 2: Skip if message was marked as completed (prevents race condition)\n // Once a message is marked complete, we reject ALL further progress updates\n const completionTime = this.completionTimestamps.get(conversationDetail.ID);\n if (completionTime) {\n return;\n }\n\n // CRITICAL FIX: Emit FULL agent run object for incremental updates\n // This contains live timestamps, status, and other fields that change during execution\n if (progressAgentRun || progressAgentRunId) {\n this.agentRunUpdate.emit({\n conversationId: conversationDetail.ConversationID,\n conversationDetailId: conversationDetail.ID,\n agentRun: progressAgentRun,\n agentRunId: progressAgentRunId\n });\n } else if (progressAgentRunId && !capturedAgentRunId) {\n // Fallback: If we don't have the full object but have the ID, emit agentRunDetected\n // This will trigger a database query to load the agent run\n this.agentRunDetected.emit({\n conversationId: conversationDetail.ConversationID,\n conversationDetailId: conversationDetail.ID,\n agentRunId: progressAgentRunId\n });\n }\n\n if (conversationDetail.Status === 'In-Progress') {\n conversationDetail.Message = progressText;\n // Server now saves progress - client only updates in-memory and emits for UI\n // (Prevents race condition where client's late save overwrites server's final Status)\n this.messageSent.emit(conversationDetail);\n }\n }\n } catch (error) {\n console.warn('Failed to update progress in ConversationDetail:', error);\n }\n };\n }\n\n /**\n * Process the message through agents (multi-stage: Sage -> possible sub-agent)\n * Only called when there's no @mention and no implicit agent context\n */\n private async processMessageThroughAgent(\n userMessage: MJConversationDetailEntity,\n mentionResult: MentionParseResult\n ): Promise<void> {\n let taskId: string | null = null;\n let conversationManagerMessage: MJConversationDetailEntity | null = null;\n\n // CRITICAL: Capture conversationId from user message at start\n // This prevents race condition when user switches conversations during async processing\n const conversationId = userMessage.ConversationID;\n\n try {\n // Create AI message for Sage BEFORE invoking\n conversationManagerMessage = await this.dataCache.createConversationDetail(this.currentUser);\n\n conversationManagerMessage.ConversationID = conversationId;\n conversationManagerMessage.Role = 'AI';\n conversationManagerMessage.Message = '⏳ Starting...';\n conversationManagerMessage.ParentID = userMessage.ID;\n conversationManagerMessage.Status = 'In-Progress';\n conversationManagerMessage.HiddenToUser = false;\n // Use the preloaded Sage agent instead of looking it up\n if (this.converationManagerAgent?.ID) {\n conversationManagerMessage.AgentID = this.converationManagerAgent.ID;\n }\n\n await conversationManagerMessage.Save();\n this.messageSent.emit(conversationManagerMessage);\n\n // Use Sage to evaluate and route\n // Stage 1: Sage evaluates the message\n taskId = this.activeTasks.add({\n agentName: 'Sage',\n status: 'Evaluating message...',\n relatedMessageId: userMessage.ID,\n conversationDetailId: conversationManagerMessage.ID,\n conversationId,\n conversationName: this.conversationName\n });\n\n // ── PR 2c follow-up: Before/After cancelable event wiring ──\n // Emit beforeAgentTurn so consumers can veto the turn (rate-limit, guardrail,\n // confirm-dialog, etc.). Cancel propagates synchronously through the chat-area\n // re-emit binding, so by the time .emit() returns, event.Cancel reflects every\n // subscriber's final answer.\n const beforeEvent = new BeforeAgentTurnEventArgs(\n conversationId,\n userMessage.Message ?? '',\n this.applicationId\n );\n this.beforeAgentTurn.emit(beforeEvent);\n if (beforeEvent.Cancel) {\n // Mark the conversation-manager message as canceled + clear its task so the\n // UI doesn't show a forever-pending spinner. afterAgentTurn is NOT emitted.\n await this.updateConversationDetail(\n conversationManagerMessage,\n beforeEvent.CancelReason ?? '⛔ Turn canceled before agent invocation',\n 'Error'\n );\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n this.cleanupCompletionTimestamp(conversationManagerMessage.ID);\n if (taskId) {\n this.activeTasks.remove(taskId);\n taskId = null;\n }\n return;\n }\n\n const result = await this.agentService.processMessage(\n conversationId,\n userMessage,\n this.conversationHistory,\n conversationManagerMessage.ID,\n this.createProgressCallback(conversationManagerMessage, 'Sage'),\n this.appContext,\n this.PlanModeEnabled, // per-request Plan Mode toggle\n this._pendingRequestedSkillIDs, // user-requested skills (/skill mentions)\n );\n\n // Emit afterAgentTurn on the happy path only — the error/failure branch\n // immediately below handles its own cleanup and skips this emit.\n if (result && result.success) {\n this.afterAgentTurn.emit(new AfterAgentTurnEventArgs(\n conversationId,\n (result.agentRun?.ID ?? '') as string,\n result as unknown as import('@memberjunction/ai-core-plus').ExecuteAgentResult\n ));\n }\n\n // Task will be removed automatically in markMessageComplete()\n // DO NOT remove here - agent may still be streaming/processing\n taskId = null; // Clear reference but don't remove from service\n\n if (!result || !result.success) {\n await this.applyAgentFailureToDetail(\n conversationManagerMessage,\n userMessage,\n this.converationManagerAgent?.Name || 'Sage',\n result,\n 'failed',\n );\n console.warn('⚠️ Sage failed:', agentFailureMessage(result, 'Agent evaluation failed'));\n this.cleanupCompletionTimestamp(conversationManagerMessage.ID);\n return;\n }\n\n // Stage 2: Check for task graph (multi-step orchestration)\n if (result.payload?.taskGraph) {\n await this.handleTaskGraphExecution(userMessage, result, conversationId, conversationManagerMessage);\n // Remove CM from active tasks\n if (taskId) {\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n }\n }\n // Stage 3: Check for sub-agent invocation (single-step delegation)\n else if (result.agentRun.FinalStep === 'Success' && result.payload?.invokeAgent) {\n // Reuse the existing conversationManagerMessage instead of creating new ones\n await this.handleSubAgentInvocation(userMessage, result, conversationId, conversationManagerMessage);\n // Remove CM from active tasks\n if (taskId) {\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n }\n }\n // Stage 4: Direct chat response from Agent\n else if (result.agentRun.FinalStep === 'Chat' && result.agentRun.Message) {\n // Normal chat response\n // use update helper to ensure that if there is a race condition with more streaming updates we don't allow that to override this final message\n // Note: updateConversationDetail will call markMessageComplete() for us\n await this.updateConversationDetail(conversationManagerMessage, result.agentRun.Message, 'Complete', result);\n\n // Handle artifacts if any (but NOT task graphs - those are intermediate work products)\n // Server already created artifacts - just emit event to trigger UI reload\n if (result.payload && Object.keys(result.payload).length > 0) {\n this.emitArtifactReload(conversationManagerMessage);\n this.messageSent.emit(conversationManagerMessage);\n }\n\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n\n // Remove CM from active tasks\n if (taskId) {\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n }\n\n // Clean up completion timestamp after delay\n this.cleanupCompletionTimestamp(conversationManagerMessage.ID);\n }\n // Stage 5: Silent observation - but check for message content first\n else {\n // Check if there's a message to display even without payload/taskGraph\n if (result.agentRun.Message) {\n // Mark message as completing BEFORE setting final content\n this.markMessageComplete(conversationManagerMessage);\n\n conversationManagerMessage.HiddenToUser = false;\n\n // use update helper to ensure that if there is a race condition with more streaming updates we don't allow that to override this final message\n await this.updateConversationDetail(conversationManagerMessage, result.agentRun.Message, 'Complete', result);\n\n this.messageSent.emit(conversationManagerMessage);\n\n // Clean up completion timestamp after delay\n this.cleanupCompletionTimestamp(conversationManagerMessage.ID);\n } else {\n // Mark message as completing\n this.markMessageComplete(conversationManagerMessage);\n\n // Hide the Sage message\n conversationManagerMessage.HiddenToUser = true;\n\n // use update helper to ensure that if there is a race condition with more streaming updates we don't allow that to override this final message\n await this.updateConversationDetail(conversationManagerMessage, conversationManagerMessage.Message, 'Complete', result);\n\n this.messageSent.emit(conversationManagerMessage);\n\n await this.handleSilentObservation(userMessage, conversationId);\n\n // Clean up completion timestamp after delay\n this.cleanupCompletionTimestamp(conversationManagerMessage.ID);\n }\n\n // Remove CM from active tasks\n if (taskId) {\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n }\n }\n\n } catch (error) {\n console.error('❌ Error processing message through agents:', error);\n\n // Update conversationManagerMessage status to Error\n if (conversationManagerMessage && conversationManagerMessage.ID) {\n // Use updateConversationDetail to ensure task cleanup\n conversationManagerMessage.Error = String(error);\n await this.updateConversationDetail(conversationManagerMessage, `❌ Error: ${String(error)}`, 'Error');\n\n // Clean up completion timestamp\n this.cleanupCompletionTimestamp(conversationManagerMessage.ID);\n }\n\n // Mark user message as complete\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n\n // Clean up active task\n if (taskId) {\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n }\n }\n }\n\n /** Detaches the progress callback for one message — used when submission never starts. */\n private releaseProgressCallback(messageId: string): void {\n const callback = this.registeredCallbacks.get(messageId);\n if (callback) {\n this.streamingService.unregisterMessageCallback(messageId, callback);\n this.registeredCallbacks.delete(messageId);\n }\n }\n\n /**\n * Submits a task graph to the server and returns — the client no longer drives execution.\n *\n * This used to call the `ExecuteTaskGraph` mutation and await the ENTIRE workflow inside one\n * long-lived GraphQL request. That had three unfixable problems: a page reload lost the awaited\n * promise (leaving a workflow running with nobody watching), a server restart orphaned every\n * in-flight task, and no other channel could reach the substrate at all.\n *\n * Now submission returns as soon as the graph is durable and the server-side dispatcher executes\n * it. The client is purely an observer: progress arrives over the existing PubSub frames, and\n * because the work lives in Task rows rather than in a promise, a reload can re-attach to a\n * workflow already in flight.\n *\n * Single-task graphs are no longer special-cased here. The old client-side fork ran them through\n * a different code path entirely; they now submit like any other graph, and the decision about\n * whether a one-node graph is worth durable machinery moves server-side where it can be recorded.\n */\n private async handleTaskGraphExecution(\n userMessage: MJConversationDetailEntity,\n managerResult: ExecuteAgentResult,\n conversationId: string,\n conversationManagerMessage: MJConversationDetailEntity\n ): Promise<void> {\n // `payload` is untyped by construction (an agent's payload shape is agent-specific), so pin the\n // graph to the operation's own input contract at the boundary rather than letting it stay loose.\n const taskGraph: TaskGraphSubmitInput['spec'] | undefined = managerResult.payload?.taskGraph;\n if (!taskGraph) return;\n\n const workflowName = taskGraph.workflowName || 'Workflow';\n const reasoning = taskGraph.reasoning || 'Executing multi-step workflow';\n const taskCount = Array.isArray(taskGraph.tasks) ? taskGraph.tasks.length : 0;\n\n // A message the user can watch. Progress frames from the dispatcher land against this ID.\n const taskExecutionMessage = await this.dataCache.createConversationDetail(this.currentUser);\n taskExecutionMessage.ConversationID = conversationId;\n taskExecutionMessage.Role = 'AI';\n taskExecutionMessage.Message = `⏳ **${workflowName}**\\n\\n${reasoning}\\n\\nSubmitting ${taskCount} task(s)…`;\n taskExecutionMessage.ParentID = conversationManagerMessage.ID;\n taskExecutionMessage.Status = 'In-Progress';\n taskExecutionMessage.HiddenToUser = false;\n await taskExecutionMessage.Save();\n this.messageSent.emit(taskExecutionMessage);\n\n const callback = this.createMessageProgressCallback(taskExecutionMessage.ID);\n this.registeredCallbacks.set(taskExecutionMessage.ID, callback);\n this.streamingService.registerMessageCallback(taskExecutionMessage.ID, callback);\n\n try {\n // `TaskGraph.Submit` is a Remote Operation, not a bespoke mutation: the same call site is\n // reachable from MCP, an Action wrapper, and this UI. `Execute` marshals over the generic\n // `ExecuteRemoteOperation` transport, so there is no hand-written GraphQL document here.\n const result = await new TaskGraphSubmitOperation().Execute({\n spec: taskGraph,\n environmentID: MJEnvironmentEntityExtended.DefaultEnvironmentID,\n conversationDetailID: taskExecutionMessage.ID,\n });\n\n if (result.Success && result.Output?.success) {\n // Deliberately NOT \"completed\" — submission means the work is durable and running, and\n // claiming completion here is exactly the lie the old await-everything path told when it\n // returned early. The dispatcher's progress frames update this message as tasks finish.\n await this.updateConversationDetail(\n taskExecutionMessage,\n `▶️ **${workflowName}** started — ${taskCount} task(s) running.`,\n 'In-Progress'\n );\n } else {\n const errorMsg = result.Output?.errorMessage || result.ErrorMessage || 'Unknown error';\n console.error('Task graph submission rejected:', errorMsg);\n taskExecutionMessage.Error = errorMsg;\n await this.updateConversationDetail(taskExecutionMessage, `❌ **${workflowName}** rejected: ${errorMsg}`, 'Error');\n this.releaseProgressCallback(taskExecutionMessage.ID);\n }\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n console.error('Task graph submission failed:', error);\n taskExecutionMessage.Error = msg;\n await this.updateConversationDetail(taskExecutionMessage, `❌ **${workflowName}** failed to submit: ${msg}`, 'Error');\n this.releaseProgressCallback(taskExecutionMessage.ID);\n }\n }\n\n\n\n protected async updateConversationDetail(convoDetail: MJConversationDetailEntity, message: string, status: 'In-Progress' | 'Complete' | 'Error', result?: ExecuteAgentResult): Promise<void> {\n // Mark as completing FIRST if status is Complete or Error\n // This ensures task cleanup happens even if we return early due to guard clause\n if (status === 'Complete' || status === 'Error') {\n this.markMessageComplete(convoDetail);\n }\n\n // Race condition guard: Before writing Error *or* In-Progress, reload from DB.\n // The In-Progress disconnect branch is the path that most needs this: a dropped\n // socket leaves the in-memory Status stale (still In-Progress from creation), and\n // without a reload we can overwrite a server Complete with the \"still running\"\n // placeholder. If the server already finished, emit that record and stop the timer.\n if ((status === 'Error' || status === 'In-Progress') && convoDetail.ID) {\n await convoDetail.Load(convoDetail.ID);\n if (convoDetail.Status === 'Complete' || convoDetail.Status === 'Error') {\n this.markMessageComplete(convoDetail);\n this.messageSent.emit(convoDetail);\n return;\n }\n }\n\n // Guard clause: Don't re-save if already complete/errored (prevents duplicate saves)\n // Task has already been removed by markMessageComplete() above\n if (convoDetail.Status === 'Complete' || convoDetail.Status === 'Error') {\n return; // Already complete, no need to save again\n }\n\n const maxAttempts = 2;\n let attempts = 0, done = false;\n while (attempts < maxAttempts && !done) {\n // Set response form and command fields before saving\n if (result?.responseForm) {\n convoDetail.ResponseForm = JSON.stringify(result.responseForm);\n }\n if (result?.actionableCommands) {\n convoDetail.ActionableCommands = JSON.stringify(result.actionableCommands);\n }\n if (result?.automaticCommands) {\n convoDetail.AutomaticCommands = JSON.stringify(result.automaticCommands);\n }\n\n convoDetail.Message = message;\n convoDetail.Status = status;\n\n await convoDetail.Save();\n\n if (convoDetail.Message === message && convoDetail.Status === status) {\n done = true;\n this.messageSent.emit(convoDetail);\n }\n else {\n console.warn(` ⚠️ ConversationDetail update attempt ${attempts + 1} did not persist. ${attempts + 1 < maxAttempts ? 'Retrying...' : 'Giving up.'}`);\n }\n attempts++;\n }\n\n // Clean up completion timestamp after delay\n if (status === 'Complete' || status === 'Error') {\n this.cleanupCompletionTimestamp(convoDetail.ID);\n }\n }\n\n /**\n * Load previous payload for an agent from its most recent OUTPUT artifact.\n *\n * Resolved by QUERY rather than by scanning `conversationHistory`. That array is now the\n * loaded transcript WINDOW, not the full conversation, so a scan silently misses any\n * artifact below the window's oldest row — and a null payload is a legal agent input, so\n * the miss surfaces as the agent regenerating from scratch instead of modifying. Covers\n * system-visibility artifacts (Agent Manager and friends) for free: the query filters on\n * Direction, not on Visibility.\n */\n private async loadPreviousPayloadForAgent(agentId: string): Promise<{\n payload: Record<string, unknown> | null;\n artifactInfo: {artifactId: string; versionId: string; versionNumber: number} | null;\n }> {\n if (!this.conversationId) {\n return { payload: null, artifactInfo: null };\n }\n\n const source = await this.agentService.FindLatestAgentOutputVersion(this.conversationId, agentId);\n if (!source || source.payload == null) {\n console.log(`📦 No previous payload found for agent ${agentId}`);\n return { payload: null, artifactInfo: null };\n }\n\n console.log(`📦 Loaded previous payload for agent ${agentId} from artifact version ${source.versionId}`);\n return {\n payload: source.payload,\n artifactInfo: {\n artifactId: source.artifactId,\n versionId: source.versionId,\n versionNumber: source.versionNumber\n }\n };\n }\n\n /**\n * Handle sub-agent invocation based on Sage's payload\n * Reuses the existing conversationManagerMessage to avoid creating multiple records\n */\n private async handleSubAgentInvocation(\n userMessage: MJConversationDetailEntity,\n managerResult: ExecuteAgentResult,\n conversationId: string,\n conversationManagerMessage: MJConversationDetailEntity\n ): Promise<void> {\n const payload = managerResult.payload;\n const agentName = payload.invokeAgent;\n const reasoning = payload.reasoning || 'Delegating to specialist agent';\n\n // Now create a NEW message for the sub-agent execution\n let agentResponseMessage: MJConversationDetailEntity | null = null;\n try {\n // Look up the agent to get its ID\n const agent = AIEngineBase.Instance.Agents.find(a => a.Name === agentName);\n\n // Create AI response message BEFORE invoking agent (for duration tracking)\n agentResponseMessage = await this.dataCache.createConversationDetail(this.currentUser);\n\n agentResponseMessage.ConversationID = conversationId;\n agentResponseMessage.Role = 'AI';\n agentResponseMessage.Message = '⏳ Starting...'; // Initial message\n agentResponseMessage.ParentID = conversationManagerMessage.ID; // Thread under delegation message\n agentResponseMessage.Status = 'In-Progress';\n agentResponseMessage.HiddenToUser = false;\n // Set AgentID immediately for proper attribution\n if (agent?.ID) {\n agentResponseMessage.AgentID = agent.ID;\n }\n\n // Save the record to establish __mj_CreatedAt timestamp\n await agentResponseMessage.Save();\n this.messageSent.emit(agentResponseMessage);\n\n // Add sub-agent to active tasks\n const newTaskId = this.activeTasks.add({\n agentName: agentName,\n status: 'Starting...',\n relatedMessageId: userMessage.ID,\n conversationDetailId: agentResponseMessage.ID,\n conversationId,\n conversationName: this.conversationName\n });\n\n // Load previous payload if agent has been invoked before\n const { payload: previousPayload, artifactInfo } = agent?.ID\n ? await this.loadPreviousPayloadForAgent(agent.ID)\n : { payload: null, artifactInfo: null };\n\n // Find configuration preset from previous @mention in conversation history\n const configurationPresetId = agent?.ID\n ? await this.agentService.FindConfigurationPresetForAgent(conversationId, agent.ID)\n : undefined;\n\n // Invoke the sub-agent with progress callback\n const subResult = await this.agentService.invokeSubAgent(\n agentName,\n conversationId,\n userMessage,\n this.conversationHistory,\n reasoning,\n agentResponseMessage.ID,\n previousPayload, // Pass previous payload for continuity\n this.createProgressCallback(agentResponseMessage, agentName),\n artifactInfo?.artifactId,\n artifactInfo?.versionId,\n configurationPresetId, // Pass configuration from previous @mention for continuity\n this.appContext, // Embedder-supplied app/form context\n this.PlanModeEnabled, // per-request Plan Mode toggle\n this._pendingRequestedSkillIDs, // user-requested skills (/skill mentions)\n );\n\n // Task will be removed automatically in markMessageComplete() when status changes to Complete/Error\n // DO NOT remove here - allows UI to show task during entire execution\n\n if (subResult && subResult.success) {\n // Update the response message with agent result\n // Store the agent ID for display\n if (subResult.agentRun.AgentID) {\n agentResponseMessage.AgentID = subResult.agentRun.AgentID;\n }\n\n await this.updateConversationDetail(agentResponseMessage, subResult.agentRun?.Message || `✅ **${agentName}** completed`, 'Complete', subResult);\n\n // Always emit artifactCreated to trigger UI reload — the server may have created\n // artifacts even when the result payload is empty (e.g., remote stage server).\n // onArtifactCreated will reload from DB and discover any artifacts that exist.\n this.emitArtifactReload(agentResponseMessage);\n this.messageSent.emit(agentResponseMessage);\n\n // Mark user message as complete\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n } else {\n // A post-ACK disconnect means the first run may still be executing on this\n // detail — do not start a second run on the same conversationDetailId.\n if (agentFailureDisposition(subResult).status === 'In-Progress') {\n await this.applyAgentFailureToDetail(agentResponseMessage, userMessage, agentName, subResult);\n return;\n }\n\n // Sub-agent failed - attempt auto-retry once\n console.log(`⚠️ ${agentName} failed, attempting auto-retry...`);\n\n await this.updateConversationDetail(conversationManagerMessage, `👉 **${agentName}** will handle this request...\\n\\n⚠️ First attempt failed, retrying...`, conversationManagerMessage.Status);\n\n // Update the existing agentResponseMessage to show retry status\n await this.updateConversationDetail(agentResponseMessage, \"Retrying...\", agentResponseMessage.Status);\n\n // Retry the sub-agent (reuse previously loaded payload and config from first attempt)\n const retryResult = await this.agentService.invokeSubAgent(\n agentName,\n conversationId,\n userMessage,\n this.conversationHistory,\n reasoning,\n agentResponseMessage.ID,\n previousPayload, // Pass same payload as first attempt\n this.createProgressCallback(agentResponseMessage, `${agentName} (retry)`),\n artifactInfo?.artifactId,\n artifactInfo?.versionId,\n configurationPresetId, // Pass same config as first attempt\n this.appContext, // Embedder-supplied app/form context\n this.PlanModeEnabled, // per-request Plan Mode toggle\n this._pendingRequestedSkillIDs, // user-requested skills (/skill mentions)\n );\n\n if (retryResult && retryResult.success) {\n // Retry succeeded - update the same message\n if (retryResult.agentRun.AgentID) {\n agentResponseMessage.AgentID = retryResult.agentRun.AgentID;\n }\n\n await this.updateConversationDetail(agentResponseMessage, retryResult.agentRun?.Message || `✅ **${agentName}** completed`, 'Complete', retryResult);\n\n // Always emit artifactCreated to trigger UI reload (same as initial attempt)\n this.emitArtifactReload(agentResponseMessage);\n this.messageSent.emit(agentResponseMessage);\n\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n } else {\n // Retry also failed — terminate the agent bubble (the red-pill timer lives here),\n // not only the Sage delegation message.\n await this.applyAgentFailureToDetail(\n agentResponseMessage,\n userMessage,\n agentName,\n retryResult,\n 'failed after retry',\n );\n const retryDisposition = agentFailureDisposition(retryResult);\n if (retryDisposition.status === 'Error') {\n conversationManagerMessage.Error = retryDisposition.message;\n await this.updateConversationDetail(\n conversationManagerMessage,\n `❌ **${agentName}** failed after retry\\n\\n${retryDisposition.message}`,\n 'Error',\n );\n }\n }\n }\n } catch (error) {\n console.error(`❌ Error invoking sub-agent ${agentName}:`, error);\n\n const catchResult = {\n success: false,\n errorMessage: error instanceof Error ? error.message : String(error),\n } as ExecuteAgentResult;\n if (agentResponseMessage) {\n await this.applyAgentFailureToDetail(agentResponseMessage, userMessage, agentName, catchResult);\n } else {\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n }\n const catchDisposition = agentFailureDisposition(catchResult);\n if (catchDisposition.status === 'Error') {\n conversationManagerMessage.Error = catchDisposition.message;\n await this.updateConversationDetail(\n conversationManagerMessage,\n `❌ **${agentName}** encountered an error\\n\\n${catchDisposition.message}`,\n 'Error',\n );\n }\n }\n }\n\n /**\n * Handle silent observation - when Sage stays silent,\n * check if we should continue with the last agent for iterative refinement\n */\n private async handleSilentObservation(\n userMessage: MJConversationDetailEntity,\n conversationId: string\n ): Promise<void> {\n // Find the last AI message (excluding Sage) in the conversation history\n const lastAIMessage = this.conversationHistory\n .slice()\n .reverse()\n .find(msg =>\n msg.Role === 'AI' &&\n msg.AgentID &&\n !UUIDsEqual(msg.AgentID, this.converationManagerAgent?.ID)\n );\n\n if (!lastAIMessage || !lastAIMessage.AgentID) {\n // No previous specialist agent - just mark user message as complete\n console.log('🔇 No previous specialist agent found - marking complete');\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n return;\n }\n\n // Load the agent entity to get its name\n const previousAgent = AIEngineBase.Instance.Agents.find(a => UUIDsEqual(a.ID, lastAIMessage.AgentID));\n if (!previousAgent) {\n console.warn('⚠️ Could not load previous agent - marking complete');\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n return;\n }\n\n const agentName = previousAgent.Name || 'Agent';\n\n let previousPayload: Record<string, unknown> | null = null;\n let previousArtifactInfo: {artifactId: string; versionId: string; versionNumber: number} | null = null;\n\n // Resolved by QUERY, not from the window's artifact maps: `lastAIMessage` can sit inside\n // the loaded window while its artifact does not, and this path silently degrades to a\n // null payload when the lookup misses.\n const source = await this.agentService.FindLatestAgentOutputVersion(\n conversationId, lastAIMessage.AgentID\n );\n if (source && source.payload != null) {\n previousPayload = source.payload;\n previousArtifactInfo = {\n artifactId: source.artifactId,\n versionId: source.versionId,\n versionNumber: source.versionNumber\n };\n console.log('📦 Loaded previous OUTPUT artifact as payload for continuity', previousArtifactInfo);\n }\n\n // Create status message showing agent continuity\n const statusMessage = await this.dataCache.createConversationDetail(this.currentUser);\n\n statusMessage.ConversationID = conversationId;\n statusMessage.Role = 'AI';\n statusMessage.Message = `Continuing with **${agentName}** for refinement...`;\n statusMessage.ParentID = userMessage.ID;\n statusMessage.Status = 'Complete';\n statusMessage.HiddenToUser = false;\n statusMessage.AgentID = this.converationManagerAgent?.ID || null;\n\n await statusMessage.Save();\n this.messageSent.emit(statusMessage);\n\n // Add agent to active tasks\n const taskId = this.activeTasks.add({\n agentName: agentName,\n status: 'Processing refinement...',\n relatedMessageId: userMessage.ID,\n conversationDetailId: statusMessage.ID,\n conversationId,\n conversationName: this.conversationName\n });\n\n try {\n // Invoke the agent with the previous payload\n const continuityResult = await this.agentService.invokeSubAgent(\n agentName,\n conversationId,\n userMessage,\n this.conversationHistory,\n 'Continuing previous work based on user feedback',\n statusMessage.ID,\n previousPayload,\n this.createProgressCallback(statusMessage, agentName),\n previousArtifactInfo?.artifactId,\n previousArtifactInfo?.versionId,\n undefined, // configurationPresetId not used in this path\n this.appContext, // Embedder-supplied app/form context\n this.PlanModeEnabled, // per-request Plan Mode toggle\n this._pendingRequestedSkillIDs, // user-requested skills (/skill mentions)\n );\n\n // Remove from active tasks\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n\n if (continuityResult && continuityResult.success) {\n // Create response message\n const agentResponseMessage = await this.dataCache.createConversationDetail(this.currentUser);\n\n agentResponseMessage.ConversationID = conversationId;\n agentResponseMessage.Role = 'AI';\n agentResponseMessage.Message = continuityResult.agentRun?.Message || `✅ **${agentName}** completed refinement`;\n agentResponseMessage.ParentID = statusMessage.ID;\n agentResponseMessage.Status = 'Complete';\n agentResponseMessage.HiddenToUser = false;\n agentResponseMessage.AgentID = lastAIMessage.AgentID;\n\n await agentResponseMessage.Save();\n this.messageSent.emit(agentResponseMessage);\n\n // Server created artifacts (handles versioning automatically) - emit event to trigger UI reload\n if (continuityResult.payload && Object.keys(continuityResult.payload).length > 0) {\n this.emitArtifactReload(agentResponseMessage);\n console.log('🎨 Server created artifact (versioned) from agent continuity');\n this.messageSent.emit(agentResponseMessage);\n }\n\n // Mark user message as complete\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n } else {\n await this.applyAgentFailureToDetail(statusMessage, userMessage, agentName, continuityResult, 'failed during refinement');\n }\n } catch (error) {\n console.error(`❌ Error in agent continuity with ${agentName}:`, error);\n\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n\n await this.applyAgentFailureToDetail(\n statusMessage,\n userMessage,\n agentName,\n { success: false, errorMessage: error instanceof Error ? error.message : String(error) } as ExecuteAgentResult,\n 'encountered an error',\n );\n }\n }\n \n\n /**\n * Invoke an agent directly when mentioned with @ symbol\n * Bypasses Sage completely - no status messages\n */\n private async invokeAgentDirectly(\n userMessage: MJConversationDetailEntity,\n agentMention: Mention,\n conversationId: string\n ): Promise<void> {\n const agentName = agentMention.name;\n\n // Add agent to active tasks\n const taskId = this.activeTasks.add({\n agentName: agentName,\n status: 'Processing...',\n relatedMessageId: userMessage.ID,\n conversationDetailId: userMessage.ID,\n conversationId,\n conversationName: this.conversationName\n });\n\n // Declare agentResponseMessage outside try block so it's accessible in catch\n let agentResponseMessage: MJConversationDetailEntity | undefined = undefined;\n\n try {\n // User message is sent successfully - mark complete immediately\n // (No UI uses User message 'In-Progress' - only AI messages need that status)\n userMessage.Status = 'Complete';\n await userMessage.Save();\n this.messageSent.emit(userMessage);\n\n // Look up the agent to get its ID\n const agent = AIEngineBase.Instance.Agents.find(a => a.Name === agentName);\n\n // Create AI response message BEFORE invoking agent (for duration tracking)\n agentResponseMessage = await this.dataCache.createConversationDetail(this.currentUser);\n\n agentResponseMessage.ConversationID = conversationId;\n agentResponseMessage.Role = 'AI';\n agentResponseMessage.Message = '⏳ Starting...'; // Initial message\n agentResponseMessage.ParentID = userMessage.ID;\n agentResponseMessage.Status = 'In-Progress';\n agentResponseMessage.HiddenToUser = false;\n // Set AgentID immediately for proper attribution\n if (agent?.ID) {\n agentResponseMessage.AgentID = agent.ID;\n }\n\n // Save the record to establish __mj_CreatedAt timestamp\n await agentResponseMessage.Save();\n this.messageSent.emit(agentResponseMessage);\n\n // Load previous payload if agent has been invoked before\n const { payload: previousPayload, artifactInfo } = agent?.ID\n ? await this.loadPreviousPayloadForAgent(agent.ID)\n : { payload: null, artifactInfo: null };\n\n // Invoke the agent directly\n const result = await this.agentService.invokeSubAgent(\n agentName,\n conversationId,\n userMessage,\n this.conversationHistory,\n `User mentioned agent directly with @${agentName}`,\n agentResponseMessage.ID,\n previousPayload, // Pass previous payload for continuity\n this.createProgressCallback(agentResponseMessage, agentName),\n artifactInfo?.artifactId,\n artifactInfo?.versionId,\n agentMention.configurationId, // Pass configuration preset ID\n this.appContext, // Embedder-supplied app/form context\n this.PlanModeEnabled, // per-request Plan Mode toggle\n this._pendingRequestedSkillIDs, // user-requested skills (/skill mentions)\n );\n\n // Remove from active tasks\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n\n if (result && result.success) {\n if (result.agentRun.AgentID) {\n agentResponseMessage.AgentID = result.agentRun.AgentID;\n }\n\n // Multi-stage response handling (same logic as ambient Sage)\n // Stage 1: Check for task graph (multi-step orchestration)\n if (result.payload?.taskGraph) {\n console.log('📋 Task graph detected from @mention, starting task orchestration');\n await this.handleTaskGraphExecution(userMessage, result, conversationId, agentResponseMessage);\n }\n // Stage 2: Check for sub-agent invocation (single-step delegation)\n else if (result.agentRun.FinalStep === 'Success' && result.payload?.invokeAgent) {\n console.log('🎯 Sub-agent invocation detected from @mention');\n await this.handleSubAgentInvocation(userMessage, result, conversationId, agentResponseMessage);\n }\n // Stage 3: Normal chat response\n else {\n await this.updateConversationDetail(agentResponseMessage, result.agentRun?.Message || `✅ **${agentName}** completed`, 'Complete', result)\n\n // Server created artifacts - emit event to trigger UI reload\n if (result.payload && Object.keys(result.payload).length > 0) {\n this.emitArtifactReload(agentResponseMessage);\n this.messageSent.emit(agentResponseMessage);\n }\n\n // Mark user message as complete\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n }\n } else {\n await this.applyAgentFailureToDetail(agentResponseMessage, userMessage, agentName, result);\n }\n } catch (error) {\n console.error(`❌ Error invoking mentioned agent ${agentName}:`, error);\n\n if (agentResponseMessage) {\n await this.applyAgentFailureToDetail(\n agentResponseMessage,\n userMessage,\n agentName,\n { success: false, errorMessage: error instanceof Error ? error.message : String(error) } as ExecuteAgentResult,\n );\n } else {\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n }\n }\n }\n\n /**\n * Continue with the same agent from previous message (implicit continuation)\n * Bypasses Sage - no status messages\n *\n * @param targetArtifactVersionId Optional specific artifact version to use as payload (from intent check)\n */\n private async continueWithAgent(\n userMessage: MJConversationDetailEntity,\n agentId: string,\n conversationId: string,\n targetArtifactVersionId?: string\n ): Promise<void> {\n // Load the agent entity to get its name\n const agent = AIEngineBase.Instance.Agents.find(a => UUIDsEqual(a.ID, agentId));\n if (!agent) {\n console.warn('⚠️ Could not load agent for continuation - falling back to Sage');\n await this.processMessageThroughAgent(userMessage, { mentions: [], agentMention: null, userMentions: [], entityMentions: [], skillMentions: [] });\n return;\n }\n\n const agentName = agent.Name || 'Agent';\n\n let previousPayload: Record<string, unknown> | null = null;\n let previousArtifactInfo: {artifactId: string; versionId: string; versionNumber: number} | null = null;\n let previousConfigurationId: string | undefined = undefined;\n\n // Use targetArtifactVersionId if specified (from intent check).\n // Resolved by ID against the database, not against artifactsByDetailId: the intent check\n // may well have named a version attached to a message BELOW the loaded window, which is\n // precisely when continuity matters and precisely what the window's maps cannot see.\n if (targetArtifactVersionId) {\n const target = await this.agentService.FindArtifactVersionById(targetArtifactVersionId);\n if (target && target.payload != null) {\n previousPayload = target.payload;\n previousArtifactInfo = {\n artifactId: target.artifactId,\n versionId: target.versionId,\n versionNumber: target.versionNumber\n };\n console.log('📦 Loaded target artifact version as payload', previousArtifactInfo);\n } else {\n console.warn('⚠️ Could not load target artifact version:', targetArtifactVersionId);\n }\n }\n\n // Extract configuration preset from the User message that @mentioned this agent\n // Uses the shared helper method in the agent service\n previousConfigurationId = await this.agentService.FindConfigurationPresetForAgent(conversationId, agentId);\n\n // Fall back to the chat header's mode-picker selection when nothing\n // in the message history pinned a preset. The picker reflects the\n // user's persistent per-agent mode preference (Draft / Standard /\n // High) and applies to all subsequent non-mention routes. A\n // history-derived preset still wins because it represents an\n // explicit per-message intent the user expressed earlier.\n if (!previousConfigurationId && this.agentConfigurationPresetId) {\n previousConfigurationId = this.agentConfigurationPresetId;\n }\n\n // Fall back to searching through all agent messages for an artifact\n // This ensures payload continuity even after clarifying exchanges without artifacts\n // Fall back to this agent's newest OUTPUT artifact when the intent check named no\n // version (or named one that no longer resolves). Queried, not scanned: the array this\n // used to walk is the loaded window, so the artifact it is looking for is exactly the\n // one most likely to be missing from it.\n if (!previousPayload) {\n const source = await this.agentService.FindLatestAgentOutputVersion(conversationId, agentId);\n if (source && source.payload != null) {\n previousPayload = source.payload;\n previousArtifactInfo = {\n artifactId: source.artifactId,\n versionId: source.versionId,\n versionNumber: source.versionNumber\n };\n console.log('📦 Loaded artifact as payload for continuation', previousArtifactInfo);\n } else {\n console.log(`📦 No artifact found for agent ${agentId} in this conversation`);\n }\n }\n\n // Execute the agent with the gathered context\n await this.executeAgentContinuation(\n userMessage,\n agentId,\n agentName,\n conversationId,\n previousPayload,\n previousArtifactInfo,\n previousConfigurationId\n );\n }\n\n /**\n * Executes agent continuation with all context already gathered.\n * This is the shared execution logic used by both continueWithAgent and direct Sage config path.\n *\n * @param userMessage The user's message entity\n * @param agentId The agent ID to invoke\n * @param agentName The agent's display name\n * @param conversationId The conversation ID\n * @param previousPayload Optional payload from previous artifact\n * @param previousArtifactInfo Optional artifact info (id, versionId, versionNumber)\n * @param configurationId Optional configuration preset ID to use\n */\n private async executeAgentContinuation(\n userMessage: MJConversationDetailEntity,\n agentId: string,\n agentName: string,\n conversationId: string,\n previousPayload: Record<string, unknown> | null,\n previousArtifactInfo: {artifactId: string; versionId: string; versionNumber: number} | null,\n configurationId?: string\n ): Promise<void> {\n // Add agent to active tasks\n const taskId = this.activeTasks.add({\n agentName: agentName,\n status: 'Processing...',\n relatedMessageId: userMessage.ID,\n conversationDetailId: userMessage.ID,\n conversationId,\n conversationName: this.conversationName\n });\n\n // Declare agentResponseMessage outside try block so it's accessible in catch\n let agentResponseMessage: MJConversationDetailEntity | undefined = undefined;\n\n try {\n // User message is sent successfully - mark complete immediately\n // (No UI uses User message 'In-Progress' - only AI messages need that status)\n userMessage.Status = 'Complete';\n await userMessage.Save();\n this.messageSent.emit(userMessage);\n\n // Create AI response message BEFORE invoking agent (for duration tracking)\n agentResponseMessage = await this.dataCache.createConversationDetail(this.currentUser);\n\n agentResponseMessage.ConversationID = conversationId;\n agentResponseMessage.Role = 'AI';\n agentResponseMessage.Message = '⏳ Starting...'; // Initial message\n agentResponseMessage.ParentID = userMessage.ID;\n agentResponseMessage.Status = 'In-Progress';\n agentResponseMessage.HiddenToUser = false;\n agentResponseMessage.AgentID = agentId;\n\n // Save the record to establish __mj_CreatedAt timestamp\n await agentResponseMessage.Save();\n this.messageSent.emit(agentResponseMessage);\n\n // Invoke the agent directly (continuation) with previous payload if available.\n // `this.appContext` is forwarded so direct-routed sub-agents (e.g. Form\n // Builder via [defaultAgentId]) see the embedder's ActiveForm/Schema/\n // OverrideID block in their prompt — same flow Sage gets via\n // `processMessage`.\n const result = await this.agentService.invokeSubAgent(\n agentName,\n conversationId,\n userMessage,\n this.conversationHistory,\n 'Continuing previous conversation with user',\n agentResponseMessage.ID,\n previousPayload, // Pass previous OUTPUT artifact payload for continuity\n this.createProgressCallback(agentResponseMessage, agentName),\n previousArtifactInfo?.artifactId,\n previousArtifactInfo?.versionId,\n configurationId, // Pass configuration for continuity\n this.appContext, // Embedder-supplied app/form context\n this.PlanModeEnabled, // per-request Plan Mode toggle\n this._pendingRequestedSkillIDs, // user-requested skills (/skill mentions)\n );\n\n // Remove from active tasks\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n\n if (result && result.success) {\n // Update the response message with agent result\n await this.updateConversationDetail(agentResponseMessage,result.agentRun?.Message || `✅ **${agentName}** completed`, 'Complete', result);\n\n // Server created artifacts (handles versioning) - emit event to trigger UI reload\n if (result.payload && Object.keys(result.payload).length > 0) {\n this.emitArtifactReload(agentResponseMessage);\n this.messageSent.emit(agentResponseMessage);\n }\n\n // Mark user message as complete\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n } else {\n await this.applyAgentFailureToDetail(agentResponseMessage, userMessage, agentName, result);\n }\n } catch (error) {\n console.error(`❌ Error continuing with agent ${agentName}:`, error);\n\n if (agentResponseMessage) {\n await this.applyAgentFailureToDetail(\n agentResponseMessage,\n userMessage,\n agentName,\n { success: false, errorMessage: error instanceof Error ? error.message : String(error) } as ExecuteAgentResult,\n );\n } else {\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n }\n }\n }\n\n /**\n * Names the conversation from its first message via the SHARED naming helper\n * ({@link GenerateAndApplyConversationName}) — the same implementation the realtime\n * session path uses. This wrapper keeps the composer-specific concerns local:\n * mention stripping and the sidebar rename animation event.\n */\n private async nameConversation(message: string, conversationId: string): Promise<void> {\n // Convert message to plain text (strips JSON-encoded mentions like @{\"id\":\"...\",\"name\":\"Sage\"} to @Sage)\n const plainTextMessage = this.mentionParser.toPlainText(\n message,\n this.mentionAutocomplete.getAvailableAgents(),\n this.mentionAutocomplete.getAvailableUsers()\n );\n\n // Use the captured conversationId (not this.conversationId): naming runs fire-and-forget\n // in the background, so the user may have swapped conversations before it resolves.\n const result = await GenerateAndApplyConversationName({\n ConversationId: conversationId,\n MessageText: plainTextMessage,\n Provider: this.ProviderToUse as GraphQLDataProvider,\n CurrentUser: this.currentUser\n });\n\n if (result) {\n // Emit event for animation in conversation list\n this.conversationRenamed.emit({\n conversationId,\n name: result.Name,\n description: result.Description\n });\n console.log(`✅ Conversation renamed to: \"${result.Name}\"`);\n }\n }\n\n /**\n * Persist an agent failure onto the response bubble.\n *\n * A dropped HTTP/WebSocket path used to return `null` from invokeSubAgent, so\n * the bubble said \"Unknown error\" while the AIAgentRun stayed Running and the\n * timer kept ticking. If the transport ACKed the mutation and then died, keep\n * In-Progress so a later completion event (or {@link startInFlightDetailWatch})\n * can land. ConversationDetail.Status is the server's claim; the client only\n * renders it. The GraphQLAIClient stall reconciler covers the wait inside\n * invokeSubAgent; once that returns, the watch observes the detail until the\n * server writes a terminal status (MaxTimePerRun).\n *\n * Always completes the user message — the user turn finished regardless of\n * what the agent is doing.\n */\n private async applyAgentFailureToDetail(\n agentResponseMessage: MJConversationDetailEntity,\n userMessage: MJConversationDetailEntity,\n agentName: string,\n result: ExecuteAgentResult | null | undefined,\n failedVerb = 'failed',\n ): Promise<void> {\n const disposition = agentFailureDisposition(result);\n if (disposition.status === 'In-Progress') {\n await this.updateConversationDetail(\n agentResponseMessage,\n `⏳ **${agentName}** is still running on the server.\\n\\n${disposition.message}`,\n 'In-Progress',\n );\n // Skip the watch if the reload-before-write guard already found a\n // terminal server status (Complete/Error) — starting it would race the\n // just-completed bubble.\n if (agentResponseMessage.Status === 'In-Progress') {\n this.startInFlightDetailWatch(agentResponseMessage);\n }\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n return;\n }\n agentResponseMessage.Error = disposition.message;\n await this.updateConversationDetail(\n agentResponseMessage,\n `❌ **${agentName}** ${failedVerb}\\n\\n${disposition.message}`,\n 'Error',\n );\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n }\n\n private startInFlightDetailWatch(detail: MJConversationDetailEntity): void {\n if (!detail.ID) {\n return;\n }\n this.stopInFlightDetailWatch(detail.ID);\n this.scheduleInFlightDetailPoll(detail, 0);\n }\n\n private scheduleInFlightDetailPoll(detail: MJConversationDetailEntity, step: number): void {\n const delays = MessageInputComponent.IN_FLIGHT_WATCH_BACKOFF_MS;\n const delay = delays[Math.min(step, delays.length - 1)];\n const handle = setTimeout(() => {\n void this.pollInFlightDetail(detail, step);\n }, delay);\n this.inFlightWatches.set(detail.ID, handle);\n }\n\n private async pollInFlightDetail(detail: MJConversationDetailEntity, step: number): Promise<void> {\n if (!this.inFlightWatches.has(detail.ID)) {\n return;\n }\n try {\n await detail.Load(detail.ID);\n if (detail.Status === 'Complete' || detail.Status === 'Error') {\n this.stopInFlightDetailWatch(detail.ID);\n this.markMessageComplete(detail);\n this.messageSent.emit(detail);\n return;\n }\n } catch (e) {\n console.warn(`[InFlightWatch] Failed to reload conversation detail ${detail.ID}:`, e);\n }\n if (!this.inFlightWatches.has(detail.ID)) {\n return;\n }\n this.scheduleInFlightDetailPoll(detail, step + 1);\n }\n\n private stopInFlightDetailWatch(detailId: string): void {\n const handle = this.inFlightWatches.get(detailId);\n if (handle) {\n clearTimeout(handle);\n this.inFlightWatches.delete(detailId);\n }\n }\n\n private clearInFlightWatches(): void {\n for (const handle of this.inFlightWatches.values()) {\n clearTimeout(handle);\n }\n this.inFlightWatches.clear();\n }\n\n /**\n * Marks a conversation detail as complete and records timestamp to prevent race conditions\n * Emits event to parent to refresh agent run data from database\n */\n private markMessageComplete(conversationDetail: MJConversationDetailEntity): void {\n const now = Date.now();\n this.completionTimestamps.set(conversationDetail.ID, now);\n this.stopInFlightDetailWatch(conversationDetail.ID);\n\n // Unregister streaming callback for this message (no more updates needed)\n const callback = this.registeredCallbacks.get(conversationDetail.ID);\n if (callback) {\n this.streamingService.unregisterMessageCallback(conversationDetail.ID, callback);\n this.registeredCallbacks.delete(conversationDetail.ID);\n LogStatusEx({ message: `[MarkComplete] Unregistered streaming callback for completed message ${conversationDetail.ID}`, verboseOnly: true });\n }\n\n // Remove task from active tasks if it exists\n const task = this.activeTasks.getByConversationDetailId(conversationDetail.ID);\n if (task) {\n LogStatusEx({\n message: `✅ Task found for message ${conversationDetail.ID} - removing from active tasks:`,\n additionalArgs: [{\n taskId: task.id,\n agentName: task.agentName,\n conversationId: task.conversationId,\n conversationName: task.conversationName\n }],\n verboseOnly: true,\n });\n\n this.activeTasks.remove(task.id);\n\n // Show toast only if the user isn't currently viewing this conversation.\n // If they're watching, the inline completion is sufficient.\n const isConvoVisible = UUIDsEqual(this.bridge.ActiveConversationID$.value, task.conversationId)\n && (this.bridge.OverlayActive$.value || this.bridge.WorkspaceActive$.value);\n if (!isConvoVisible) {\n // The server announces the same completion through its Agent Completion notification\n // (when the run produced an artifact); the shared dedupe key folds the two into one\n // toast, and this wording — the later of the two — is what stays on screen.\n const agent = task.agentId\n ? AIEngineBase.Instance.Agents.find(a => UUIDsEqual(a.ID, task.agentId))\n : undefined;\n // The task carries the name from send time; the engine has the current one (the\n // first exchange auto-names the conversation). The placeholder a brand-new\n // conversation starts with is not a name worth announcing.\n const currentName = this.engine.Conversations.find(c => UUIDsEqual(c.ID, task.conversationId))?.Name\n ?? task.conversationName;\n const conversationName = currentName && currentName !== 'New Conversation' ? currentName : null;\n MJNotificationService.Instance?.CreateRichNotification({\n title: `${task.agentName} finished`,\n message: conversationName ? `in ${conversationName}` : null,\n imageUrl: agent?.LogoURL ?? null,\n iconClass: agent?.IconClass ?? 'fa-solid fa-robot',\n hideAfter: 5000,\n dedupeKey: `agent-completion:${task.conversationId ?? task.id}`,\n context: { conversationId: task.conversationId, agentId: task.agentId, agentName: task.agentName }\n });\n }\n } else {\n // verboseOnly, and no longer a warning. A turn registers ONE task, against whichever message\n // its flow chose — activeTasks.add() is called with the user message, a Sage delegation\n // message, a status message or the agent response depending on the path — while this method\n // runs for EVERY message in the turn reaching Complete or Error. Most calls therefore land\n // here, so it is the normal case rather than the lifecycle race the old text described\n // (\"task may have been removed prematurely or not added\"). Kept for tracing, off by default.\n LogStatusEx({ message: `[MarkComplete] No task registered against completed message ${conversationDetail.ID} — expected for any message that did not start the turn`, verboseOnly: true });\n }\n\n // Emit completion event to parent so it can refresh agent run data\n this.messageComplete.emit({\n conversationId: conversationDetail.ConversationID,\n conversationDetailId: conversationDetail.ID,\n agentId: conversationDetail.AgentID || undefined\n });\n }\n\n /**\n * Emit an artifact-reload signal for {@link detail}. The artifact metadata fields are\n * placeholders — the parent reloads the real artifacts from the DB; the only fields it\n * consumes are conversationDetailId and conversationId (the latter lets it drop events from\n * a background conversation after a conversation swap). conversationId is taken from the\n * detail entity's immutable ConversationID, never this.conversationId.\n */\n private emitArtifactReload(detail: MJConversationDetailEntity): void {\n this.artifactCreated.emit({\n conversationId: detail.ConversationID,\n artifactId: '',\n versionId: '',\n versionNumber: 0,\n conversationDetailId: detail.ID,\n name: ''\n });\n }\n\n /**\n * Cleans up completion timestamps for completed messages (prevents memory leak)\n */\n private cleanupCompletionTimestamp(conversationDetailId: string): void {\n // Keep timestamp for a short period to catch any late progress updates\n setTimeout(() => {\n this.completionTimestamps.delete(conversationDetailId);\n }, 5000); // 5 seconds should be more than enough\n }\n}\n","<div class=\"message-input-wrapper\" cdkOverlayOrigin #pickerOrigin=\"cdkOverlayOrigin\">\n <!-- Processing Indicator Overlay -->\n @if (isProcessing) {\n <div class=\"processing-indicator\">\n <i class=\"fas fa-circle-notch fa-spin\"></i>\n <span>{{ processingMessage }}</span>\n </div>\n }\n\n <!-- AI composer (mic + Plan Mode buttons live in its in-composer toolbar): wraps the\n generic mj-message-input-box with the '@' agent / '#' record / '/' skill trigger\n plugins built in — all three on by default, preserving the standard chat behavior. -->\n <mj-ai-composer\n #inputBox\n [placeholder]=\"placeholder\"\n [disabled]=\"disabled || isProcessing\"\n [showCharacterCount]=\"false\"\n [enableMentions]=\"enableMentions\"\n [EnableAgentMentions]=\"enableAgentMentions\"\n [EnableEntityMentions]=\"enableEntityMentions\"\n [EnableSkillCommands]=\"enableSkillCommands\"\n [TargetAgentId]=\"pickerTargetAgentId\"\n [enableAttachments]=\"enableAttachments\"\n [maxAttachments]=\"maxAttachments\"\n [maxAttachmentSizeBytes]=\"maxAttachmentSizeBytes\"\n [acceptedFileTypes]=\"acceptedFileTypes\"\n [currentUser]=\"currentUser\"\n [Provider]=\"Provider\"\n [rows]=\"3\"\n [enableRealtime]=\"enableRealtime\"\n [voiceActive]=\"voiceActive\"\n [canStartRealtime]=\"canStartRealtime\"\n [enablePlanMode]=\"enablePlanMode\"\n [planModeActive]=\"PlanModeEnabled\"\n [value]=\"messageText\"\n (valueChange)=\"OnComposerValueChanged($event)\"\n (blurred)=\"ComposerBlurred.emit()\"\n (textSubmitted)=\"onTextSubmitted($event)\"\n (attachmentsChanged)=\"onAttachmentsChanged($event)\"\n (attachmentError)=\"onAttachmentError($event)\"\n (voiceRequested)=\"onStartRealtime()\"\n (voiceOptionsRequested)=\"onRealtimeOptions()\"\n (planModeToggle)=\"TogglePlanMode()\">\n </mj-ai-composer>\n\n <!-- Voice agent/co-agent/model picker — shown when starting a call on a conversation\n with NO prior agent participation, or on demand via the caret next to the phone\n button (any conversation). Rendered in a body-level CDK overlay anchored above the\n composer so it POPS OUT of the chat overlay's clipping border instead of being cut\n off at the top of a narrow (~390px) overlay. -->\n <ng-template\n cdkConnectedOverlay\n [cdkConnectedOverlayOrigin]=\"pickerOrigin\"\n [cdkConnectedOverlayOpen]=\"showRealtimeAgentPicker\"\n [cdkConnectedOverlayPositions]=\"pickerOverlayPositions\"\n [cdkConnectedOverlayPush]=\"true\"\n [cdkConnectedOverlayHasBackdrop]=\"true\"\n cdkConnectedOverlayBackdropClass=\"cdk-overlay-transparent-backdrop\"\n (backdropClick)=\"onRealtimeAgentPickerCancelled()\"\n (detach)=\"onRealtimeAgentPickerCancelled()\">\n <mj-realtime-agent-picker\n [Provider]=\"Provider\"\n [Agents]=\"voicePickerAgents\"\n [DefaultAgentId]=\"voicePickerDefaultAgentId\"\n [CoAgents]=\"voicePickerCoAgents\"\n [DefaultCoAgentId]=\"voicePickerDefaultCoAgentId\"\n (AgentPicked)=\"onRealtimeAgentPicked($event)\"\n (Cancelled)=\"onRealtimeAgentPickerCancelled()\">\n </mj-realtime-agent-picker>\n </ng-template>\n</div>\n\n<!-- The voice \"call mode\" overlay is hosted by <mj-conversation-chat-area> (it fills the\n whole conversation panel in place); this component only owns the trigger wiring. -->\n"]}
|
|
1
|
+
{"version":3,"file":"message-input.component.js","sourceRoot":"","sources":["../../../../src/lib/components/message/message-input.component.ts","../../../../src/lib/components/message/message-input.component.html"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,SAAS,EAA8D,MAAM,eAAe,CAAC;AAE9I,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,EAAsB,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACvE,OAAO,EAA8B,2BAA2B,EAAE,kBAAkB,EAAE,cAAc,EAAE,wBAAwB,EAA6B,MAAM,+BAA+B,CAAC;AAKjM,OAAO,EAAE,wBAAwB,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAK7F,OAAO,EAAE,gCAAgC,EAAE,MAAM,oCAAoC,CAAC;AACtF,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAC9D,OAAO,EAA8G,mBAAmB,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAG7N,OAAO,EAAE,0BAA0B,EAAE,MAAM,6CAA6C,CAAC;AAIzF,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AAEtE,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAIzE,OAAO,EACL,gCAAgC,EAChC,sBAAsB,EACtB,mBAAmB,EACnB,mBAAmB,EACpB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,UAAU,EAAqB,MAAM,wBAAwB,CAAC;;;;;;;;;;;;;;;;;ICjCnE,8BAAkC;IAChC,uBAA2C;IAC3C,4BAAM;IAAA,YAAuB;IAC/B,AAD+B,iBAAO,EAChC;;;IADE,eAAuB;IAAvB,8CAAuB;;;;IAuD/B,mDAQiD;IAA/C,AADA,6NAAe,oCAA6B,KAAC,sMAChC,uCAAgC,KAAC;IAChD,iBAA2B;;;IAHzB,AADA,AADA,AADA,AADA,AADA,+CAA0B,mCACC,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BAAC,UAAU;;kBAoCpB,KAAK;;kBAkBL,MAAM;;kBAON,MAAM;;kBAGN,MAAM;;kFAhSI,qBAAqB","sourcesContent":["import { Component, Input, Output, EventEmitter, ViewChild, OnInit, OnDestroy, OnChanges, SimpleChanges, AfterViewInit } from '@angular/core';\nimport { ConnectedPosition } from '@angular/cdk/overlay';\nimport { BaseAngularComponent } from '@memberjunction/ng-base-types';\nimport { UserInfo, Metadata, LogStatusEx } from '@memberjunction/core';\nimport { MJConversationDetailEntity, MJEnvironmentEntityExtended, ConversationEngine, UserInfoEngine, TaskGraphSubmitOperation, type TaskGraphSubmitInput } from '@memberjunction/core-entities';\nimport { MJAIAgentEntityExtended, MJAIAgentRunEntityExtended, AppContextSnapshot } from \"@memberjunction/ai-core-plus\";\nimport { DialogService } from '../../services/dialog.service';\nimport { ToastService } from '../../services/toast.service';\nimport { ConversationAgentService } from '../../services/conversation-agent.service';\nimport { BeforeAgentTurnEventArgs, AfterAgentTurnEventArgs } from '../../events/chat-events';\nimport { DataCacheService } from '../../services/data-cache.service';\nimport { ActiveTasksService } from '../../services/active-tasks.service';\nimport { ConversationStreamingService, MessageProgressUpdate, MessageProgressMetadata } from '../../services/conversation-streaming.service';\nimport { GraphQLDataProvider, GraphQLAIClient } from '@memberjunction/graphql-dataprovider';\nimport { GenerateAndApplyConversationName } from '../../services/conversation-naming';\nimport { AIEngineBase } from '@memberjunction/ai-engine-base';\nimport { ExecuteAgentResult, AgentExecutionProgressCallback, AgentResponseForm, ActionableCommand, AutomaticCommand, ConversationUtility, agentFailureDisposition, agentFailureMessage } from '@memberjunction/ai-core-plus';\nimport { PendingAttachment } from '@memberjunction/ng-composer';\nimport { AiComposerComponent } from '../composer/ai-composer.component';\nimport { MentionAutocompleteService } from '../../services/mention-autocomplete.service';\nimport { MentionParserService } from '../../services/mention-parser.service';\nimport { ConversationAttachmentService } from '../../services/conversation-attachment.service';\nimport { Mention, MentionParseResult } from '../../models/conversation-state.model';\nimport { PlanModePreference } from '../../utils/plan-mode-preference';\nimport { LazyArtifactInfo } from '../../models/lazy-artifact-info';\nimport { MJNotificationService } from '@memberjunction/ng-notifications';\nimport { ConversationBridgeService } from '../../services/conversation-bridge.service';\nimport { RealtimeSessionService } from '../../services/realtime-session.service';\nimport { RealtimeAgentPick } from '../realtime/realtime-agent-picker.component';\nimport {\n BuildRealtimeConfigOverridesJson,\n FilterRealtimeCoAgents,\n LoadCoAgentPairings,\n PairingsAllowTarget\n} from '../../services/realtime-pairing';\nimport { Subscription } from 'rxjs';\nimport { UUIDsEqual, CleanAndParseJSON } from '@memberjunction/global';\n\n@Component({\n standalone: false,\n selector: 'mj-message-input',\n templateUrl: './message-input.component.html',\n styleUrl: './message-input.component.css'\n})\nexport class MessageInputComponent extends BaseAngularComponent implements OnInit, OnDestroy, OnChanges, AfterViewInit {\n // Default artifact type ID for JSON (when agent doesn't specify DefaultArtifactTypeID)\n private readonly JSON_ARTIFACT_TYPE_ID = 'ae674c7e-ea0d-49ea-89e4-0649f5eb20d4';\n\n @Input() conversationId!: string;\n @Input() conversationName?: string | null; // For task tracking display\n @Input() currentUser!: UserInfo;\n @Input() disabled: boolean = false;\n @Input() placeholder: string = 'Type a message... (Ctrl+Enter to send)';\n @Input() parentMessageId?: string; // Optional: for replying in threads\n @Input() enableAttachments: boolean = true; // Whether to show attachment button (based on agent modality support)\n @Input() enableMentions: boolean = true; // Whether to enable @-mention autocomplete (agents/users). Hosts addressing a single fixed agent (e.g. Form Builder cockpit) typically set false.\n // Per-type caps under enableMentions (all default true) — forwarded to the AI composer's\n // EnableAgentMentions/EnableEntityMentions/EnableSkillCommands. Let a host keep '/' skill\n // commands while dropping '@' agent mentions (which would override a pinned default agent).\n @Input() enableAgentMentions: boolean = true;\n @Input() enableEntityMentions: boolean = true;\n @Input() enableSkillCommands: boolean = true;\n @Input() enablePlanMode: boolean = true; // Whether the composer shows the Plan Mode toggle. Hosts that don't expose plan-mode workflows set false.\n @Input() enableRealtime: boolean = true; // Whether the composer shows the realtime voice-call launcher/options. Hosts without a voice experience set false.\n @Input() maxAttachments: number = 10; // Maximum number of attachments per message\n @Input() maxAttachmentSizeBytes: number = 20 * 1024 * 1024; // Maximum size per attachment (20MB default)\n @Input() acceptedFileTypes: string = 'image/*'; // Accepted MIME types pattern\n @Input() artifactsByDetailId?: Map<string, LazyArtifactInfo[]>; // Pre-loaded artifact data for performance\n @Input() systemArtifactsByDetailId?: Map<string, LazyArtifactInfo[]>; // Pre-loaded system artifact data (Visibility='System Only')\n @Input() agentRunsByDetailId?: Map<string, MJAIAgentRunEntityExtended>; // Pre-loaded agent run data for performance\n @Input() emptyStateMode: boolean = false; // When true, emits emptyStateSubmit instead of creating messages directly\n @Input() appContext: Record<string, unknown> | null = null; // Application context for AI agent awareness\n\n /**\n * Plan Mode toggle state — sticky PER CONVERSATION, OFF by default (no behavior change unless\n * the user turns it on). When on, the user's next message(s) in THIS conversation request Plan\n * Mode: the routed root agent must present a plan for approval before executing Actions/\n * Sub-Agents. The toggle is always shown and the server enforces the `AIAgent.SupportsPlanMode`\n * capability — a plan-mode request to an agent that doesn't support it simply no-ops the gate\n * (see resolvePlanModeGate), so we don't need to resolve \"the current agent\" client-side.\n *\n * IMPORTANT: this is a GETTER over {@link PlanModePreference} (UserInfoEngine-backed), NOT a\n * local field. The composer is mounted in multiple places at once (empty-state, chat-area,\n * thread panel) — a local boolean per instance goes stale the moment another instance toggles.\n * On the new-conversation composer (no conversationId yet) the value lives in a pending bucket\n * that transfers to the real conversation on its first message. Approving a plan turns the\n * conversation's flag OFF automatically (see message-item's plan-decision handling).\n */\n public get PlanModeEnabled(): boolean {\n return PlanModePreference.IsEnabled(this.conversationId);\n }\n\n /**\n * Skill IDs the user requested via `/skill-name` mentions in the message being routed. Collected\n * once per send from the composer's mention chips and forwarded to every agent-invocation path so\n * whichever agent handles the message receives them as `RequestedSkillIDs`. The server intersects\n * them with the agent's accepted skills AND the user's Run permission before any activate, so a\n * skill the user can't run (or the agent doesn't accept) is silently dropped. Reset each send.\n */\n private _pendingRequestedSkillIDs: string[] = [];\n\n /**\n * Collects the skill IDs from `/skill` mention chips currently in the composer. Called at the\n * start of routing so the value is stable for the whole message dispatch.\n */\n private collectRequestedSkillIDs(): string[] {\n const chipData = this.inputBox?.getMentionChipsData() || [];\n return chipData.filter(chip => chip.type === 'skill').map(chip => chip.id);\n }\n\n /**\n * Optional default agent ID for the conversation. When set, the FIRST\n * message routes directly to this agent — skipping Sage's default\n * delegation — provided the user did not @mention a different agent\n * and there is no prior agent in the conversation history. After the\n * first message, the existing \"last non-Sage agent\" continuity rule\n * keeps subsequent messages on the same agent.\n *\n * Used by embedded chat surfaces (Form Builder cockpit, future\n * domain-specific chats) that have an obvious specialist agent for the\n * context and don't need Sage to route. Leave unset to preserve the\n * standard Sage-fronted UX of the main Chat app.\n */\n @Input() defaultAgentId: string | null = null;\n\n /**\n * Per-conversation pinned default agent — sourced from the loaded\n * `MJConversationEntity.DefaultAgentID`. When set, this agent is used in\n * preference to the embedder-supplied {@link defaultAgentId} so a user\n * who pins a conversation to e.g. Research Agent gets that routing even\n * inside an embedded surface whose embedder defaults to a different\n * specialist. Routing precedence:\n * 1. @mention\n * 2. continuity (last responder)\n * 3. **conversationDefaultAgentId** (this input — user's per-conversation pin)\n * 4. defaultAgentId (embedder-supplied)\n * 5. Sage fallback\n */\n @Input() conversationDefaultAgentId: string | null = null;\n\n /**\n * The `MJ: AI Agent Configurations.ID` selected via the chat header's\n * mode picker (Draft / Standard / High). Applied to **non-mention**\n * routes — when the user types without `@mention`, this preset rides\n * along on the next `invokeSubAgent` call so the server resolves the\n * agent's Fast / Standard / High Power AI configuration accordingly.\n *\n * Mentioned-route turns still use the preset embedded in the mention\n * (e.g. `@Form Builder /high`) because that's a per-message intent\n * the user just expressed. Continuity-route turns (last responder\n * agent) also honor this input as the fallback when the prior\n * message itself doesn't carry an explicit configuration preset.\n *\n * Picker writes are forward-only: changing the mode does NOT re-route\n * messages already in flight or already in history. Affects \"what\n * happens next.\"\n */\n @Input() agentConfigurationPresetId: string | null = null;\n\n // Initial message to send automatically - using getter/setter for precise control\n private _initialMessage: string | null = null;\n private _initialAttachments: PendingAttachment[] | null = null;\n private _isComponentReady = false; // Track if component is ready to send\n /** Conversation this input has already auto-sent its pending first message for. */\n private _autoSentForConversationId: string | null = null;\n\n @Input()\n set initialMessage(value: string | null) {\n // Handle case where an object with {text, attachments} is passed instead of just a string\n // This can happen if there's a type mismatch in the binding chain\n let actualValue = value;\n if (value && typeof value === 'object' && 'text' in value) {\n actualValue = (value as { text: string }).text;\n }\n\n const previousValue = this._initialMessage;\n this._initialMessage = actualValue;\n\n // If component is ready and we have a new non-null message, trigger send\n if (this._isComponentReady && actualValue && actualValue !== previousValue) {\n this.triggerInitialSend();\n }\n }\n get initialMessage(): string | null {\n return this._initialMessage;\n }\n\n @Input()\n set initialAttachments(value: PendingAttachment[] | null) {\n this._initialAttachments = value;\n }\n get initialAttachments(): PendingAttachment[] | null {\n return this._initialAttachments;\n }\n\n private _conversationHistory: MJConversationDetailEntity[] = [];\n @Input()\n public get conversationHistory(): MJConversationDetailEntity[] {\n return this._conversationHistory;\n }\n public set conversationHistory(value: MJConversationDetailEntity[]) {\n this._conversationHistory = value;\n }\n\n // Message IDs that are in-progress and need streaming reconnection\n // Using getter/setter to react immediately when value changes (avoids timing issues with ngOnChanges)\n private _inProgressMessageIds?: string[];\n @Input()\n set inProgressMessageIds(value: string[] | undefined) {\n this._inProgressMessageIds = value;\n // React immediately when input changes (after component initialized)\n // This ensures callbacks are registered without relying on ngOnChanges timing\n if (this.streamingService && value && value.length > 0) {\n this.reconnectInProgressMessages();\n } else if (this.streamingService) {\n // Empty/undefined — e.g. this input was backgrounded by a conversation swap\n // ([] is bound to non-active inputs). Drop any streaming callbacks so a hidden\n // input isn't left subscribed; reconnectInProgressMessages re-registers when it\n // becomes active again with a non-empty list.\n this.unregisterAllCallbacks();\n }\n }\n get inProgressMessageIds(): string[] | undefined {\n return this._inProgressMessageIds;\n }\n\n /**\n * Application context for the current conversation. Threaded through from the\n * chat-area component for inclusion in the {@link beforeAgentTurn} event payload —\n * lets listeners reason about which app's chat surface is invoking the agent.\n * Optional; defaults to null for surfaces with no app context.\n */\n @Input() applicationId: string | null = null;\n\n @Output() messageSent = new EventEmitter<MJConversationDetailEntity>();\n @Output() agentResponse = new EventEmitter<{message: MJConversationDetailEntity, agentResult: any}>();\n\n /**\n * Cancelable — fired BEFORE `agentService.processMessage()` is called for a user turn.\n * Listeners may set `event.Cancel = true` to halt the agent invocation (e.g., a\n * client-side guardrail blocking the turn). When canceled, the corresponding\n * {@link afterAgentTurn} event is NOT fired and the running task is cleared.\n * Follows MJ's established Before/After cancelable event pattern.\n */\n @Output() beforeAgentTurn = new EventEmitter<BeforeAgentTurnEventArgs>();\n\n /**\n * Fired AFTER a successful agent turn completes. Carries the agent run id and the\n * full agent result. Not fired when {@link beforeAgentTurn} was canceled or when\n * the underlying `processMessage` errored.\n */\n @Output() afterAgentTurn = new EventEmitter<AfterAgentTurnEventArgs>();\n // conversationId is carried on every agent-lifecycle event so the parent chat-area can drop\n // events emitted by a BACKGROUND conversation's (hidden, still-streaming) input after the user\n // has swapped conversations — preventing cross-conversation state/cache bleed. Sourced from the\n // ConversationDetail entity's ConversationID (the captured, immutable value), never this.conversationId.\n @Output() agentRunDetected = new EventEmitter<{conversationId: string; conversationDetailId: string; agentRunId: string}>();\n @Output() agentRunUpdate = new EventEmitter<{conversationId: string; conversationDetailId: string; agentRun?: any, agentRunId?: string}>(); // Emits when agent run data updates during progress\n @Output() messageComplete = new EventEmitter<{conversationId: string; conversationDetailId: string; agentId?: string}>(); // Emits when message completes (success or error)\n @Output() artifactCreated = new EventEmitter<{conversationId: string; artifactId: string; versionId: string; versionNumber: number; conversationDetailId: string; name: string}>();\n @Output() conversationRenamed = new EventEmitter<{conversationId: string; name: string; description: string}>();\n @Output() intentCheckStarted = new EventEmitter<{conversationId: string}>(); // Emits when intent checking starts\n @Output() intentCheckCompleted = new EventEmitter<{conversationId: string}>(); // Emits when intent checking completes (carries conversationId so the parent can drop a background conversation's completion after a swap — symmetric with intentCheckStarted)\n @Output() initialMessageAutoSendStarted = new EventEmitter<{conversationId: string}>(); // Emitted when this input latches the pending first message for auto-send\n @Output() initialMessageAutoSendFailed = new EventEmitter<{conversationId: string}>(); // Emitted when a latched pending first message fails before messageSent\n @Output() emptyStateSubmit = new EventEmitter<{text: string; attachments: PendingAttachment[]}>(); // Emitted when in emptyStateMode\n @Output() uploadStateChanged = new EventEmitter<{isUploading: boolean; message: string}>(); // Emits when attachment upload state changes\n\n @ViewChild('inputBox') inputBox!: AiComposerComponent;\n\n private _messageText: string = '';\n /**\n * The composer's text. An accessor pair rather than a plain field because every write reaches the\n * editor through `[value]` -> `ngModel.writeValue`, which rebuilds or empties the chip DOM WITHOUT\n * emitting `valueChange` — so a write is exactly the event {@link mentionedAgentId} has to hear\n * about, and the setter is the one place that cannot be bypassed.\n *\n * Bypassing it is not hypothetical: `handleSuccessfulSend` and the empty-state submit clear the\n * text without touching the editor, and `conversation-chat-area` assigns `messageText` on this\n * component from the outside (three call sites). Invalidating at the individual call sites instead\n * would leave every future one to remember.\n *\n * Read is a plain field read; there is no two-way `ngModel` on this property (the template binds\n * `[value]=\"messageText\"` one-way), so the pair is transparent to callers.\n */\n public get messageText(): string {\n return this._messageText;\n }\n public set messageText(value: string) {\n this._messageText = value;\n this.mentionedAgentId = undefined;\n }\n\n /**\n * Prefills the composer with draft text WITHOUT sending (unlike pendingMessage,\n * which auto-sends) and focuses the input — e.g. the omnibar's '@agent' flow\n * lands in chat with '@AgentName ' staged so the user just types their ask.\n */\n /**\n * Draft text to stage in the composer when this input mounts (NOT sent — unlike\n * pendingMessage). Applied once per distinct value, view-readiness-proof: if the\n * view isn't up yet, ngAfterViewInit applies it. Emits initialDraftApplied so the\n * host can clear its pending state.\n */\n @Input()\n set initialDraft(value: string | null) {\n if (value && value !== this.appliedInitialDraft) {\n this.appliedInitialDraft = value;\n if (this.inputBox) {\n this.SetDraft(value, true);\n this.initialDraftApplied.emit();\n } else {\n this.pendingInitialDraft = value;\n }\n }\n }\n get initialDraft(): string | null {\n return this.appliedInitialDraft;\n }\n private appliedInitialDraft: string | null = null;\n private pendingInitialDraft: string | null = null;\n\n @Output() initialDraftApplied = new EventEmitter<void>();\n\n /**\n * Live draft-state signal: fires on every composer value change with the\n * SERIALIZED content (mention pills encoded via getPlainTextWithJsonMentions,\n * so hosts can persist drafts losslessly). Empty string = draft cleared.\n */\n @Output() DraftStateChanged = new EventEmitter<string>();\n\n /** The composer lost focus — hosts flush persisted drafts on this. */\n @Output() ComposerBlurred = new EventEmitter<void>();\n\n /** Handles the composer's value stream: keeps messageText in sync + emits draft state. */\n public OnComposerValueChanged(value: string): void {\n this.messageText = value;\n this.DraftStateChanged.emit(this.GetSerializedDraft());\n }\n\n /** Current composer content in the lossless serialized form ('' when empty). */\n public GetSerializedDraft(): string {\n const serialized = this.inputBox?.getPlainTextWithJsonMentions() ?? this.messageText ?? '';\n return serialized.trim().length === 0 ? '' : serialized;\n }\n\n /**\n * Pre-addresses the composer to an agent as a RESOLVED mention pill (+ trailing\n * space, caret after, focused) — identical to the user typing '@agent' and picking\n * it from the dropdown. Resolves the agent through MentionAutocompleteService so\n * the chip carries the agent's real id/icon/presets; falls back to a plain-text\n * '@Name ' draft when the agent can't be resolved (e.g. name mismatch).\n *\n * @returns false while the composer view isn't mounted yet — callers may retry.\n */\n public async InsertAgentMention(agentName: string, focus: boolean = true, clearExisting: boolean = true): Promise<boolean> {\n if (!this.inputBox) {\n console.log(`[Omnibar→Chat] InsertAgentMention('${agentName}'): input box not mounted yet — caller will retry`);\n return false;\n }\n if (clearExisting) {\n // Pre-addressing REPLACES any un-sent draft (tagging agent B after agent A\n // must not stack pills).\n this.inputBox.mentionEditor?.clear();\n this.messageText = '';\n }\n try {\n if (!this.mentionAutocomplete.IsInitialized && this.currentUser) {\n console.log(`[Omnibar→Chat] InsertAgentMention('${agentName}'): initializing mention autocomplete…`);\n await this.mentionAutocomplete.initialize(this.currentUser);\n }\n const wanted = agentName.trim().toLowerCase();\n const suggestion = this.mentionAutocomplete\n .getSuggestions(agentName, false, '@')\n .find(s => s.type === 'agent' && s.name.trim().toLowerCase() === wanted);\n if (suggestion) {\n const inserted = this.inputBox.InsertMention(suggestion, focus);\n console.log(`[Omnibar→Chat] InsertAgentMention('${agentName}'): resolved to pill (id=${suggestion.id}) — insert ${inserted ? 'OK' : 'FAILED (editor view not ready)'}`);\n if (inserted) {\n if (focus) {\n this.scheduleFocusReassert(agentName);\n }\n return true;\n }\n return false; // editor view not mounted — caller retries\n }\n console.warn(`[Omnibar→Chat] InsertAgentMention('${agentName}'): agent NOT found in autocomplete (initialized=${this.mentionAutocomplete.IsInitialized}) — falling back to plain text`);\n } catch (e) {\n console.warn(`[Omnibar→Chat] InsertAgentMention('${agentName}'): resolution error — falling back to plain text`, e);\n }\n const mention = agentName.includes(' ') ? `@\"${agentName}\" ` : `@${agentName} `;\n this.SetDraft(mention, focus);\n return true;\n }\n\n /**\n * The insert happens mid-tab-mount; late-arriving chat UI (lists, empty-state\n * autofocus, tab chrome) can steal focus AFTER we set it. Re-assert at settle\n * points — only when focus genuinely left the editor, so we never fight the user.\n */\n private scheduleFocusReassert(context: string): void {\n for (const delay of [300, 900, 1800]) {\n setTimeout(() => {\n const editor = this.inputBox?.mentionEditor;\n if (editor && !editor.HasFocus) {\n const ok = editor.FocusCaretAtEnd();\n console.log(`[Omnibar→Chat] focus re-assert (+${delay}ms) for '${context}': ${ok ? 'refocused' : 'editor gone'}`);\n }\n }, delay);\n }\n }\n\n public SetDraft(text: string, focus: boolean = true): void {\n this.messageText = text;\n if (focus) {\n // The composer mounts/binds on the next tick after messageText flows down.\n setTimeout(() => this.inputBox?.focus(), 50);\n }\n }\n public isSending: boolean = false;\n public isProcessing: boolean = false; // True when waiting for agent/naming response\n public processingMessage: string = 'AI is responding...'; // Message shown during processing\n public isUploadingAttachments: boolean = false; // True when uploading attachments to server\n public uploadingMessage: string = 'Uploading attachments...'; // Message shown during upload\n public converationManagerAgent: MJAIAgentEntityExtended | null = null;\n\n // Track completion timestamps to prevent race conditions with late progress updates\n private completionTimestamps = new Map<string, number>();\n // Track registered streaming callbacks for cleanup\n private registeredCallbacks = new Map<string, (progress: MessageProgressUpdate) => Promise<void>>();\n // After a post-ACK disconnect, keep observing ConversationDetail.Status until\n // the *server* writes Complete/Error (MaxTimePerRun terminates the run).\n // Back off 5s → 15s → 60s so we bound polling cost, not invent a client\n // verdict. Do not paint Error here — that would unregister the streaming\n // callback and make a later server Complete sticky-wrong until reload.\n private static readonly IN_FLIGHT_WATCH_BACKOFF_MS = [5_000, 15_000, 60_000] as const;\n private inFlightWatches = new Map<string, ReturnType<typeof setTimeout>>();\n\n // Track pending attachments from the input box\n private pendingAttachments: PendingAttachment[] = [];\n\n private engine = ConversationEngine.Instance;\n // Shared AI mention/suggestion engine (BaseSingleton — same instance the composer plugins use)\n private mentionAutocomplete = MentionAutocompleteService.Instance;\n\n constructor(\n private dialogService: DialogService,\n private toastService: ToastService,\n private agentService: ConversationAgentService,\n private dataCache: DataCacheService,\n private activeTasks: ActiveTasksService,\n private streamingService: ConversationStreamingService,\n private mentionParser: MentionParserService,\n private attachmentService: ConversationAttachmentService,\n private bridge: ConversationBridgeService,\n private realtimeSession: RealtimeSessionService\n ) {\n super();}\n\n // ── Voice session (Realtime Co-Agent) ───────────────────────────────\n /** True while a live voice session is active — drives the overlay + mic state. */\n public voiceActive: boolean = false;\n private realtimeActiveSub?: Subscription;\n\n async ngOnInit() {\n // Bind provider-aware services to this component's provider.\n const p = this.ProviderToUse;\n this.agentService.Provider = p;\n this.dataCache.Provider = p;\n this.activeTasks.Provider = p;\n this.attachmentService.Provider = p;\n this.realtimeSession.Provider = p;\n\n // Reflect the live voice-session Active flag into a local field for the template.\n this.realtimeActiveSub = this.realtimeSession.Active$.subscribe(active => {\n this.voiceActive = active;\n });\n\n this.converationManagerAgent = await this.agentService.getConversationManagerAgent();\n\n // Warm UserInfoEngine so the PlanModeEnabled getter has the cached settings available\n // (no-op when already loaded; failure just leaves the toggle at its default OFF).\n PlanModePreference.Warm();\n\n // Initialize mention autocomplete (needed for parsing mentions in messages)\n await this.mentionAutocomplete.initialize(this.currentUser);\n\n // Reconnect to any in-progress messages for streaming updates (via global streaming service)\n this.reconnectInProgressMessages();\n }\n\n ngOnChanges(changes: SimpleChanges) {\n // When conversation changes, focus the input\n if (changes['conversationId'] && !changes['conversationId'].firstChange) {\n this.focusInput();\n }\n // Note: initialMessage/initialAttachments handled by setters, inProgressMessageIds handled by setter\n }\n\n ngAfterViewInit() {\n if (this.pendingInitialDraft) {\n const draft = this.pendingInitialDraft;\n this.pendingInitialDraft = null;\n // next tick — the composer's own view finishes mounting first\n setTimeout(() => {\n this.SetDraft(draft, true);\n this.initialDraftApplied.emit();\n }, 50);\n }\n // Focus input on initial load\n this.focusInput();\n\n // Mark component as ready\n this._isComponentReady = true;\n\n // If there's an initial message to send (from empty state), send it automatically\n if (this._initialMessage || (this._initialAttachments && this._initialAttachments.length > 0)) {\n this.triggerInitialSend();\n }\n }\n\n /**\n * Triggers sending of initial message and attachments.\n * Called from setter or ngAfterViewInit when conditions are met.\n */\n private triggerInitialSend(): void {\n const message = this._initialMessage;\n const attachments = this._initialAttachments;\n const hasContent = !!message || !!(attachments && attachments.length > 0);\n\n if (!hasContent || !this.conversationId || UUIDsEqual(this._autoSentForConversationId, this.conversationId)) {\n return;\n }\n this._autoSentForConversationId = this.conversationId;\n\n // Set pending attachments before sending\n if (attachments && attachments.length > 0) {\n this.pendingAttachments = [...attachments];\n }\n\n Promise.resolve().then(() => {\n this.initialMessageAutoSendStarted.emit({ conversationId: this.conversationId });\n });\n\n // Use setTimeout to ensure we're outside of change detection cycle\n setTimeout(async () => {\n const sent = await this.sendMessageWithText(message || '');\n if (!sent) {\n this._autoSentForConversationId = null;\n this.initialMessageAutoSendFailed.emit({ conversationId: this.conversationId });\n }\n }, 100);\n }\n\n ngOnDestroy() {\n // Unregister all streaming callbacks\n this.unregisterAllCallbacks();\n this.clearInFlightWatches();\n this.realtimeActiveSub?.unsubscribe();\n // If the user navigates away mid-call, tear the session down.\n if (this.realtimeSession.IsActive) {\n void this.realtimeSession.EndRealtimeSession();\n }\n }\n\n /**\n * Resolve the agent the voice session should front for THIS conversation.\n * Mirrors the routing precedence used for text turns ({@link routeMessage}):\n * 1. last non-Sage agent (continuity)\n * 2. per-conversation pinned default\n * 3. embedder-supplied default\n * 4. Sage fallback\n * Returns null only if Sage itself failed to load.\n */\n public resolveCurrentAgentId(): string | null {\n return this.findLastNonSageAgentId()\n ?? this.conversationDefaultAgentId\n ?? this.defaultAgentId\n ?? this.converationManagerAgent?.ID\n ?? null;\n }\n\n /**\n * The agent the '/' skill picker should narrow to. Mirrors routing's priority: an explicit\n * `@agent` chip already in the draft wins (routeMessage's Priority 1), else the agent the message\n * would otherwise go to ({@link resolveCurrentAgentId}). Bound to `mj-ai-composer`'s\n * `TargetAgentId`; null = unknown, no narrowing.\n */\n public get pickerTargetAgentId(): string | null {\n if (this.mentionedAgentId === undefined) {\n const chips = this.inputBox?.getMentionChipsData() || [];\n this.mentionedAgentId = chips.find(chip => chip.type === 'agent')?.id ?? null;\n }\n return this.mentionedAgentId ?? this.resolveCurrentAgentId();\n }\n\n /**\n * Memo for the first `@agent` chip in the draft, so the template-bound\n * {@link pickerTargetAgentId} does not walk the editor DOM on every change-detection cycle.\n *\n * `undefined` = dirty, recompute on next read; `null` = computed, no `@agent` chip present.\n * The two are NOT interchangeable — collapsing them to `null` is what makes a cleared or restored\n * draft read as \"no chip\" forever.\n *\n * Invalidated from {@link messageText}'s setter, which is the only choke point every chip change\n * passes through. Chips reach the editor by two kinds of path and only one announces itself:\n *\n * - user editing (autocomplete insert, backspace-delete, `InsertMention`) and `clear()` all end\n * in the editor's `onInput()`, which emits `valueChange` -> {@link OnComposerValueChanged},\n * which assigns `messageText`;\n * - a programmatic write — a restored draft (`[initialDraft]` -> {@link SetDraft}), a post-send\n * reset, or a host assigning `messageText` directly — goes `[value]` ->\n * `ngModel.writeValue` -> `setEditorContent`, which rebuilds the chips with `appendChild` (or\n * empties the editor) and never calls `onInput()`. No `valueChange`, so no hook fires.\n *\n * Invalidate-and-lazy rather than eager refresh, because an eager read in the setter would be too\n * early: `ngModel` writes the editor on a later change-detection pass, so the read would predate\n * the chips it wants. Marking dirty is timing-independent — the recompute happens on the next\n * read, by which point the editor holds the new content.\n *\n * The picker can be opened by the Skills button as well as by typing `/`, so \"the next keystroke\n * would repair it\" is not a defence: the button path takes whatever the memo holds.\n */\n private mentionedAgentId: string | null | undefined = undefined;\n\n /** True when the mic button should be enabled (have an agent + not disabled). */\n public get canStartRealtime(): boolean {\n return !this.disabled && !this.voiceActive && !!this.resolveCurrentAgentId();\n }\n\n /**\n * Display name of the agent the voice session fronts. Resolved here (this component\n * owns the conversation's routing context) and passed to RealtimeSessionService at\n * session start so the chat-area-hosted overlay can read it from the service.\n */\n private resolveRealtimeAgentName(): string {\n const agentId = this.resolveCurrentAgentId();\n if (agentId) {\n const match = this.mentionAutocomplete\n .getAvailableAgents()\n .find(a => UUIDsEqual(a.ID, agentId));\n if (match?.Name) {\n return match.Name;\n }\n }\n return this.converationManagerAgent?.Name ?? 'Sage';\n }\n\n /** True while the \"Start a voice call with…\" agent picker popover is open. */\n public showRealtimeAgentPicker: boolean = false;\n\n /**\n * CDK connected-overlay positions for the voice agent picker. Preferred: open UPWARD,\n * right edge aligned to the composer's right edge (matching the old absolute placement).\n * Fallback: open downward when there isn't room above. Because the popover renders in the\n * body-level CDK overlay container (with `cdkConnectedOverlayPush`), it escapes the chat\n * overlay's `overflow: hidden` border and can never clip at the top of a narrow overlay.\n */\n public readonly pickerOverlayPositions: ConnectedPosition[] = [\n { originX: 'end', originY: 'top', overlayX: 'end', overlayY: 'bottom', offsetY: -8 },\n { originX: 'end', originY: 'bottom', overlayX: 'end', overlayY: 'top', offsetY: 8 },\n ];\n\n /**\n * `MJ: User Settings` key persisting the user's co-agent choice for realtime calls\n * (server-side, cross-device — never localStorage). Stored shape: `{\"coAgentId\":\n * string | null}` — `null` is an explicit \"Auto\" choice that overwrites an older pick.\n */\n private static readonly CoAgentPrefKey = 'mj.realtimeVoice.coAgent.v1';\n\n /**\n * The persisted co-agent preference, loaded just before the picker opens (and read by\n * the instant-start path). `null` = no preference / explicit \"Auto\".\n */\n public voicePickerDefaultCoAgentId: string | null = null;\n\n /**\n * Agents the voice picker offers — the same cached set the @mention\n * autocomplete and {@link resolveRealtimeAgentName} use, so the picker can\n * never offer an agent the conversation couldn't otherwise route to.\n */\n public get voicePickerAgents(): MJAIAgentEntityExtended[] {\n return this.mentionAutocomplete.getAvailableAgents();\n }\n\n /**\n * The ACTIVE Realtime-type co-agent candidates — the same run-permission-filtered\n * cached set as {@link voicePickerAgents}, narrowed to the Realtime agent type. The\n * picker shows its co-agent selector only when more than one exists.\n */\n public get voicePickerCoAgents(): MJAIAgentEntityExtended[] {\n return FilterRealtimeCoAgents(this.mentionAutocomplete.getAvailableAgents());\n }\n\n /** The agent the default resolution would call — preselected in the picker. */\n public get voicePickerDefaultAgentId(): string | null {\n return this.resolveCurrentAgentId();\n }\n\n /**\n * Start a real-time voice session fronting the conversation's current agent.\n * Client-direct: the RealtimeSessionService mints an ephemeral token and connects\n * the browser straight to the realtime provider over WebRTC. The \"call mode\"\n * overlay itself is hosted by the conversation chat area (driven by Active$).\n *\n * NEW vs EXISTING conversation:\n * - When an agent has already participated (a prior non-Sage AI turn exists),\n * start immediately with the resolved agent — zero added friction.\n * - When the conversation has NO prior agent participation (new / empty\n * conversation), the resolution would silently fall through to a default\n * the user never chose — so show a compact agent picker instead and start\n * with whichever agent they pick.\n */\n public async onStartRealtime(): Promise<void> {\n if (!this.canStartRealtime) {\n return;\n }\n // New/empty conversation (no prior agent turn): let the user choose who\n // to call. Falls through to the immediate path if the agent cache is\n // empty (nothing to pick from — the resolved default is the only option).\n if (!this.findLastNonSageAgentId() && this.voicePickerAgents.length > 0) {\n await this.openRealtimeAgentPicker();\n return;\n }\n const targetAgentId = this.resolveCurrentAgentId();\n if (!targetAgentId) {\n this.toastService.error('No agent available for a voice session.');\n return;\n }\n const coAgentId = await this.resolveInstantCoAgentId(targetAgentId);\n await this.startRealtimeWithAgent(targetAgentId, this.resolveRealtimeAgentName(), null, coAgentId);\n }\n\n /**\n * Caret-next-to-the-phone click: open the agent/co-agent/model picker ON DEMAND, even\n * when the conversation already has agent history (where the plain phone click\n * instant-starts). The resolved agent is preselected, so \"open → Start\" matches the\n * instant path while keeping the co-agent (and, for authorized users, voice-model)\n * choice one click away. Falls through to the instant path when there is nothing to\n * pick from.\n */\n public async onRealtimeOptions(): Promise<void> {\n if (!this.canStartRealtime) {\n return;\n }\n if (this.voicePickerAgents.length > 0) {\n await this.openRealtimeAgentPicker();\n return;\n }\n void this.onStartRealtime();\n }\n\n /** Loads the persisted co-agent preference, then shows the picker (pref preselected). */\n private async openRealtimeAgentPicker(): Promise<void> {\n this.voicePickerDefaultCoAgentId = await this.loadPersistedCoAgentId();\n this.showRealtimeAgentPicker = true;\n }\n\n /** User confirmed an agent (+ optional co-agent / voice model) in the voice picker — start the call. */\n public async onRealtimeAgentPicked(pick: RealtimeAgentPick): Promise<void> {\n this.showRealtimeAgentPicker = false;\n this.persistCoAgentChoice(pick.CoAgentId);\n await this.startRealtimeWithAgent(\n pick.Agent.ID,\n pick.Agent.Name || this.resolveRealtimeAgentName(),\n pick.PreferredModelId,\n pick.CoAgentId,\n BuildRealtimeConfigOverridesJson(pick.PreferredModelId, pick.PreferredVoice),\n pick.RecordingConsent\n );\n }\n\n /**\n * Reads the persisted co-agent preference from `MJ: User Settings` (via\n * `UserInfoEngine`'s cached settings). Defensive: any failure or malformed payload\n * resolves to `null` (Auto — the server's co-agent resolution chain).\n */\n private async loadPersistedCoAgentId(): Promise<string | null> {\n try {\n await UserInfoEngine.Instance.Config();\n const raw = UserInfoEngine.Instance.GetSetting(MessageInputComponent.CoAgentPrefKey);\n if (!raw) {\n return null;\n }\n const parsed = JSON.parse(raw) as { coAgentId?: string | null };\n return typeof parsed.coAgentId === 'string' && parsed.coAgentId.length > 0 ? parsed.coAgentId : null;\n } catch {\n return null;\n }\n }\n\n /** Persists the user's co-agent choice (including explicit \"Auto\" = null) cross-device. */\n private persistCoAgentChoice(coAgentId: string | null): void {\n try {\n UserInfoEngine.Instance.SetSettingDebounced(\n MessageInputComponent.CoAgentPrefKey,\n JSON.stringify({ coAgentId: coAgentId ?? null })\n );\n } catch (error) {\n console.warn('[MessageInput] Failed to persist co-agent preference:', error);\n }\n }\n\n /**\n * Co-agent for the INSTANT start path (plain phone click, no picker): the persisted\n * preference is honored when it's still a valid candidate AND its pairing rows (if\n * any) allow the resolved target. Anything else falls back to `null` — the server's\n * co-agent resolution chain — so a stale/deactivated/incompatible preference can never\n * block the friction-free start (pairings constrain a chosen co-agent; they never\n * mandate one).\n */\n private async resolveInstantCoAgentId(targetAgentId: string): Promise<string | null> {\n const preferred = await this.loadPersistedCoAgentId();\n if (!preferred) {\n return null;\n }\n const isValidCandidate = this.voicePickerCoAgents.some(a => UUIDsEqual(a.ID, preferred));\n if (!isValidCandidate) {\n return null;\n }\n const pairings = await LoadCoAgentPairings(this.ProviderToUse, preferred);\n return PairingsAllowTarget(pairings, targetAgentId) ? preferred : null;\n }\n\n /** User dismissed the voice picker without starting a call. */\n public onRealtimeAgentPickerCancelled(): void {\n this.showRealtimeAgentPicker = false;\n }\n\n /**\n * Shared session-start path for both the immediate (existing conversation)\n * and picker (new conversation / caret options) flows. The agent NAME is passed\n * through to RealtimeSessionService so the chat-area-hosted overlay banner (AgentName$)\n * shows who the call fronts without re-resolving. An explicit voice-model choice\n * (authorization-gated, picker only) rides along as `preferredModelId` — the server\n * uses exactly that model or fails with a clear reason (no silent fallback) — and is\n * mirrored into `configOverridesJson` (`{\"realtime\":{\"modelPreference\":…}}`, the\n * pinned override envelope). An explicit co-agent choice (picker pick or persisted\n * preference) rides along as `coAgentId`.\n *\n * Interactive-channel tools (e.g. the live whiteboard's `Whiteboard_*` set) are NOT\n * passed here — the session service resolves the active channel plugins from the\n * `MJ: AI Agent Channels` registry and aggregates their tool sets at mint itself.\n */\n private async startRealtimeWithAgent(\n agentId: string,\n agentName: string,\n preferredModelId?: string | null,\n coAgentId?: string | null,\n configOverridesJson?: string | null,\n recordingConsent?: boolean | null\n ): Promise<void> {\n try {\n await this.realtimeSession.StartRealtimeSession(\n agentId,\n this.conversationId,\n null,\n agentName,\n preferredModelId ?? null,\n null,\n coAgentId ?? null,\n configOverridesJson ?? null,\n recordingConsent ?? null,\n null,\n // App awareness: the app the session runs in + the live app-context snapshot (where the\n // user is, what they see, capability manifest) — drives the server-side app cascade + the\n // mint-time prompt injection, and seeds the ClientContextChannel's streaming.\n this.applicationId,\n this.appContext as AppContextSnapshot | null\n );\n } catch (error) {\n console.error('Failed to start voice session:', error);\n this.toastService.error('Could not start the voice session.');\n }\n }\n\n /**\n * Focus the message input textarea\n */\n private focusInput(): void {\n // Use setTimeout to ensure DOM is ready\n setTimeout(() => {\n if (this.inputBox) {\n this.inputBox.focus();\n }\n }, 100);\n }\n\n /**\n * Reconnect to in-progress messages for streaming updates via global streaming service.\n * This is called when:\n * 1. Component initializes (ngOnInit)\n * 2. Conversation changes (ngOnChanges)\n * 3. User returns to a conversation with in-progress messages\n * 4. Parent component explicitly triggers reconnection\n */\n public reconnectInProgressMessages(): void {\n if (!this.inProgressMessageIds || this.inProgressMessageIds.length === 0) {\n return;\n }\n\n // Unregister any previously registered callbacks for this component\n this.unregisterAllCallbacks();\n\n // Register new callbacks for each in-progress message\n for (const messageId of this.inProgressMessageIds) {\n // Create callback bound to this message ID\n const callback = this.createMessageProgressCallback(messageId);\n\n // Store reference for cleanup\n this.registeredCallbacks.set(messageId, callback);\n\n // Register with streaming service\n this.streamingService.registerMessageCallback(messageId, callback);\n }\n }\n\n /**\n * Create a progress callback for a specific message ID.\n * This callback will be invoked by the streaming service when progress updates arrive.\n */\n private createMessageProgressCallback(messageId: string): (progress: MessageProgressUpdate) => Promise<void> {\n // Resolve the message once and reuse it for the callback's lifetime: streamed\n // final-response updates arrive per content delta, and re-awaiting the cache on\n // every delta both wastes work and (on a cold cache) races concurrent loads.\n let resolvedMessage: Awaited<ReturnType<DataCacheService['getConversationDetail']>> = null;\n return async (progress: MessageProgressUpdate) => {\n try {\n // Get message from cache (single source of truth)\n const message = (resolvedMessage ??= await this.dataCache.getConversationDetail(messageId, this.currentUser));\n\n if (!message) {\n console.warn(`[StreamingCallback] Message ${messageId} not found in cache`);\n return;\n }\n\n // Skip if already complete or errored\n if (message.Status === 'Complete' || message.Status === 'Error') {\n console.log(`[StreamingCallback] Message ${messageId} is ${message.Status}, ignoring progress update`);\n return;\n }\n\n // Check if message was marked as completed (prevents race condition)\n const completionTime = this.completionTimestamps.get(messageId);\n if (completionTime) {\n console.log(`[StreamingCallback] Message ${messageId} marked complete at ${new Date(completionTime).toISOString()}, ignoring late progress update`);\n return;\n }\n\n // Streamed final-response content: the service accumulates deltas, so\n // progress.streaming.content is always the full reply text so far — assign it.\n // The completion flow (above guards + the 'complete' path) reconciles the\n // bubble with the server-saved final message, so no append/merge is needed here.\n if (progress.streaming) {\n message.Message = progress.streaming.content;\n this.messageSent.emit(message);\n // Keep the tasks dropdown on a stable status line rather than the growing reply text.\n this.activeTasks.updateStatusByConversationDetailId(message.ID, 'Responding…');\n return;\n }\n\n // Default: plain message (used by RunAIAgentResolver and TaskOrchestrator without step info)\n message.Message = progress.message;\n\n // TaskOrchestrator with step info: add formatted header\n // Prefer hierarchical step (e.g., \"2.1.3\") over flat stepCount\n if (progress.resolver === 'TaskOrchestrator') {\n const stepDisplay = progress.metadata?.progress?.hierarchicalStep || progress.stepCount;\n if (stepDisplay != null) {\n message.Message = `**Step ${stepDisplay}**\\n\\n${progress.message}`;\n }\n }\n\n // Server now saves progress - client only updates in-memory and emits for UI\n // (Prevents race condition where client's late save overwrites server's final Status)\n\n // CRITICAL: Emit update to trigger UI refresh\n this.messageSent.emit(message);\n\n // CRITICAL: Update ActiveTasksService to keep the tasks dropdown in sync\n this.activeTasks.updateStatusByConversationDetailId(message.ID, progress.message);\n\n console.log(`[StreamingCallback] Updated message ${messageId}: ${progress.taskName || 'Agent'}`);\n } catch (error) {\n console.error(`[StreamingCallback] Error updating message ${messageId}:`, error);\n }\n };\n }\n\n /**\n * Unregister all callbacks registered by this component.\n * Called during cleanup and when switching conversations.\n */\n private unregisterAllCallbacks(): void {\n if (this.registeredCallbacks.size === 0) {\n return;\n }\n\n console.log(`🧹 Unregistering ${this.registeredCallbacks.size} message callbacks`);\n\n for (const [messageId, callback] of this.registeredCallbacks) {\n this.streamingService.unregisterMessageCallback(messageId, callback);\n }\n\n this.registeredCallbacks.clear();\n }\n\n get canSend(): boolean {\n return !this.disabled && !this.isSending && this.messageText.trim().length > 0;\n }\n\n /**\n * Handle attachments changed from the input box\n */\n onAttachmentsChanged(attachments: PendingAttachment[]): void {\n this.pendingAttachments = attachments;\n }\n\n /**\n * Handle attachment errors from the input box\n */\n onAttachmentError(error: string): void {\n this.toastService.error(error);\n }\n\n /**\n * Handle text submitted from the input box\n */\n async onTextSubmitted(text: string): Promise<void> {\n // Check if we have either text or attachments\n const hasText = text && text.trim().length > 0;\n const hasAttachments = this.pendingAttachments.length > 0;\n\n if (!hasText && !hasAttachments) {\n return;\n }\n\n // In empty state mode, just emit the data and let parent handle conversation creation\n if (this.emptyStateMode) {\n const attachmentsToEmit = [...this.pendingAttachments];\n this.pendingAttachments = [];\n this.messageText = '';\n this.emptyStateSubmit.emit({ text: text?.trim() || '', attachments: attachmentsToEmit });\n return;\n }\n\n this.isSending = true;\n\n // Store attachments locally since we'll clear them after send\n const attachmentsToSave = [...this.pendingAttachments];\n\n try {\n const messageDetail = await this.createMessageDetailFromText(text?.trim() || '');\n\n const saved = await messageDetail.Save();\n\n if (saved) {\n // Save attachments if any were pending\n // Attachments are stored in ConversationDetailAttachment table and loaded\n // separately when building AI messages - no need to add tokens to Message field\n if (attachmentsToSave.length > 0) {\n // Show upload indicator for attachments\n this.isUploadingAttachments = true;\n this.uploadingMessage = `Uploading ${attachmentsToSave.length} attachment${attachmentsToSave.length > 1 ? 's' : ''}...`;\n this.uploadStateChanged.emit({ isUploading: true, message: this.uploadingMessage });\n\n let attachmentRejection: string | null = null;\n try {\n await this.attachmentService.saveAttachments(\n messageDetail.ID,\n attachmentsToSave,\n this.currentUser\n );\n } catch (attachmentError) {\n console.error('Failed to save attachments:', attachmentError);\n attachmentRejection = attachmentError instanceof Error\n ? attachmentError.message\n : 'Some attachments could not be saved';\n } finally {\n this.isUploadingAttachments = false;\n this.uploadStateChanged.emit({ isUploading: false, message: '' });\n }\n\n // Plan §6: when attachments are rejected, the message itself must\n // not go through. Roll back the ConversationDetail and notify the\n // user with the server's rejection message so they can see exactly\n // why and either remove the file or upload a supported one. The\n // text and pending attachments stay in the input so the user can edit.\n if (attachmentRejection) {\n MJNotificationService.Instance?.CreateSimpleNotification(attachmentRejection, 'error', 5000);\n try {\n await messageDetail.Delete();\n } catch (rollbackErr) {\n console.error('Failed to roll back conversation detail after attachment rejection:', rollbackErr);\n }\n this.isSending = false;\n return;\n }\n }\n\n // Clear pending attachments after successful send\n this.pendingAttachments = [];\n\n await this.handleSuccessfulSend(messageDetail);\n } else {\n this.handleSendFailure(messageDetail);\n }\n } catch (error) {\n this.handleSendError(error);\n } finally {\n this.isSending = false;\n }\n }\n\n /**\n * Toggle sticky Plan Mode for THIS conversation (or the pending-new bucket on the\n * new-conversation composer). Writes through {@link PlanModePreference} — the\n * {@link PlanModeEnabled} getter reads the same cached setting, so ALL live composer\n * instances flip together, and the value survives component recreation and sessions\n * until the user turns it off or approves a plan.\n */\n public TogglePlanMode(): void {\n PlanModePreference.Set(this.conversationId, !this.PlanModeEnabled);\n }\n\n async onSend(): Promise<void> {\n if (!this.canSend) return;\n\n this.isSending = true;\n try {\n const messageDetail = await this.createMessageDetail();\n const saved = await messageDetail.Save();\n\n if (saved) {\n await this.handleSuccessfulSend(messageDetail);\n } else {\n this.handleSendFailure(messageDetail);\n }\n } catch (error) {\n this.handleSendError(error);\n } finally {\n this.isSending = false;\n }\n }\n\n /**\n * Send a message with custom text WITHOUT modifying the visible messageText input\n * Used for suggested responses and initial messages from empty state.\n * Also saves any pending attachments.\n *\n * `extraAttachments` is an escape hatch for callers that programmatically\n * attached something via `AddArtifactAttachment` and want to send in the same\n * tick — the `attachmentsChanged` event chain hasn't propagated yet, so\n * `this.pendingAttachments` may not contain the attachment. Pass it in\n * explicitly and we merge + dedupe (by `id`) before saving.\n */\n public async sendMessageWithText(text: string, extraAttachments?: PendingAttachment[]): Promise<boolean> {\n const merged: PendingAttachment[] = (() => {\n if (!extraAttachments || extraAttachments.length === 0) {\n return [...this.pendingAttachments];\n }\n const seen = new Set<string>();\n const out: PendingAttachment[] = [];\n for (const a of [...this.pendingAttachments, ...extraAttachments]) {\n if (seen.has(a.id)) continue;\n seen.add(a.id);\n out.push(a);\n }\n return out;\n })();\n\n const hasText = text && text.trim().length > 0;\n const hasAttachments = merged.length > 0;\n\n if (!hasText && !hasAttachments) {\n return false;\n }\n\n if (this.isSending) {\n return false;\n }\n\n this.isSending = true;\n const attachmentsToSave = merged;\n\n try {\n const detail = await this.dataCache.createConversationDetail(this.currentUser);\n detail.ConversationID = this.conversationId;\n detail.Message = text?.trim() || '';\n detail.Role = 'User';\n detail.UserID = this.currentUser.ID; // Set the user who sent the message\n\n if (this.parentMessageId) {\n detail.ParentID = this.parentMessageId;\n }\n\n const saved = await detail.Save();\n\n if (saved) {\n // Save attachments if any were pending\n if (attachmentsToSave.length > 0) {\n // Show upload indicator for attachments\n this.isUploadingAttachments = true;\n this.uploadingMessage = `Uploading ${attachmentsToSave.length} attachment${attachmentsToSave.length > 1 ? 's' : ''}...`;\n this.uploadStateChanged.emit({ isUploading: true, message: this.uploadingMessage });\n\n let attachmentRejection: string | null = null;\n try {\n await this.attachmentService.saveAttachments(\n detail.ID,\n attachmentsToSave,\n this.currentUser\n );\n } catch (attachmentError) {\n console.error('Failed to save attachments:', attachmentError);\n attachmentRejection = attachmentError instanceof Error\n ? attachmentError.message\n : 'Some attachments could not be saved';\n } finally {\n this.isUploadingAttachments = false;\n this.uploadStateChanged.emit({ isUploading: false, message: '' });\n }\n\n // Plan §6: roll back the message when attachments are rejected so\n // the user sees the rejection clearly instead of the agent answering\n // a question that was supposed to include the file.\n if (attachmentRejection) {\n MJNotificationService.Instance?.CreateSimpleNotification(attachmentRejection, 'error', 5000);\n try {\n await detail.Delete();\n } catch (rollbackErr) {\n console.error('Failed to roll back conversation detail after attachment rejection:', rollbackErr);\n }\n this.isSending = false;\n return false;\n }\n }\n\n // Clear pending attachments after successful send\n this.pendingAttachments = [];\n\n // Also clear the mention editor's content + its own attachments list.\n // The user-initiated send path (MessageInputBoxComponent.onSendClick)\n // calls mentionEditor.clear() — we bypass that path here, so the chips\n // would otherwise stay on screen after the message goes out.\n this.inputBox?.mentionEditor?.clear();\n\n this.messageSent.emit(detail);\n\n const mentionResult = this.parseMentionsFromMessage(detail.Message);\n const isFirstMessage = this.conversationHistory.length === 0;\n await this.routeMessage(detail, mentionResult, isFirstMessage);\n return true;\n } else {\n this.handleSendFailure(detail);\n return false;\n }\n } catch (error) {\n this.handleSendError(error);\n return false;\n } finally {\n this.isSending = false;\n }\n }\n\n /**\n * Creates and configures a new conversation detail message\n */\n private async createMessageDetail(): Promise<MJConversationDetailEntity> {\n const detail = await this.dataCache.createConversationDetail(this.currentUser);\n\n detail.ConversationID = this.conversationId;\n detail.Message = this.messageText.trim();\n detail.Role = 'User';\n detail.UserID = this.currentUser.ID; // Set the user who sent the message\n\n if (this.parentMessageId) {\n detail.ParentID = this.parentMessageId;\n }\n\n return detail;\n }\n\n /**\n * Creates and configures a new conversation detail message from provided text\n */\n private async createMessageDetailFromText(text: string): Promise<MJConversationDetailEntity> {\n const detail = await this.dataCache.createConversationDetail(this.currentUser);\n\n detail.ConversationID = this.conversationId;\n detail.Message = text;\n detail.Role = 'User';\n detail.UserID = this.currentUser.ID; // Set the user who sent the message\n\n if (this.parentMessageId) {\n detail.ParentID = this.parentMessageId;\n }\n\n return detail;\n }\n\n /**\n * Handles successful message send - routes to appropriate agent\n */\n private async handleSuccessfulSend(messageDetail: MJConversationDetailEntity): Promise<void> {\n this.messageSent.emit(messageDetail);\n this.messageText = '';\n\n const mentionResult = this.parseMentionsFromMessage(messageDetail.Message);\n const isFirstMessage = this.conversationHistory.length === 0;\n\n await this.routeMessage(messageDetail, mentionResult, isFirstMessage);\n this.refocusTextarea();\n }\n\n /**\n * Parses mentions from the message for routing decisions\n */\n private parseMentionsFromMessage(message: string): MentionParseResult {\n const mentionResult = this.mentionParser.parseMentions(\n message,\n this.mentionAutocomplete.getAvailableAgents(),\n this.mentionAutocomplete.getAvailableUsers()\n );\n\n return mentionResult;\n }\n\n /**\n * Routes the message to the appropriate agent or Sage based on context.\n * Priority: explicit @mention > prior-agent continuity > embedder-supplied\n * default agent > Sage fallback.\n */\n private async routeMessage(\n messageDetail: MJConversationDetailEntity,\n mentionResult: MentionParseResult,\n isFirstMessage: boolean\n ): Promise<void> {\n // A Plan Mode choice made on the new-conversation composer (no conversation yet) lives in a\n // pending bucket — the FIRST routed message claims it onto the real conversation so the\n // toggle carries across the empty-state → chat-area transition without bleeding into other\n // conversations.\n if (isFirstMessage && messageDetail.ConversationID) {\n PlanModePreference.ClaimPendingNew(messageDetail.ConversationID);\n }\n\n // Snapshot user-requested skills once, before any routing branch, so every invocation path\n // forwards the same set for this message. Derived from the SAVED MESSAGE TEXT via the shared\n // MentionParser (`@{\"type\":\"skill\",…}` JSON mentions — same encoding as @agent/#entity), so the\n // source of truth is the message itself, not composer DOM state. Chip-DOM read is the fallback\n // for any path where the parsed result isn't available.\n this._pendingRequestedSkillIDs = mentionResult.skillMentions?.length\n ? mentionResult.skillMentions.map(m => m.id)\n : this.collectRequestedSkillIDs();\n\n // Priority 1: Direct @mention\n if (mentionResult.agentMention) {\n await this.handleDirectMention(messageDetail, mentionResult.agentMention, isFirstMessage);\n return;\n }\n\n // Priority 2: Check for previous agent with intent check\n const lastAgentId = this.findLastNonSageAgentId();\n if (lastAgentId) {\n await this.handleAgentContinuity(messageDetail, lastAgentId, mentionResult, isFirstMessage);\n return;\n }\n\n // Priority 3: User's per-conversation pinned default agent — sourced\n // from MJConversationEntity.DefaultAgentID. Wins over the embedder's\n // default because it represents an explicit user choice on this\n // conversation (e.g. \"always route to Research Agent for this thread\").\n if (this.conversationDefaultAgentId) {\n await this.handleAgentContinuity(\n messageDetail, this.conversationDefaultAgentId, mentionResult, isFirstMessage,\n );\n return;\n }\n\n // Priority 4: Embedder-supplied default agent. Set by chat surfaces\n // that have a specialist agent for the context (e.g. Form Builder\n // cockpit). Only kicks in when nothing more explicit is present —\n // @mention always wins, conversation continuity always wins. The\n // intent is to skip Sage's default delegation when the embedder\n // already knows what agent owns this conversation.\n if (this.defaultAgentId) {\n await this.handleAgentContinuity(\n messageDetail, this.defaultAgentId, mentionResult, isFirstMessage,\n );\n return;\n }\n\n // Priority 5: Check if Sage was explicitly @mentioned with a config preset\n // If so, treat it like agent continuity so the config preset is preserved\n if (this.converationManagerAgent?.ID) {\n const sageConfigPreset = this.conversationId\n ? await this.agentService.FindConfigurationPresetForAgent(\n this.conversationId,\n this.converationManagerAgent.ID\n )\n : undefined;\n if (sageConfigPreset) {\n // User explicitly @mentioned Sage with a config - use the shared execution helper directly\n // Pass the already-found config preset to avoid redundant history search\n await this.executeRouteWithNaming(\n () => this.executeAgentContinuation(\n messageDetail,\n this.converationManagerAgent!.ID,\n this.converationManagerAgent!.Name || 'Sage',\n messageDetail.ConversationID,\n null, // Sage doesn't use payload continuity\n null, // Sage doesn't use artifact info\n sageConfigPreset // Pass the already-found config preset\n ),\n messageDetail.Message,\n isFirstMessage,\n messageDetail.ConversationID\n );\n return;\n }\n }\n\n // Priority 6: No context - use Sage with default config\n await this.handleNoAgentContext(messageDetail, mentionResult, isFirstMessage);\n }\n\n /**\n * Handles routing when user directly mentions an agent with @\n */\n private async handleDirectMention(\n messageDetail: MJConversationDetailEntity,\n agentMention: Mention,\n isFirstMessage: boolean\n ): Promise<void> {\n // The agentMention already has configurationId from JSON parsing\n // If it wasn't in JSON (legacy format), try to get from chip data\n if (!agentMention.configurationId) {\n const chipData = this.inputBox?.getMentionChipsData() || [];\n const agentChip = chipData.find(chip => chip.id === agentMention.id && chip.type === 'agent');\n if (agentChip?.presetId) {\n agentMention.configurationId = agentChip.presetId;\n }\n }\n\n if (agentMention.configurationId) {\n //console.log(`🎯 Agent mention has configuration ID: ${agentMention.configurationId}`);\n }\n\n await this.executeRouteWithNaming(\n () => this.invokeAgentDirectly(messageDetail, agentMention, messageDetail.ConversationID),\n messageDetail.Message,\n isFirstMessage,\n messageDetail.ConversationID\n );\n }\n\n /**\n * Handles routing when there's a previous non-Sage agent in the conversation.\n *\n * LATENCY OPTIMIZATION (PR #2309 / plans/agent-latency-optimization.md — Opt #1):\n * Previously, this method made a separate LLM call via checkContinuityIntent() to decide\n * whether the user's new message was still directed at the previous agent or should be\n * routed to Sage. That call added ~300ms of latency on every message in a conversation\n * with an active agent — the single largest source of non-inference overhead on the client.\n *\n * The heuristic replacement is simple: if a previous non-Sage agent exists, always continue\n * with it. The user can @mention a different agent (or Sage) to explicitly switch. This is\n * more predictable and eliminates a common source of confusion where the intent check\n * incorrectly rerouted messages away from the active agent.\n *\n * The checkContinuityIntent() method and the underlying checkAgentContinuityIntent() service\n * method are preserved (not deleted) so we can reintroduce intent checking in the future\n * when browser-local inference is fast enough (~20-50ms) to do this without blocking the\n * user. See PR #2309 for the full discussion.\n */\n private async handleAgentContinuity(\n messageDetail: MJConversationDetailEntity,\n lastAgentId: string,\n mentionResult: MentionParseResult,\n isFirstMessage: boolean\n ): Promise<void> {\n // COMMENTED OUT — LLM intent check removed for latency optimization (see JSDoc above).\n // const intentResult = await this.checkContinuityIntent(lastAgentId, messageDetail.Message);\n //\n // if (intentResult.decision === 'YES') {\n // await this.executeRouteWithNaming(\n // () => this.continueWithAgent(\n // messageDetail,\n // lastAgentId,\n // this.conversationId,\n // intentResult.targetArtifactVersionId\n // ),\n // messageDetail.Message,\n // isFirstMessage\n // );\n // } else {\n // await this.executeRouteWithNaming(\n // () => this.processMessageThroughAgent(messageDetail, mentionResult),\n // messageDetail.Message,\n // isFirstMessage\n // );\n // }\n\n // Always continue with the previous agent — user can @mention another agent to switch.\n await this.executeRouteWithNaming(\n () => this.continueWithAgent(\n messageDetail,\n lastAgentId,\n messageDetail.ConversationID,\n undefined // artifact version targeting unavailable without intent check\n ),\n messageDetail.Message,\n isFirstMessage,\n messageDetail.ConversationID\n );\n }\n\n /**\n * Handles routing when there's no previous agent context\n */\n private async handleNoAgentContext(\n messageDetail: MJConversationDetailEntity,\n mentionResult: MentionParseResult,\n isFirstMessage: boolean\n ): Promise<void> {\n await this.executeRouteWithNaming(\n () => this.processMessageThroughAgent(messageDetail, mentionResult),\n messageDetail.Message,\n isFirstMessage,\n messageDetail.ConversationID\n );\n }\n\n /**\n * Finds the last agent ID that isn't Sage\n */\n private findLastNonSageAgentId(): string | null {\n const lastAIMessage = this.conversationHistory\n .slice()\n .reverse()\n .find(msg =>\n msg.Role === 'AI' &&\n msg.AgentID &&\n !UUIDsEqual(msg.AgentID, this.converationManagerAgent?.ID)\n );\n\n return lastAIMessage?.AgentID || null;\n }\n\n /**\n * Checks if message should continue with the previous agent\n * Emits events to show temporary intent checking message in conversation\n */\n private async checkContinuityIntent(agentId: string, message: string) {\n // FAST PATH: If message contains form response syntax, skip the intent check entirely\n // Form responses always continue with the agent that requested the form\n // Don't show \"Analyzing intent...\" message for this obvious case\n if (ConversationUtility.ContainsFormResponse(message)) {\n console.log('✅ Form response detected, skipping intent check UI (fast path)');\n return {\n decision: 'YES' as const,\n reasoning: 'User submitted a form response to the previous agent'\n };\n }\n\n // Emit event to show temporary \"Analyzing intent...\" message in conversation\n this.intentCheckStarted.emit({ conversationId: this.conversationId });\n\n try {\n // The pre-loaded artifact/agent-run maps are no longer passed: they are scoped to the\n // loaded transcript window, and the service now queries for this agent's artifacts so\n // the classifier reasons over the whole conversation. A conversation id is what it\n // needs instead, and without one there is nothing to query.\n if (!this.conversationId) {\n console.warn('⚠️ No conversation id available for intent check');\n return { decision: 'UNSURE' as const, reasoning: 'Conversation not available' };\n }\n\n const intent = await this.agentService.checkAgentContinuityIntent(\n this.conversationId,\n agentId,\n message,\n this.conversationHistory\n );\n return intent;\n } catch (error) {\n console.error('❌ Intent check failed, defaulting to UNSURE:', error);\n return { decision: 'UNSURE' as const, reasoning: 'Intent check failed with error' };\n } finally {\n // Emit event to remove temporary intent checking message\n this.intentCheckCompleted.emit({ conversationId: this.conversationId });\n }\n }\n\n /**\n * Executes a routing function, optionally with conversation naming for first message\n *\n * IMPORTANT: Conversation naming runs asynchronously in the background and does NOT\n * block the agent invocation. This prevents UI blocking if naming times out.\n */\n private async executeRouteWithNaming(\n routeFunction: () => Promise<void>,\n userMessage: string,\n isFirstMessage: boolean,\n conversationId: string\n ): Promise<void> {\n if (isFirstMessage) {\n // Fire conversation naming in background (don't await)\n // This prevents 2+ minute UI blocking if naming times out\n this.nameConversation(userMessage, conversationId);\n\n // Execute route immediately (don't wait for naming)\n await routeFunction();\n } else {\n await routeFunction();\n }\n }\n\n /**\n * Returns focus to the message textarea\n */\n private refocusTextarea(): void {\n setTimeout(() => {\n if (this.inputBox) {\n this.inputBox.focus();\n }\n }, 100);\n }\n\n /**\n * Handles message send failure\n */\n private handleSendFailure(messageDetail: MJConversationDetailEntity): void {\n console.error('Failed to send message:', messageDetail.LatestResult?.Message);\n this.toastService.error('Failed to send message. Please try again.');\n }\n\n /**\n * Handles message send error\n */\n private handleSendError(error: unknown): void {\n console.error('Error sending message:', error);\n this.toastService.error('Error sending message. Please try again.');\n }\n\n /**\n * Create a progress callback for agent execution\n * This callback updates both the active task and the ConversationDetail message\n * IMPORTANT: Filters by agentRunId to prevent cross-contamination when multiple agents run in parallel\n */\n private createProgressCallback(\n conversationDetail: MJConversationDetailEntity,\n agentName: string\n ): AgentExecutionProgressCallback {\n // Use closure to capture the agent run ID from the first progress message\n // This allows us to filter out progress messages from other concurrent agents\n let capturedAgentRunId: string | null = null;\n\n return async (progress) => {\n const metadata = progress.metadata as MessageProgressMetadata | undefined;\n const progressAgentRun = metadata?.agentRun;\n const progressAgentRunId = metadata?.agentRun?.ID || metadata?.agentRunId;\n\n // Capture the agent run ID from the first progress message\n if (!capturedAgentRunId && progressAgentRunId) {\n capturedAgentRunId = progressAgentRunId;\n }\n\n // Filter out progress messages from other concurrent agents\n // This prevents cross-contamination when multiple agents run in parallel\n if (capturedAgentRunId && progressAgentRunId && progressAgentRunId !== capturedAgentRunId) {\n return;\n }\n\n // Format progress message with visual indicator\n const progressText = progress.message;\n\n // Update the active task with progress details (if it exists)\n this.activeTasks.updateStatusByConversationDetailId(conversationDetail.ID, progressText);\n\n // Update the ConversationDetail message in real-time\n try {\n if (conversationDetail) {\n // Check 1: Skip if message is already complete or errored\n if (conversationDetail.Status === 'Complete' || conversationDetail.Status === 'Error') {\n return;\n }\n\n // Check 2: Skip if message was marked as completed (prevents race condition)\n // Once a message is marked complete, we reject ALL further progress updates\n const completionTime = this.completionTimestamps.get(conversationDetail.ID);\n if (completionTime) {\n return;\n }\n\n // CRITICAL FIX: Emit FULL agent run object for incremental updates\n // This contains live timestamps, status, and other fields that change during execution\n if (progressAgentRun || progressAgentRunId) {\n this.agentRunUpdate.emit({\n conversationId: conversationDetail.ConversationID,\n conversationDetailId: conversationDetail.ID,\n agentRun: progressAgentRun,\n agentRunId: progressAgentRunId\n });\n } else if (progressAgentRunId && !capturedAgentRunId) {\n // Fallback: If we don't have the full object but have the ID, emit agentRunDetected\n // This will trigger a database query to load the agent run\n this.agentRunDetected.emit({\n conversationId: conversationDetail.ConversationID,\n conversationDetailId: conversationDetail.ID,\n agentRunId: progressAgentRunId\n });\n }\n\n if (conversationDetail.Status === 'In-Progress') {\n conversationDetail.Message = progressText;\n // Server now saves progress - client only updates in-memory and emits for UI\n // (Prevents race condition where client's late save overwrites server's final Status)\n this.messageSent.emit(conversationDetail);\n }\n }\n } catch (error) {\n console.warn('Failed to update progress in ConversationDetail:', error);\n }\n };\n }\n\n /**\n * Process the message through agents (multi-stage: Sage -> possible sub-agent)\n * Only called when there's no @mention and no implicit agent context\n */\n private async processMessageThroughAgent(\n userMessage: MJConversationDetailEntity,\n mentionResult: MentionParseResult\n ): Promise<void> {\n let taskId: string | null = null;\n let conversationManagerMessage: MJConversationDetailEntity | null = null;\n\n // CRITICAL: Capture conversationId from user message at start\n // This prevents race condition when user switches conversations during async processing\n const conversationId = userMessage.ConversationID;\n\n try {\n // Create AI message for Sage BEFORE invoking\n conversationManagerMessage = await this.dataCache.createConversationDetail(this.currentUser);\n\n conversationManagerMessage.ConversationID = conversationId;\n conversationManagerMessage.Role = 'AI';\n conversationManagerMessage.Message = '⏳ Starting...';\n conversationManagerMessage.ParentID = userMessage.ID;\n conversationManagerMessage.Status = 'In-Progress';\n conversationManagerMessage.HiddenToUser = false;\n // Use the preloaded Sage agent instead of looking it up\n if (this.converationManagerAgent?.ID) {\n conversationManagerMessage.AgentID = this.converationManagerAgent.ID;\n }\n\n await conversationManagerMessage.Save();\n this.messageSent.emit(conversationManagerMessage);\n\n // Use Sage to evaluate and route\n // Stage 1: Sage evaluates the message\n taskId = this.activeTasks.add({\n agentName: 'Sage',\n status: 'Evaluating message...',\n relatedMessageId: userMessage.ID,\n conversationDetailId: conversationManagerMessage.ID,\n conversationId,\n conversationName: this.conversationName\n });\n\n // ── PR 2c follow-up: Before/After cancelable event wiring ──\n // Emit beforeAgentTurn so consumers can veto the turn (rate-limit, guardrail,\n // confirm-dialog, etc.). Cancel propagates synchronously through the chat-area\n // re-emit binding, so by the time .emit() returns, event.Cancel reflects every\n // subscriber's final answer.\n const beforeEvent = new BeforeAgentTurnEventArgs(\n conversationId,\n userMessage.Message ?? '',\n this.applicationId\n );\n this.beforeAgentTurn.emit(beforeEvent);\n if (beforeEvent.Cancel) {\n // Mark the conversation-manager message as canceled + clear its task so the\n // UI doesn't show a forever-pending spinner. afterAgentTurn is NOT emitted.\n await this.updateConversationDetail(\n conversationManagerMessage,\n beforeEvent.CancelReason ?? '⛔ Turn canceled before agent invocation',\n 'Error'\n );\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n this.cleanupCompletionTimestamp(conversationManagerMessage.ID);\n if (taskId) {\n this.activeTasks.remove(taskId);\n taskId = null;\n }\n return;\n }\n\n const result = await this.agentService.processMessage(\n conversationId,\n userMessage,\n this.conversationHistory,\n conversationManagerMessage.ID,\n this.createProgressCallback(conversationManagerMessage, 'Sage'),\n this.appContext,\n this.PlanModeEnabled, // per-request Plan Mode toggle\n this._pendingRequestedSkillIDs, // user-requested skills (/skill mentions)\n );\n\n // Emit afterAgentTurn on the happy path only — the error/failure branch\n // immediately below handles its own cleanup and skips this emit.\n if (result && result.success) {\n this.afterAgentTurn.emit(new AfterAgentTurnEventArgs(\n conversationId,\n (result.agentRun?.ID ?? '') as string,\n result as unknown as import('@memberjunction/ai-core-plus').ExecuteAgentResult\n ));\n }\n\n // Task will be removed automatically in markMessageComplete()\n // DO NOT remove here - agent may still be streaming/processing\n taskId = null; // Clear reference but don't remove from service\n\n if (!result || !result.success) {\n await this.applyAgentFailureToDetail(\n conversationManagerMessage,\n userMessage,\n this.converationManagerAgent?.Name || 'Sage',\n result,\n 'failed',\n );\n console.warn('⚠️ Sage failed:', agentFailureMessage(result, 'Agent evaluation failed'));\n this.cleanupCompletionTimestamp(conversationManagerMessage.ID);\n return;\n }\n\n // Stage 2: Check for task graph (multi-step orchestration)\n if (result.payload?.taskGraph) {\n await this.handleTaskGraphExecution(userMessage, result, conversationId, conversationManagerMessage);\n // Remove CM from active tasks\n if (taskId) {\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n }\n }\n // Stage 3: Check for sub-agent invocation (single-step delegation)\n else if (result.agentRun.FinalStep === 'Success' && result.payload?.invokeAgent) {\n // Reuse the existing conversationManagerMessage instead of creating new ones\n await this.handleSubAgentInvocation(userMessage, result, conversationId, conversationManagerMessage);\n // Remove CM from active tasks\n if (taskId) {\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n }\n }\n // Stage 4: Direct chat response from Agent\n else if (result.agentRun.FinalStep === 'Chat' && result.agentRun.Message) {\n // Normal chat response\n // use update helper to ensure that if there is a race condition with more streaming updates we don't allow that to override this final message\n // Note: updateConversationDetail will call markMessageComplete() for us\n await this.updateConversationDetail(conversationManagerMessage, result.agentRun.Message, 'Complete', result);\n\n // Handle artifacts if any (but NOT task graphs - those are intermediate work products)\n // Server already created artifacts - just emit event to trigger UI reload\n if (result.payload && Object.keys(result.payload).length > 0) {\n this.emitArtifactReload(conversationManagerMessage);\n this.messageSent.emit(conversationManagerMessage);\n }\n\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n\n // Remove CM from active tasks\n if (taskId) {\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n }\n\n // Clean up completion timestamp after delay\n this.cleanupCompletionTimestamp(conversationManagerMessage.ID);\n }\n // Stage 5: Silent observation - but check for message content first\n else {\n // Check if there's a message to display even without payload/taskGraph\n if (result.agentRun.Message) {\n // Mark message as completing BEFORE setting final content\n this.markMessageComplete(conversationManagerMessage);\n\n conversationManagerMessage.HiddenToUser = false;\n\n // use update helper to ensure that if there is a race condition with more streaming updates we don't allow that to override this final message\n await this.updateConversationDetail(conversationManagerMessage, result.agentRun.Message, 'Complete', result);\n\n this.messageSent.emit(conversationManagerMessage);\n\n // Clean up completion timestamp after delay\n this.cleanupCompletionTimestamp(conversationManagerMessage.ID);\n } else {\n // Mark message as completing\n this.markMessageComplete(conversationManagerMessage);\n\n // Hide the Sage message\n conversationManagerMessage.HiddenToUser = true;\n\n // use update helper to ensure that if there is a race condition with more streaming updates we don't allow that to override this final message\n await this.updateConversationDetail(conversationManagerMessage, conversationManagerMessage.Message, 'Complete', result);\n\n this.messageSent.emit(conversationManagerMessage);\n\n await this.handleSilentObservation(userMessage, conversationId);\n\n // Clean up completion timestamp after delay\n this.cleanupCompletionTimestamp(conversationManagerMessage.ID);\n }\n\n // Remove CM from active tasks\n if (taskId) {\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n }\n }\n\n } catch (error) {\n console.error('❌ Error processing message through agents:', error);\n\n // Update conversationManagerMessage status to Error\n if (conversationManagerMessage && conversationManagerMessage.ID) {\n // Use updateConversationDetail to ensure task cleanup\n conversationManagerMessage.Error = String(error);\n await this.updateConversationDetail(conversationManagerMessage, `❌ Error: ${String(error)}`, 'Error');\n\n // Clean up completion timestamp\n this.cleanupCompletionTimestamp(conversationManagerMessage.ID);\n }\n\n // Mark user message as complete\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n\n // Clean up active task\n if (taskId) {\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n }\n }\n }\n\n /** Detaches the progress callback for one message — used when submission never starts. */\n private releaseProgressCallback(messageId: string): void {\n const callback = this.registeredCallbacks.get(messageId);\n if (callback) {\n this.streamingService.unregisterMessageCallback(messageId, callback);\n this.registeredCallbacks.delete(messageId);\n }\n }\n\n /**\n * Submits a task graph to the server and returns — the client no longer drives execution.\n *\n * This used to call the `ExecuteTaskGraph` mutation and await the ENTIRE workflow inside one\n * long-lived GraphQL request. That had three unfixable problems: a page reload lost the awaited\n * promise (leaving a workflow running with nobody watching), a server restart orphaned every\n * in-flight task, and no other channel could reach the substrate at all.\n *\n * Now submission returns as soon as the graph is durable and the server-side dispatcher executes\n * it. The client is purely an observer: progress arrives over the existing PubSub frames, and\n * because the work lives in Task rows rather than in a promise, a reload can re-attach to a\n * workflow already in flight.\n *\n * Single-task graphs are no longer special-cased here. The old client-side fork ran them through\n * a different code path entirely; they now submit like any other graph, and the decision about\n * whether a one-node graph is worth durable machinery moves server-side where it can be recorded.\n */\n private async handleTaskGraphExecution(\n userMessage: MJConversationDetailEntity,\n managerResult: ExecuteAgentResult,\n conversationId: string,\n conversationManagerMessage: MJConversationDetailEntity\n ): Promise<void> {\n // `payload` is untyped by construction (an agent's payload shape is agent-specific), so pin the\n // graph to the operation's own input contract at the boundary rather than letting it stay loose.\n const taskGraph: TaskGraphSubmitInput['spec'] | undefined = managerResult.payload?.taskGraph;\n if (!taskGraph) return;\n\n const workflowName = taskGraph.workflowName || 'Workflow';\n const reasoning = taskGraph.reasoning || 'Executing multi-step workflow';\n const taskCount = Array.isArray(taskGraph.tasks) ? taskGraph.tasks.length : 0;\n\n // A message the user can watch. Progress frames from the dispatcher land against this ID.\n const taskExecutionMessage = await this.dataCache.createConversationDetail(this.currentUser);\n taskExecutionMessage.ConversationID = conversationId;\n taskExecutionMessage.Role = 'AI';\n taskExecutionMessage.Message = `⏳ **${workflowName}**\\n\\n${reasoning}\\n\\nSubmitting ${taskCount} task(s)…`;\n taskExecutionMessage.ParentID = conversationManagerMessage.ID;\n taskExecutionMessage.Status = 'In-Progress';\n taskExecutionMessage.HiddenToUser = false;\n await taskExecutionMessage.Save();\n this.messageSent.emit(taskExecutionMessage);\n\n const callback = this.createMessageProgressCallback(taskExecutionMessage.ID);\n this.registeredCallbacks.set(taskExecutionMessage.ID, callback);\n this.streamingService.registerMessageCallback(taskExecutionMessage.ID, callback);\n\n try {\n // `TaskGraph.Submit` is a Remote Operation, not a bespoke mutation: the same call site is\n // reachable from MCP, an Action wrapper, and this UI. `Execute` marshals over the generic\n // `ExecuteRemoteOperation` transport, so there is no hand-written GraphQL document here.\n const result = await new TaskGraphSubmitOperation().Execute({\n spec: taskGraph,\n environmentID: MJEnvironmentEntityExtended.DefaultEnvironmentID,\n conversationDetailID: taskExecutionMessage.ID,\n });\n\n if (result.Success && result.Output?.success) {\n // Deliberately NOT \"completed\" — submission means the work is durable and running, and\n // claiming completion here is exactly the lie the old await-everything path told when it\n // returned early. The dispatcher's progress frames update this message as tasks finish.\n await this.updateConversationDetail(\n taskExecutionMessage,\n `▶️ **${workflowName}** started — ${taskCount} task(s) running.`,\n 'In-Progress'\n );\n } else {\n const errorMsg = result.Output?.errorMessage || result.ErrorMessage || 'Unknown error';\n console.error('Task graph submission rejected:', errorMsg);\n taskExecutionMessage.Error = errorMsg;\n await this.updateConversationDetail(taskExecutionMessage, `❌ **${workflowName}** rejected: ${errorMsg}`, 'Error');\n this.releaseProgressCallback(taskExecutionMessage.ID);\n }\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n console.error('Task graph submission failed:', error);\n taskExecutionMessage.Error = msg;\n await this.updateConversationDetail(taskExecutionMessage, `❌ **${workflowName}** failed to submit: ${msg}`, 'Error');\n this.releaseProgressCallback(taskExecutionMessage.ID);\n }\n }\n\n\n\n protected async updateConversationDetail(convoDetail: MJConversationDetailEntity, message: string, status: 'In-Progress' | 'Complete' | 'Error', result?: ExecuteAgentResult): Promise<void> {\n // Mark as completing FIRST if status is Complete or Error\n // This ensures task cleanup happens even if we return early due to guard clause\n if (status === 'Complete' || status === 'Error') {\n this.markMessageComplete(convoDetail);\n }\n\n // Race condition guard: Before writing Error *or* In-Progress, reload from DB.\n // The In-Progress disconnect branch is the path that most needs this: a dropped\n // socket leaves the in-memory Status stale (still In-Progress from creation), and\n // without a reload we can overwrite a server Complete with the \"still running\"\n // placeholder. If the server already finished, emit that record and stop the timer.\n if ((status === 'Error' || status === 'In-Progress') && convoDetail.ID) {\n await convoDetail.Load(convoDetail.ID);\n if (convoDetail.Status === 'Complete' || convoDetail.Status === 'Error') {\n this.markMessageComplete(convoDetail);\n this.messageSent.emit(convoDetail);\n return;\n }\n }\n\n // Guard clause: Don't re-save if already complete/errored (prevents duplicate saves)\n // Task has already been removed by markMessageComplete() above\n if (convoDetail.Status === 'Complete' || convoDetail.Status === 'Error') {\n return; // Already complete, no need to save again\n }\n\n const maxAttempts = 2;\n let attempts = 0, done = false;\n while (attempts < maxAttempts && !done) {\n // Set response form and command fields before saving\n if (result?.responseForm) {\n convoDetail.ResponseForm = JSON.stringify(result.responseForm);\n }\n if (result?.actionableCommands) {\n convoDetail.ActionableCommands = JSON.stringify(result.actionableCommands);\n }\n if (result?.automaticCommands) {\n convoDetail.AutomaticCommands = JSON.stringify(result.automaticCommands);\n }\n\n convoDetail.Message = message;\n convoDetail.Status = status;\n\n await convoDetail.Save();\n\n if (convoDetail.Message === message && convoDetail.Status === status) {\n done = true;\n this.messageSent.emit(convoDetail);\n }\n else {\n console.warn(` ⚠️ ConversationDetail update attempt ${attempts + 1} did not persist. ${attempts + 1 < maxAttempts ? 'Retrying...' : 'Giving up.'}`);\n }\n attempts++;\n }\n\n // Clean up completion timestamp after delay\n if (status === 'Complete' || status === 'Error') {\n this.cleanupCompletionTimestamp(convoDetail.ID);\n }\n }\n\n /**\n * Load previous payload for an agent from its most recent OUTPUT artifact.\n *\n * Resolved by QUERY rather than by scanning `conversationHistory`. That array is now the\n * loaded transcript WINDOW, not the full conversation, so a scan silently misses any\n * artifact below the window's oldest row — and a null payload is a legal agent input, so\n * the miss surfaces as the agent regenerating from scratch instead of modifying. Covers\n * system-visibility artifacts (Agent Manager and friends) for free: the query filters on\n * Direction, not on Visibility.\n */\n private async loadPreviousPayloadForAgent(agentId: string): Promise<{\n payload: Record<string, unknown> | null;\n artifactInfo: {artifactId: string; versionId: string; versionNumber: number} | null;\n }> {\n if (!this.conversationId) {\n return { payload: null, artifactInfo: null };\n }\n\n const source = await this.agentService.FindLatestAgentOutputVersion(this.conversationId, agentId);\n if (!source || source.payload == null) {\n console.log(`📦 No previous payload found for agent ${agentId}`);\n return { payload: null, artifactInfo: null };\n }\n\n console.log(`📦 Loaded previous payload for agent ${agentId} from artifact version ${source.versionId}`);\n return {\n payload: source.payload,\n artifactInfo: {\n artifactId: source.artifactId,\n versionId: source.versionId,\n versionNumber: source.versionNumber\n }\n };\n }\n\n /**\n * Handle sub-agent invocation based on Sage's payload\n * Reuses the existing conversationManagerMessage to avoid creating multiple records\n */\n private async handleSubAgentInvocation(\n userMessage: MJConversationDetailEntity,\n managerResult: ExecuteAgentResult,\n conversationId: string,\n conversationManagerMessage: MJConversationDetailEntity\n ): Promise<void> {\n const payload = managerResult.payload;\n const agentName = payload.invokeAgent;\n const reasoning = payload.reasoning || 'Delegating to specialist agent';\n\n // Now create a NEW message for the sub-agent execution\n let agentResponseMessage: MJConversationDetailEntity | null = null;\n try {\n // Look up the agent to get its ID\n const agent = AIEngineBase.Instance.Agents.find(a => a.Name === agentName);\n\n // Create AI response message BEFORE invoking agent (for duration tracking)\n agentResponseMessage = await this.dataCache.createConversationDetail(this.currentUser);\n\n agentResponseMessage.ConversationID = conversationId;\n agentResponseMessage.Role = 'AI';\n agentResponseMessage.Message = '⏳ Starting...'; // Initial message\n agentResponseMessage.ParentID = conversationManagerMessage.ID; // Thread under delegation message\n agentResponseMessage.Status = 'In-Progress';\n agentResponseMessage.HiddenToUser = false;\n // Set AgentID immediately for proper attribution\n if (agent?.ID) {\n agentResponseMessage.AgentID = agent.ID;\n }\n\n // Save the record to establish __mj_CreatedAt timestamp\n await agentResponseMessage.Save();\n this.messageSent.emit(agentResponseMessage);\n\n // Add sub-agent to active tasks\n const newTaskId = this.activeTasks.add({\n agentName: agentName,\n status: 'Starting...',\n relatedMessageId: userMessage.ID,\n conversationDetailId: agentResponseMessage.ID,\n conversationId,\n conversationName: this.conversationName\n });\n\n // Load previous payload if agent has been invoked before\n const { payload: previousPayload, artifactInfo } = agent?.ID\n ? await this.loadPreviousPayloadForAgent(agent.ID)\n : { payload: null, artifactInfo: null };\n\n // Find configuration preset from previous @mention in conversation history\n const configurationPresetId = agent?.ID\n ? await this.agentService.FindConfigurationPresetForAgent(conversationId, agent.ID)\n : undefined;\n\n // Invoke the sub-agent with progress callback\n const subResult = await this.agentService.invokeSubAgent(\n agentName,\n conversationId,\n userMessage,\n this.conversationHistory,\n reasoning,\n agentResponseMessage.ID,\n previousPayload, // Pass previous payload for continuity\n this.createProgressCallback(agentResponseMessage, agentName),\n artifactInfo?.artifactId,\n artifactInfo?.versionId,\n configurationPresetId, // Pass configuration from previous @mention for continuity\n this.appContext, // Embedder-supplied app/form context\n this.PlanModeEnabled, // per-request Plan Mode toggle\n this._pendingRequestedSkillIDs, // user-requested skills (/skill mentions)\n );\n\n // Task will be removed automatically in markMessageComplete() when status changes to Complete/Error\n // DO NOT remove here - allows UI to show task during entire execution\n\n if (subResult && subResult.success) {\n // Update the response message with agent result\n // Store the agent ID for display\n if (subResult.agentRun.AgentID) {\n agentResponseMessage.AgentID = subResult.agentRun.AgentID;\n }\n\n await this.updateConversationDetail(agentResponseMessage, subResult.agentRun?.Message || `✅ **${agentName}** completed`, 'Complete', subResult);\n\n // Always emit artifactCreated to trigger UI reload — the server may have created\n // artifacts even when the result payload is empty (e.g., remote stage server).\n // onArtifactCreated will reload from DB and discover any artifacts that exist.\n this.emitArtifactReload(agentResponseMessage);\n this.messageSent.emit(agentResponseMessage);\n\n // Mark user message as complete\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n } else {\n // A post-ACK disconnect means the first run may still be executing on this\n // detail — do not start a second run on the same conversationDetailId.\n if (agentFailureDisposition(subResult).status === 'In-Progress') {\n await this.applyAgentFailureToDetail(agentResponseMessage, userMessage, agentName, subResult);\n return;\n }\n\n // Sub-agent failed - attempt auto-retry once\n console.log(`⚠️ ${agentName} failed, attempting auto-retry...`);\n\n await this.updateConversationDetail(conversationManagerMessage, `👉 **${agentName}** will handle this request...\\n\\n⚠️ First attempt failed, retrying...`, conversationManagerMessage.Status);\n\n // Update the existing agentResponseMessage to show retry status\n await this.updateConversationDetail(agentResponseMessage, \"Retrying...\", agentResponseMessage.Status);\n\n // Retry the sub-agent (reuse previously loaded payload and config from first attempt)\n const retryResult = await this.agentService.invokeSubAgent(\n agentName,\n conversationId,\n userMessage,\n this.conversationHistory,\n reasoning,\n agentResponseMessage.ID,\n previousPayload, // Pass same payload as first attempt\n this.createProgressCallback(agentResponseMessage, `${agentName} (retry)`),\n artifactInfo?.artifactId,\n artifactInfo?.versionId,\n configurationPresetId, // Pass same config as first attempt\n this.appContext, // Embedder-supplied app/form context\n this.PlanModeEnabled, // per-request Plan Mode toggle\n this._pendingRequestedSkillIDs, // user-requested skills (/skill mentions)\n );\n\n if (retryResult && retryResult.success) {\n // Retry succeeded - update the same message\n if (retryResult.agentRun.AgentID) {\n agentResponseMessage.AgentID = retryResult.agentRun.AgentID;\n }\n\n await this.updateConversationDetail(agentResponseMessage, retryResult.agentRun?.Message || `✅ **${agentName}** completed`, 'Complete', retryResult);\n\n // Always emit artifactCreated to trigger UI reload (same as initial attempt)\n this.emitArtifactReload(agentResponseMessage);\n this.messageSent.emit(agentResponseMessage);\n\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n } else {\n // Retry also failed — terminate the agent bubble (the red-pill timer lives here),\n // not only the Sage delegation message.\n await this.applyAgentFailureToDetail(\n agentResponseMessage,\n userMessage,\n agentName,\n retryResult,\n 'failed after retry',\n );\n const retryDisposition = agentFailureDisposition(retryResult);\n if (retryDisposition.status === 'Error') {\n conversationManagerMessage.Error = retryDisposition.message;\n await this.updateConversationDetail(\n conversationManagerMessage,\n `❌ **${agentName}** failed after retry\\n\\n${retryDisposition.message}`,\n 'Error',\n );\n }\n }\n }\n } catch (error) {\n console.error(`❌ Error invoking sub-agent ${agentName}:`, error);\n\n const catchResult = {\n success: false,\n errorMessage: error instanceof Error ? error.message : String(error),\n } as ExecuteAgentResult;\n if (agentResponseMessage) {\n await this.applyAgentFailureToDetail(agentResponseMessage, userMessage, agentName, catchResult);\n } else {\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n }\n const catchDisposition = agentFailureDisposition(catchResult);\n if (catchDisposition.status === 'Error') {\n conversationManagerMessage.Error = catchDisposition.message;\n await this.updateConversationDetail(\n conversationManagerMessage,\n `❌ **${agentName}** encountered an error\\n\\n${catchDisposition.message}`,\n 'Error',\n );\n }\n }\n }\n\n /**\n * Handle silent observation - when Sage stays silent,\n * check if we should continue with the last agent for iterative refinement\n */\n private async handleSilentObservation(\n userMessage: MJConversationDetailEntity,\n conversationId: string\n ): Promise<void> {\n // Find the last AI message (excluding Sage) in the conversation history\n const lastAIMessage = this.conversationHistory\n .slice()\n .reverse()\n .find(msg =>\n msg.Role === 'AI' &&\n msg.AgentID &&\n !UUIDsEqual(msg.AgentID, this.converationManagerAgent?.ID)\n );\n\n if (!lastAIMessage || !lastAIMessage.AgentID) {\n // No previous specialist agent - just mark user message as complete\n console.log('🔇 No previous specialist agent found - marking complete');\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n return;\n }\n\n // Load the agent entity to get its name\n const previousAgent = AIEngineBase.Instance.Agents.find(a => UUIDsEqual(a.ID, lastAIMessage.AgentID));\n if (!previousAgent) {\n console.warn('⚠️ Could not load previous agent - marking complete');\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n return;\n }\n\n const agentName = previousAgent.Name || 'Agent';\n\n let previousPayload: Record<string, unknown> | null = null;\n let previousArtifactInfo: {artifactId: string; versionId: string; versionNumber: number} | null = null;\n\n // Resolved by QUERY, not from the window's artifact maps: `lastAIMessage` can sit inside\n // the loaded window while its artifact does not, and this path silently degrades to a\n // null payload when the lookup misses.\n const source = await this.agentService.FindLatestAgentOutputVersion(\n conversationId, lastAIMessage.AgentID\n );\n if (source && source.payload != null) {\n previousPayload = source.payload;\n previousArtifactInfo = {\n artifactId: source.artifactId,\n versionId: source.versionId,\n versionNumber: source.versionNumber\n };\n console.log('📦 Loaded previous OUTPUT artifact as payload for continuity', previousArtifactInfo);\n }\n\n // Create status message showing agent continuity\n const statusMessage = await this.dataCache.createConversationDetail(this.currentUser);\n\n statusMessage.ConversationID = conversationId;\n statusMessage.Role = 'AI';\n statusMessage.Message = `Continuing with **${agentName}** for refinement...`;\n statusMessage.ParentID = userMessage.ID;\n statusMessage.Status = 'Complete';\n statusMessage.HiddenToUser = false;\n statusMessage.AgentID = this.converationManagerAgent?.ID || null;\n\n await statusMessage.Save();\n this.messageSent.emit(statusMessage);\n\n // Add agent to active tasks\n const taskId = this.activeTasks.add({\n agentName: agentName,\n status: 'Processing refinement...',\n relatedMessageId: userMessage.ID,\n conversationDetailId: statusMessage.ID,\n conversationId,\n conversationName: this.conversationName\n });\n\n try {\n // Invoke the agent with the previous payload\n const continuityResult = await this.agentService.invokeSubAgent(\n agentName,\n conversationId,\n userMessage,\n this.conversationHistory,\n 'Continuing previous work based on user feedback',\n statusMessage.ID,\n previousPayload,\n this.createProgressCallback(statusMessage, agentName),\n previousArtifactInfo?.artifactId,\n previousArtifactInfo?.versionId,\n undefined, // configurationPresetId not used in this path\n this.appContext, // Embedder-supplied app/form context\n this.PlanModeEnabled, // per-request Plan Mode toggle\n this._pendingRequestedSkillIDs, // user-requested skills (/skill mentions)\n );\n\n // Remove from active tasks\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n\n if (continuityResult && continuityResult.success) {\n // Create response message\n const agentResponseMessage = await this.dataCache.createConversationDetail(this.currentUser);\n\n agentResponseMessage.ConversationID = conversationId;\n agentResponseMessage.Role = 'AI';\n agentResponseMessage.Message = continuityResult.agentRun?.Message || `✅ **${agentName}** completed refinement`;\n agentResponseMessage.ParentID = statusMessage.ID;\n agentResponseMessage.Status = 'Complete';\n agentResponseMessage.HiddenToUser = false;\n agentResponseMessage.AgentID = lastAIMessage.AgentID;\n\n await agentResponseMessage.Save();\n this.messageSent.emit(agentResponseMessage);\n\n // Server created artifacts (handles versioning automatically) - emit event to trigger UI reload\n if (continuityResult.payload && Object.keys(continuityResult.payload).length > 0) {\n this.emitArtifactReload(agentResponseMessage);\n console.log('🎨 Server created artifact (versioned) from agent continuity');\n this.messageSent.emit(agentResponseMessage);\n }\n\n // Mark user message as complete\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n } else {\n await this.applyAgentFailureToDetail(statusMessage, userMessage, agentName, continuityResult, 'failed during refinement');\n }\n } catch (error) {\n console.error(`❌ Error in agent continuity with ${agentName}:`, error);\n\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n\n await this.applyAgentFailureToDetail(\n statusMessage,\n userMessage,\n agentName,\n { success: false, errorMessage: error instanceof Error ? error.message : String(error) } as ExecuteAgentResult,\n 'encountered an error',\n );\n }\n }\n \n\n /**\n * Invoke an agent directly when mentioned with @ symbol\n * Bypasses Sage completely - no status messages\n */\n private async invokeAgentDirectly(\n userMessage: MJConversationDetailEntity,\n agentMention: Mention,\n conversationId: string\n ): Promise<void> {\n const agentName = agentMention.name;\n\n // Add agent to active tasks\n const taskId = this.activeTasks.add({\n agentName: agentName,\n status: 'Processing...',\n relatedMessageId: userMessage.ID,\n conversationDetailId: userMessage.ID,\n conversationId,\n conversationName: this.conversationName\n });\n\n // Declare agentResponseMessage outside try block so it's accessible in catch\n let agentResponseMessage: MJConversationDetailEntity | undefined = undefined;\n\n try {\n // User message is sent successfully - mark complete immediately\n // (No UI uses User message 'In-Progress' - only AI messages need that status)\n userMessage.Status = 'Complete';\n await userMessage.Save();\n this.messageSent.emit(userMessage);\n\n // Look up the agent to get its ID\n const agent = AIEngineBase.Instance.Agents.find(a => a.Name === agentName);\n\n // Create AI response message BEFORE invoking agent (for duration tracking)\n agentResponseMessage = await this.dataCache.createConversationDetail(this.currentUser);\n\n agentResponseMessage.ConversationID = conversationId;\n agentResponseMessage.Role = 'AI';\n agentResponseMessage.Message = '⏳ Starting...'; // Initial message\n agentResponseMessage.ParentID = userMessage.ID;\n agentResponseMessage.Status = 'In-Progress';\n agentResponseMessage.HiddenToUser = false;\n // Set AgentID immediately for proper attribution\n if (agent?.ID) {\n agentResponseMessage.AgentID = agent.ID;\n }\n\n // Save the record to establish __mj_CreatedAt timestamp\n await agentResponseMessage.Save();\n this.messageSent.emit(agentResponseMessage);\n\n // Load previous payload if agent has been invoked before\n const { payload: previousPayload, artifactInfo } = agent?.ID\n ? await this.loadPreviousPayloadForAgent(agent.ID)\n : { payload: null, artifactInfo: null };\n\n // Invoke the agent directly\n const result = await this.agentService.invokeSubAgent(\n agentName,\n conversationId,\n userMessage,\n this.conversationHistory,\n `User mentioned agent directly with @${agentName}`,\n agentResponseMessage.ID,\n previousPayload, // Pass previous payload for continuity\n this.createProgressCallback(agentResponseMessage, agentName),\n artifactInfo?.artifactId,\n artifactInfo?.versionId,\n agentMention.configurationId, // Pass configuration preset ID\n this.appContext, // Embedder-supplied app/form context\n this.PlanModeEnabled, // per-request Plan Mode toggle\n this._pendingRequestedSkillIDs, // user-requested skills (/skill mentions)\n );\n\n // Remove from active tasks\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n\n if (result && result.success) {\n if (result.agentRun.AgentID) {\n agentResponseMessage.AgentID = result.agentRun.AgentID;\n }\n\n // Multi-stage response handling (same logic as ambient Sage)\n // Stage 1: Check for task graph (multi-step orchestration)\n if (result.payload?.taskGraph) {\n console.log('📋 Task graph detected from @mention, starting task orchestration');\n await this.handleTaskGraphExecution(userMessage, result, conversationId, agentResponseMessage);\n }\n // Stage 2: Check for sub-agent invocation (single-step delegation)\n else if (result.agentRun.FinalStep === 'Success' && result.payload?.invokeAgent) {\n console.log('🎯 Sub-agent invocation detected from @mention');\n await this.handleSubAgentInvocation(userMessage, result, conversationId, agentResponseMessage);\n }\n // Stage 3: Normal chat response\n else {\n await this.updateConversationDetail(agentResponseMessage, result.agentRun?.Message || `✅ **${agentName}** completed`, 'Complete', result)\n\n // Server created artifacts - emit event to trigger UI reload\n if (result.payload && Object.keys(result.payload).length > 0) {\n this.emitArtifactReload(agentResponseMessage);\n this.messageSent.emit(agentResponseMessage);\n }\n\n // Mark user message as complete\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n }\n } else {\n await this.applyAgentFailureToDetail(agentResponseMessage, userMessage, agentName, result);\n }\n } catch (error) {\n console.error(`❌ Error invoking mentioned agent ${agentName}:`, error);\n\n if (agentResponseMessage) {\n await this.applyAgentFailureToDetail(\n agentResponseMessage,\n userMessage,\n agentName,\n { success: false, errorMessage: error instanceof Error ? error.message : String(error) } as ExecuteAgentResult,\n );\n } else {\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n }\n }\n }\n\n /**\n * Continue with the same agent from previous message (implicit continuation)\n * Bypasses Sage - no status messages\n *\n * @param targetArtifactVersionId Optional specific artifact version to use as payload (from intent check)\n */\n private async continueWithAgent(\n userMessage: MJConversationDetailEntity,\n agentId: string,\n conversationId: string,\n targetArtifactVersionId?: string\n ): Promise<void> {\n // Load the agent entity to get its name\n const agent = AIEngineBase.Instance.Agents.find(a => UUIDsEqual(a.ID, agentId));\n if (!agent) {\n console.warn('⚠️ Could not load agent for continuation - falling back to Sage');\n await this.processMessageThroughAgent(userMessage, { mentions: [], agentMention: null, userMentions: [], entityMentions: [], skillMentions: [] });\n return;\n }\n\n const agentName = agent.Name || 'Agent';\n\n let previousPayload: Record<string, unknown> | null = null;\n let previousArtifactInfo: {artifactId: string; versionId: string; versionNumber: number} | null = null;\n let previousConfigurationId: string | undefined = undefined;\n\n // Use targetArtifactVersionId if specified (from intent check).\n // Resolved by ID against the database, not against artifactsByDetailId: the intent check\n // may well have named a version attached to a message BELOW the loaded window, which is\n // precisely when continuity matters and precisely what the window's maps cannot see.\n if (targetArtifactVersionId) {\n const target = await this.agentService.FindArtifactVersionById(targetArtifactVersionId);\n if (target && target.payload != null) {\n previousPayload = target.payload;\n previousArtifactInfo = {\n artifactId: target.artifactId,\n versionId: target.versionId,\n versionNumber: target.versionNumber\n };\n console.log('📦 Loaded target artifact version as payload', previousArtifactInfo);\n } else {\n console.warn('⚠️ Could not load target artifact version:', targetArtifactVersionId);\n }\n }\n\n // Extract configuration preset from the User message that @mentioned this agent\n // Uses the shared helper method in the agent service\n previousConfigurationId = await this.agentService.FindConfigurationPresetForAgent(conversationId, agentId);\n\n // Fall back to the chat header's mode-picker selection when nothing\n // in the message history pinned a preset. The picker reflects the\n // user's persistent per-agent mode preference (Draft / Standard /\n // High) and applies to all subsequent non-mention routes. A\n // history-derived preset still wins because it represents an\n // explicit per-message intent the user expressed earlier.\n if (!previousConfigurationId && this.agentConfigurationPresetId) {\n previousConfigurationId = this.agentConfigurationPresetId;\n }\n\n // Fall back to searching through all agent messages for an artifact\n // This ensures payload continuity even after clarifying exchanges without artifacts\n // Fall back to this agent's newest OUTPUT artifact when the intent check named no\n // version (or named one that no longer resolves). Queried, not scanned: the array this\n // used to walk is the loaded window, so the artifact it is looking for is exactly the\n // one most likely to be missing from it.\n if (!previousPayload) {\n const source = await this.agentService.FindLatestAgentOutputVersion(conversationId, agentId);\n if (source && source.payload != null) {\n previousPayload = source.payload;\n previousArtifactInfo = {\n artifactId: source.artifactId,\n versionId: source.versionId,\n versionNumber: source.versionNumber\n };\n console.log('📦 Loaded artifact as payload for continuation', previousArtifactInfo);\n } else {\n console.log(`📦 No artifact found for agent ${agentId} in this conversation`);\n }\n }\n\n // Execute the agent with the gathered context\n await this.executeAgentContinuation(\n userMessage,\n agentId,\n agentName,\n conversationId,\n previousPayload,\n previousArtifactInfo,\n previousConfigurationId\n );\n }\n\n /**\n * Executes agent continuation with all context already gathered.\n * This is the shared execution logic used by both continueWithAgent and direct Sage config path.\n *\n * @param userMessage The user's message entity\n * @param agentId The agent ID to invoke\n * @param agentName The agent's display name\n * @param conversationId The conversation ID\n * @param previousPayload Optional payload from previous artifact\n * @param previousArtifactInfo Optional artifact info (id, versionId, versionNumber)\n * @param configurationId Optional configuration preset ID to use\n */\n private async executeAgentContinuation(\n userMessage: MJConversationDetailEntity,\n agentId: string,\n agentName: string,\n conversationId: string,\n previousPayload: Record<string, unknown> | null,\n previousArtifactInfo: {artifactId: string; versionId: string; versionNumber: number} | null,\n configurationId?: string\n ): Promise<void> {\n // Add agent to active tasks\n const taskId = this.activeTasks.add({\n agentName: agentName,\n status: 'Processing...',\n relatedMessageId: userMessage.ID,\n conversationDetailId: userMessage.ID,\n conversationId,\n conversationName: this.conversationName\n });\n\n // Declare agentResponseMessage outside try block so it's accessible in catch\n let agentResponseMessage: MJConversationDetailEntity | undefined = undefined;\n\n try {\n // User message is sent successfully - mark complete immediately\n // (No UI uses User message 'In-Progress' - only AI messages need that status)\n userMessage.Status = 'Complete';\n await userMessage.Save();\n this.messageSent.emit(userMessage);\n\n // Create AI response message BEFORE invoking agent (for duration tracking)\n agentResponseMessage = await this.dataCache.createConversationDetail(this.currentUser);\n\n agentResponseMessage.ConversationID = conversationId;\n agentResponseMessage.Role = 'AI';\n agentResponseMessage.Message = '⏳ Starting...'; // Initial message\n agentResponseMessage.ParentID = userMessage.ID;\n agentResponseMessage.Status = 'In-Progress';\n agentResponseMessage.HiddenToUser = false;\n agentResponseMessage.AgentID = agentId;\n\n // Save the record to establish __mj_CreatedAt timestamp\n await agentResponseMessage.Save();\n this.messageSent.emit(agentResponseMessage);\n\n // Invoke the agent directly (continuation) with previous payload if available.\n // `this.appContext` is forwarded so direct-routed sub-agents (e.g. Form\n // Builder via [defaultAgentId]) see the embedder's ActiveForm/Schema/\n // OverrideID block in their prompt — same flow Sage gets via\n // `processMessage`.\n const result = await this.agentService.invokeSubAgent(\n agentName,\n conversationId,\n userMessage,\n this.conversationHistory,\n 'Continuing previous conversation with user',\n agentResponseMessage.ID,\n previousPayload, // Pass previous OUTPUT artifact payload for continuity\n this.createProgressCallback(agentResponseMessage, agentName),\n previousArtifactInfo?.artifactId,\n previousArtifactInfo?.versionId,\n configurationId, // Pass configuration for continuity\n this.appContext, // Embedder-supplied app/form context\n this.PlanModeEnabled, // per-request Plan Mode toggle\n this._pendingRequestedSkillIDs, // user-requested skills (/skill mentions)\n );\n\n // Remove from active tasks\n // Task removed in markMessageComplete() - this.activeTasks.remove(taskId);\n\n if (result && result.success) {\n // Update the response message with agent result\n await this.updateConversationDetail(agentResponseMessage,result.agentRun?.Message || `✅ **${agentName}** completed`, 'Complete', result);\n\n // Server created artifacts (handles versioning) - emit event to trigger UI reload\n if (result.payload && Object.keys(result.payload).length > 0) {\n this.emitArtifactReload(agentResponseMessage);\n this.messageSent.emit(agentResponseMessage);\n }\n\n // Mark user message as complete\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n } else {\n await this.applyAgentFailureToDetail(agentResponseMessage, userMessage, agentName, result);\n }\n } catch (error) {\n console.error(`❌ Error continuing with agent ${agentName}:`, error);\n\n if (agentResponseMessage) {\n await this.applyAgentFailureToDetail(\n agentResponseMessage,\n userMessage,\n agentName,\n { success: false, errorMessage: error instanceof Error ? error.message : String(error) } as ExecuteAgentResult,\n );\n } else {\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n }\n }\n }\n\n /**\n * Names the conversation from its first message via the SHARED naming helper\n * ({@link GenerateAndApplyConversationName}) — the same implementation the realtime\n * session path uses. This wrapper keeps the composer-specific concerns local:\n * mention stripping and the sidebar rename animation event.\n */\n private async nameConversation(message: string, conversationId: string): Promise<void> {\n // Convert message to plain text (strips JSON-encoded mentions like @{\"id\":\"...\",\"name\":\"Sage\"} to @Sage)\n const plainTextMessage = this.mentionParser.toPlainText(\n message,\n this.mentionAutocomplete.getAvailableAgents(),\n this.mentionAutocomplete.getAvailableUsers()\n );\n\n // Use the captured conversationId (not this.conversationId): naming runs fire-and-forget\n // in the background, so the user may have swapped conversations before it resolves.\n const result = await GenerateAndApplyConversationName({\n ConversationId: conversationId,\n MessageText: plainTextMessage,\n Provider: this.ProviderToUse as GraphQLDataProvider,\n CurrentUser: this.currentUser\n });\n\n if (result) {\n // Emit event for animation in conversation list\n this.conversationRenamed.emit({\n conversationId,\n name: result.Name,\n description: result.Description\n });\n console.log(`✅ Conversation renamed to: \"${result.Name}\"`);\n }\n }\n\n /**\n * Persist an agent failure onto the response bubble.\n *\n * A dropped HTTP/WebSocket path used to return `null` from invokeSubAgent, so\n * the bubble said \"Unknown error\" while the AIAgentRun stayed Running and the\n * timer kept ticking. If the transport ACKed the mutation and then died, keep\n * In-Progress so a later completion event (or {@link startInFlightDetailWatch})\n * can land. ConversationDetail.Status is the server's claim; the client only\n * renders it. The GraphQLAIClient stall reconciler covers the wait inside\n * invokeSubAgent; once that returns, the watch observes the detail until the\n * server writes a terminal status (MaxTimePerRun).\n *\n * Always completes the user message — the user turn finished regardless of\n * what the agent is doing.\n */\n private async applyAgentFailureToDetail(\n agentResponseMessage: MJConversationDetailEntity,\n userMessage: MJConversationDetailEntity,\n agentName: string,\n result: ExecuteAgentResult | null | undefined,\n failedVerb = 'failed',\n ): Promise<void> {\n const disposition = agentFailureDisposition(result);\n if (disposition.status === 'In-Progress') {\n await this.updateConversationDetail(\n agentResponseMessage,\n `⏳ **${agentName}** is still running on the server.\\n\\n${disposition.message}`,\n 'In-Progress',\n );\n // Skip the watch if the reload-before-write guard already found a\n // terminal server status (Complete/Error) — starting it would race the\n // just-completed bubble.\n if (agentResponseMessage.Status === 'In-Progress') {\n this.startInFlightDetailWatch(agentResponseMessage);\n }\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n return;\n }\n agentResponseMessage.Error = disposition.message;\n await this.updateConversationDetail(\n agentResponseMessage,\n `❌ **${agentName}** ${failedVerb}\\n\\n${disposition.message}`,\n 'Error',\n );\n await this.updateConversationDetail(userMessage, userMessage.Message, 'Complete');\n }\n\n private startInFlightDetailWatch(detail: MJConversationDetailEntity): void {\n if (!detail.ID) {\n return;\n }\n this.stopInFlightDetailWatch(detail.ID);\n this.scheduleInFlightDetailPoll(detail, 0);\n }\n\n private scheduleInFlightDetailPoll(detail: MJConversationDetailEntity, step: number): void {\n const delays = MessageInputComponent.IN_FLIGHT_WATCH_BACKOFF_MS;\n const delay = delays[Math.min(step, delays.length - 1)];\n const handle = setTimeout(() => {\n void this.pollInFlightDetail(detail, step);\n }, delay);\n this.inFlightWatches.set(detail.ID, handle);\n }\n\n private async pollInFlightDetail(detail: MJConversationDetailEntity, step: number): Promise<void> {\n if (!this.inFlightWatches.has(detail.ID)) {\n return;\n }\n try {\n await detail.Load(detail.ID);\n if (detail.Status === 'Complete' || detail.Status === 'Error') {\n this.stopInFlightDetailWatch(detail.ID);\n this.markMessageComplete(detail);\n this.messageSent.emit(detail);\n return;\n }\n } catch (e) {\n console.warn(`[InFlightWatch] Failed to reload conversation detail ${detail.ID}:`, e);\n }\n if (!this.inFlightWatches.has(detail.ID)) {\n return;\n }\n this.scheduleInFlightDetailPoll(detail, step + 1);\n }\n\n private stopInFlightDetailWatch(detailId: string): void {\n const handle = this.inFlightWatches.get(detailId);\n if (handle) {\n clearTimeout(handle);\n this.inFlightWatches.delete(detailId);\n }\n }\n\n private clearInFlightWatches(): void {\n for (const handle of this.inFlightWatches.values()) {\n clearTimeout(handle);\n }\n this.inFlightWatches.clear();\n }\n\n /**\n * Marks a conversation detail as complete and records timestamp to prevent race conditions\n * Emits event to parent to refresh agent run data from database\n */\n private markMessageComplete(conversationDetail: MJConversationDetailEntity): void {\n const now = Date.now();\n this.completionTimestamps.set(conversationDetail.ID, now);\n this.stopInFlightDetailWatch(conversationDetail.ID);\n\n // Unregister streaming callback for this message (no more updates needed)\n const callback = this.registeredCallbacks.get(conversationDetail.ID);\n if (callback) {\n this.streamingService.unregisterMessageCallback(conversationDetail.ID, callback);\n this.registeredCallbacks.delete(conversationDetail.ID);\n LogStatusEx({ message: `[MarkComplete] Unregistered streaming callback for completed message ${conversationDetail.ID}`, verboseOnly: true });\n }\n\n // Remove task from active tasks if it exists\n const task = this.activeTasks.getByConversationDetailId(conversationDetail.ID);\n if (task) {\n LogStatusEx({\n message: `✅ Task found for message ${conversationDetail.ID} - removing from active tasks:`,\n additionalArgs: [{\n taskId: task.id,\n agentName: task.agentName,\n conversationId: task.conversationId,\n conversationName: task.conversationName\n }],\n verboseOnly: true,\n });\n\n this.activeTasks.remove(task.id);\n\n // Show toast only if the user isn't currently viewing this conversation.\n // If they're watching, the inline completion is sufficient.\n const isConvoVisible = UUIDsEqual(this.bridge.ActiveConversationID$.value, task.conversationId)\n && (this.bridge.OverlayActive$.value || this.bridge.WorkspaceActive$.value);\n if (!isConvoVisible) {\n // The server announces the same completion through its Agent Completion notification\n // (when the run produced an artifact); the shared dedupe key folds the two into one\n // toast, and this wording — the later of the two — is what stays on screen.\n const agent = task.agentId\n ? AIEngineBase.Instance.Agents.find(a => UUIDsEqual(a.ID, task.agentId))\n : undefined;\n // The task carries the name from send time; the engine has the current one (the\n // first exchange auto-names the conversation). The placeholder a brand-new\n // conversation starts with is not a name worth announcing.\n const currentName = this.engine.Conversations.find(c => UUIDsEqual(c.ID, task.conversationId))?.Name\n ?? task.conversationName;\n const conversationName = currentName && currentName !== 'New Conversation' ? currentName : null;\n MJNotificationService.Instance?.CreateRichNotification({\n title: `${task.agentName} finished`,\n message: conversationName ? `in ${conversationName}` : null,\n imageUrl: agent?.LogoURL ?? null,\n iconClass: agent?.IconClass ?? 'fa-solid fa-robot',\n hideAfter: 5000,\n dedupeKey: `agent-completion:${task.conversationId ?? task.id}`,\n context: { conversationId: task.conversationId, agentId: task.agentId, agentName: task.agentName }\n });\n }\n } else {\n // verboseOnly, and no longer a warning. A turn registers ONE task, against whichever message\n // its flow chose — activeTasks.add() is called with the user message, a Sage delegation\n // message, a status message or the agent response depending on the path — while this method\n // runs for EVERY message in the turn reaching Complete or Error. Most calls therefore land\n // here, so it is the normal case rather than the lifecycle race the old text described\n // (\"task may have been removed prematurely or not added\"). Kept for tracing, off by default.\n LogStatusEx({ message: `[MarkComplete] No task registered against completed message ${conversationDetail.ID} — expected for any message that did not start the turn`, verboseOnly: true });\n }\n\n // Emit completion event to parent so it can refresh agent run data\n this.messageComplete.emit({\n conversationId: conversationDetail.ConversationID,\n conversationDetailId: conversationDetail.ID,\n agentId: conversationDetail.AgentID || undefined\n });\n }\n\n /**\n * Emit an artifact-reload signal for {@link detail}. The artifact metadata fields are\n * placeholders — the parent reloads the real artifacts from the DB; the only fields it\n * consumes are conversationDetailId and conversationId (the latter lets it drop events from\n * a background conversation after a conversation swap). conversationId is taken from the\n * detail entity's immutable ConversationID, never this.conversationId.\n */\n private emitArtifactReload(detail: MJConversationDetailEntity): void {\n this.artifactCreated.emit({\n conversationId: detail.ConversationID,\n artifactId: '',\n versionId: '',\n versionNumber: 0,\n conversationDetailId: detail.ID,\n name: ''\n });\n }\n\n /**\n * Cleans up completion timestamps for completed messages (prevents memory leak)\n */\n private cleanupCompletionTimestamp(conversationDetailId: string): void {\n // Keep timestamp for a short period to catch any late progress updates\n setTimeout(() => {\n this.completionTimestamps.delete(conversationDetailId);\n }, 5000); // 5 seconds should be more than enough\n }\n}\n","<div class=\"message-input-wrapper\" cdkOverlayOrigin #pickerOrigin=\"cdkOverlayOrigin\">\n <!-- Processing Indicator Overlay -->\n @if (isProcessing) {\n <div class=\"processing-indicator\">\n <i class=\"fas fa-circle-notch fa-spin\"></i>\n <span>{{ processingMessage }}</span>\n </div>\n }\n\n <!-- AI composer (mic + Plan Mode buttons live in its in-composer toolbar): wraps the\n generic mj-message-input-box with the '@' agent / '#' record / '/' skill trigger\n plugins built in — all three on by default, preserving the standard chat behavior. -->\n <mj-ai-composer\n #inputBox\n [placeholder]=\"placeholder\"\n [disabled]=\"disabled || isProcessing\"\n [showCharacterCount]=\"false\"\n [enableMentions]=\"enableMentions\"\n [EnableAgentMentions]=\"enableAgentMentions\"\n [EnableEntityMentions]=\"enableEntityMentions\"\n [EnableSkillCommands]=\"enableSkillCommands\"\n [TargetAgentId]=\"pickerTargetAgentId\"\n [enableAttachments]=\"enableAttachments\"\n [maxAttachments]=\"maxAttachments\"\n [maxAttachmentSizeBytes]=\"maxAttachmentSizeBytes\"\n [acceptedFileTypes]=\"acceptedFileTypes\"\n [currentUser]=\"currentUser\"\n [Provider]=\"Provider\"\n [rows]=\"3\"\n [enableRealtime]=\"enableRealtime\"\n [voiceActive]=\"voiceActive\"\n [canStartRealtime]=\"canStartRealtime\"\n [enablePlanMode]=\"enablePlanMode\"\n [planModeActive]=\"PlanModeEnabled\"\n [value]=\"messageText\"\n (valueChange)=\"OnComposerValueChanged($event)\"\n (blurred)=\"ComposerBlurred.emit()\"\n (textSubmitted)=\"onTextSubmitted($event)\"\n (attachmentsChanged)=\"onAttachmentsChanged($event)\"\n (attachmentError)=\"onAttachmentError($event)\"\n (voiceRequested)=\"onStartRealtime()\"\n (voiceOptionsRequested)=\"onRealtimeOptions()\"\n (planModeToggle)=\"TogglePlanMode()\">\n </mj-ai-composer>\n\n <!-- Voice agent/co-agent/model picker — shown when starting a call on a conversation\n with NO prior agent participation, or on demand via the caret next to the phone\n button (any conversation). Rendered in a body-level CDK overlay anchored above the\n composer so it POPS OUT of the chat overlay's clipping border instead of being cut\n off at the top of a narrow (~390px) overlay. -->\n <ng-template\n cdkConnectedOverlay\n [cdkConnectedOverlayOrigin]=\"pickerOrigin\"\n [cdkConnectedOverlayOpen]=\"showRealtimeAgentPicker\"\n [cdkConnectedOverlayPositions]=\"pickerOverlayPositions\"\n [cdkConnectedOverlayPush]=\"true\"\n [cdkConnectedOverlayHasBackdrop]=\"true\"\n cdkConnectedOverlayBackdropClass=\"cdk-overlay-transparent-backdrop\"\n (backdropClick)=\"onRealtimeAgentPickerCancelled()\"\n (detach)=\"onRealtimeAgentPickerCancelled()\">\n <mj-realtime-agent-picker\n [Provider]=\"ProviderToUse\"\n [CurrentUser]=\"currentUser\"\n [Agents]=\"voicePickerAgents\"\n [DefaultAgentId]=\"voicePickerDefaultAgentId\"\n [CoAgents]=\"voicePickerCoAgents\"\n [DefaultCoAgentId]=\"voicePickerDefaultCoAgentId\"\n (AgentPicked)=\"onRealtimeAgentPicked($event)\"\n (Cancelled)=\"onRealtimeAgentPickerCancelled()\">\n </mj-realtime-agent-picker>\n </ng-template>\n</div>\n\n<!-- The voice \"call mode\" overlay is hosted by <mj-conversation-chat-area> (it fills the\n whole conversation panel in place); this component only owns the trigger wiring. -->\n"]}
|