Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

94.6 KB
Raw Blame
// Disable the auto sort key eslint rule to make the code more logic and readable
import { createCallAgentManifest } from '@lobechat/builtin-tool-agent-management';
import { GoalIdentifier, isGoalPrompt } from '@lobechat/builtin-tool-goal';
import { isDesktop, isHeterogeneousAgentModelId, LOADING_FLAT } from '@lobechat/const';
import { formatSelectedSkillsContext, formatSelectedToolsContext } from '@lobechat/context-engine';
import { collectHeteroAttachedFiles } from '@lobechat/heterogeneous-agents';
import type {
  ChatTopicMetadata,
  ConversationContext,
  MessageMetadata,
  SendMessageParams,
  SendMessageServerResponse,
} from '@lobechat/types';
import {
  applyTopicModelToHeterogeneousProvider,
  resolveAgentAgencyConfig,
  toComposerUserMessage,
} from '@lobechat/types';
import { generateEntityId, nanoid } from '@lobechat/utils';
import { toast } from '@lobehub/ui';
import { t } from 'i18next';

import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { type ChatInputEditor } from '@/features/ChatInput';
import { saveDraft } from '@/features/ChatInput/draftStorage';
import {
  ensureAgentManagementAccess,
  getRuntimeCanManageAgent,
} from '@/helpers/agentManagementAccess';
import {
  applyTopicDeviceBinding,
  getTopicBoundDeviceId,
  resolveWorkspaceScoped,
} from '@/helpers/executionTarget';
import { agentService } from '@/services/agent';
import { aiAgentService, MAX_CLIENT_OPERATION_SNAPSHOT } from '@/services/aiAgent';
import { aiChatService } from '@/services/aiChat';
import { resolveSelectedSkillsWithContent } from '@/services/chat/mecha/skillPreload';
import { resolveSelectedToolsWithContent } from '@/services/chat/mecha/toolPreload';
import { messageService } from '@/services/message';
import { topicService } from '@/services/topic';
import { getAgentStoreState } from '@/store/agent';
import {
  agentByIdSelectors,
  agentSelectors,
  chatConfigByIdSelectors,
} from '@/store/agent/selectors';
import { agentGroupByIdSelectors, getChatGroupStoreState } from '@/store/agentGroup';
import {
  resolvePendingSandboxSelection,
  toSandboxTopicMetadata,
} from '@/store/chat/pendingSandboxSelection';
import { consumePendingTopicRepos, getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';
import {
  dbMessageSelectors,
  displayMessageSelectors,
  operationSelectors,
  topicSelectors,
} from '@/store/chat/selectors';
import { leaveBlankConversationBucket } from '@/store/chat/slices/agentRun/actions/clearBlankBucket';
import { selectRuntimeType } from '@/store/chat/slices/agentRun/actions/dispatch/agentDispatcher';
import {
  executeDirectMention,
  toDirectMentionThreadTitle,
} from '@/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor';
import { resolveNewThreadIntent } from '@/store/chat/slices/agentRun/actions/dispatch/newThreadIntent';
import { buildRunLifecycle } from '@/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle';
import {
  drainQueuedTurn,
  findOrphanedQueueKey,
  sendQueuedTurn,
} from '@/store/chat/slices/agentRun/actions/lifecycle/queuedFollowUp';
import type { RunScope } from '@/store/chat/slices/agentRun/actions/lifecycle/types';
import {
  buildQueuedFollowUpRequest,
  resolveUserInterventionConfig,
} from '@/store/chat/slices/agentRun/actions/transports/gateway/execRequest';
import {
  canQueueOnServer,
  findServerHeldQueueKey,
  handOffQueuedMessage,
  reclaimServerQueuedMessages,
} from '@/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue';
import { findUntrackedHeteroMarker } from '@/store/chat/slices/agentRun/actions/transports/gateway/untrackedHeteroRun';
import {
  getNativeHeteroSessionBindingKey,
  resolveHeteroResume,
} from '@/store/chat/slices/agentRun/actions/transports/hetero/heteroResume';
import { snapshotQueuedFiles } from '@/store/chat/slices/operation/types';
import { PortalViewType } from '@/store/chat/slices/portal/initialState';
import { chatPortalSelectors } from '@/store/chat/slices/portal/selectors';
import { topicListFilterOf } from '@/store/chat/slices/topic/projection';
import { resolveTopicHeteroPin } from '@/store/chat/slices/topic/selectors';
import { type ChatStore } from '@/store/chat/store';
import {
  mergeAgentRuntimeInitialContexts,
  resolveActiveTopicDocumentInitialContext,
} from '@/store/chat/utils/activeTopicDocumentContext';
import { hasRunningCompressionOperation } from '@/store/chat/utils/compression';
import { isLocalOnlyMessage } from '@/store/chat/utils/localMessages';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { snapshotAgentModel, snapshotAgentReasoning } from '@/store/chat/utils/snapshotAgentModel';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import { getElectronStoreState } from '@/store/electron';
import { getFileStoreState } from '@/store/file/store';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { type StoreSetter } from '@/store/types';
import { getUserStoreState } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
import { useUserMemoryStore } from '@/store/userMemory';
import { toTitleText } from '@/utils/markdownToTxt';
import { aggregateSubagentMetrics } from '@/utils/subagentMetrics';

import { materializeLocalSystemToolSnapshots } from '../../transports/client/localSystemToolSnapshots';
import type { CommandSendOverrides } from '../commandBus';
import {
  hasNonActionContent,
  injectReferTopicNode,
  mergeLocalFileReferences,
  parseGatewaySkillIdsFromEditorData,
  parseLocalFileReferencesFromEditorData,
  parseMentionedAgentsFromEditorData,
  parseSelectedSkillsFromEditorData,
  parseSelectedToolsFromEditorData,
  parseSingleAgentMentionDirectRoute,
  processCommands,
} from '../commandBus';
import { pageConversationNeedsGateway, preparePageConversation } from '../pageConversation';
import { mergePartialPersistedMessages, resolveSendResponseMessages } from '../persistedMessages';
import { resolveExistingTopicForRun } from '../resolveExistingTopic';
import { type ContextCompressionOptions, executeContextCompression } from './compression';
import { getOptimisticMessageMedia } from './optimisticMessageMedia';
import { findRunningBlockingOp } from './queueBlockingOp';
import { resolveSendProjectRun, resolveSendRunCwd, type SourceTopicDirectory } from './runCwd';
import { showSendErrorInContext } from './sendErrorNotice';
import { submitFirstSendWorktree } from './submitFirstSendWorktree';

/**
 * Extended params for sendMessage with context
 */
export interface SendMessageWithContextParams extends SendMessageParams {
  /**
   * Conversation context (required for cross-store usage)
   * Contains sessionId, topicId, and threadId
   */
  context: ConversationContext;
  /**
   * Editor owned by the calling ConversationProvider. Embedded conversations
   * must not fall back to ChatStore's global editor, which may belong to a
   * sibling panel. Pass `null` when the send is not backed by a composer editor
   * at all, so a failed send is not written into the global one.
   */
  inputEditor?: ChatInputEditor | null;
  /** Restore composer-owned context when sending fails before a message owns it. */
  onPreflightFailure?: () => void;
  /**
   * Called as soon as the backend reports a newly created topic id, so callers
   * with an isolated topic scope (e.g. Task Manager) can switch their UI to the
   * new topic while the AI response is still streaming.
   *
   * Only invoked when `context.isolatedTopic` is true; otherwise the store's
   * own `switchTopic` handles the transition on the global chat store.
   */
  onTopicCreated?: (topicId: string) => void | Promise<void>;
  /** Topic a new topic continues (a handoff): only its cwd carries over, never its CLI session. */
  sourceTopic?: SourceTopicDirectory;
}

/**
 * Result returned from sendMessage
 */
export interface SendMessageResult {
  /** The created assistant message ID */
  assistantMessageId: string;
  /** The created thread ID (if a new thread was created) */
  createdThreadId?: string;
  /** The created topic ID (if a new topic was created in this call) */
  createdTopicId?: string;
  /** The created user message ID */
  userMessageId: string;
}

type SendMessageServerResponseMeta = SendMessageServerResponse & {
  __isPartialMessages?: boolean;
};

interface OptimisticTopicPlaceholder {
  id: string;
  metadata?: ChatTopicMetadata;
  /** Pinned model snapshot β€” top-level `topics.model` column, not metadata. */
  model?: string;
  provider?: string;
  title: string;
}

/**
 * Actions managing the complete lifecycle of conversations including sending,
 * regenerating, and resending messages
 */

type Setter = StoreSetter<ChatStore>;
export const conversationLifecycle = (set: Setter, get: () => ChatStore, _api?: unknown) =>
  new ConversationLifecycleActionImpl(set, get, _api);

const throwIfSendAborted = (signal?: AbortSignal) => {
  if (!signal?.aborted) return;

  throw signal.reason instanceof Error
    ? signal.reason
    : new DOMException('Message send was cancelled', 'AbortError');
};

export class ConversationLifecycleActionImpl {
  readonly #get: () => ChatStore;

  constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
    void _api;
    void set;
    this.#get = get;
  }

  /** The active topic-list filter, forwarded to `sendMessageInServer` (see `topicListFilterOf`). */
  #getTopicFilter = (agentId?: string, groupId?: string) =>
    agentId || groupId
      ? topicListFilterOf(this.#get().topicDataMap[topicMapKey({ agentId, groupId })])
      : undefined;

  /**
   * Land a thread the server created for this send: record it on the operation,
   * pivot the portal from the staged `isNew` thread to the persisted one, and
   * refresh the sidebar's nested list. Shared by both send transports β€” the
   * gateway path creates the thread through `execAgentTask.appContext.newThread`
   * and the client path through `sendMessageInServer.newThread`, but everything
   * downstream of "the row now exists" is identical.
   */
  #syncCreatedThread = (
    operationId: string,
    createdThreadId: string,
    sourceMessageId?: string,
  ): void => {
    this.#get().updateOperationMetadata(operationId, { createdThreadId });

    // When the active portal view is already the Thread surface (the
    // main-page "create subtopic" flow staged it before sending), pivot it
    // from `isNew` β†’ persisted thread id. Otherwise the thread was started
    // by a panel-hosted ConversationProvider (e.g. FloatingChatPanel inside
    // the Document portal) and we must NOT push a Thread view β€” doing so
    // would cover the host view the user is still reading.
    const currentPortalViewType = chatPortalSelectors.currentViewType(this.#get());
    if (currentPortalViewType === PortalViewType.Thread) {
      this.#get().openThreadInPortal(createdThreadId, sourceMessageId);
    } else {
      this.#get().syncThreadInPortal(createdThreadId, sourceMessageId);
    }

    // Refresh threads list to update the sidebar
    void Promise.resolve(this.#get().refreshThreads()).catch(console.error);
  };

  sendMessage = async ({
    message,
    editorData: inputEditorData,
    files,
    forceRuntime,
    metadata,
    onlyAddUserMessage,
    context,
    contextSelections,
    inputEditor,
    messages: inputMessages,
    firstSendWorktree,
    newTopicWorkingDirectory,
    optimisticUserMessageId,
    parentId: inputParentId,
    pageSelections,
    onPreflightFailure,
    onMessageAccepted,
    onMessagePersisted,
    onTopicCreated,
    preserveComposer,
    queueHead,
    signal,
    sourceTopic,
  }: SendMessageWithContextParams): Promise<SendMessageResult | undefined> => {
    throwIfSendAborted(signal);

    let detachCallerAbort = () => {};
    let hasNotifiedMessageAccepted = false;
    let sendOperationId: string | undefined = undefined;
    // Where the user was when they hit send. Continuations adopt the topic this send
    // creates only while the conversation is still here β€” the awaited preflight (access
    // check, snapshots, topic resolution) is long enough to open another topic, and a
    // switchTopic would yank the message list and URL back (`onlyIfActiveTopicIn`
    // below). Agent and group are pinned too: two blank views share
    // `activeTopicId === null`. The workspace scopes the agent CLI run it may start.
    const sendOriginWorkspaceId = getActiveWorkspaceId();
    const sendOriginActiveTopicId = this.#get().activeTopicId || null;
    const sendOriginActiveAgentId = this.#get().activeAgentId ?? null;
    const sendOriginActiveGroupId = this.#get().activeGroupId ?? null;
    const detachUnacceptedCallerAbort = () => {
      if (!hasNotifiedMessageAccepted) detachCallerAbort();
    };
    const notifyMessageAccepted = () => {
      if (hasNotifiedMessageAccepted) return;

      hasNotifiedMessageAccepted = true;
      // Queued messages are accepted before a send operation exists; a send's acceptance ends its optimistic phase.
      if (sendOperationId) {
        this.#get().updateOperationMetadata(sendOperationId, { inputEditorTempState: null });
      }
      detachCallerAbort();
      try {
        onMessageAccepted?.();
      } catch (error) {
        console.error('[sendMessage] onMessageAccepted callback failed:', error);
      }
    };
    let hasNotifiedMessagePersisted = false;
    const notifyMessagePersisted = () => {
      if (hasNotifiedMessagePersisted) return;

      notifyMessageAccepted();
      hasNotifiedMessagePersisted = true;
      try {
        onMessagePersisted?.();
      } catch (error) {
        console.error('[sendMessage] onMessagePersisted callback failed:', error);
      }
    };

    let editorData = inputEditorData;
    const { executeClientAgent, mainInputEditor } = this.#get();
    // `inputEditor` names the editor that owns this send. An explicit `null`
    // means "this send has no composer editor": an embedded reply (a task run's
    // inline follow-up) must not fall back to ChatStore's global editor, which
    // belongs to a sibling surface and would be refilled with this send's text
    // when it fails. Only an omitted editor falls back to the global one.
    const targetInputEditor = inputEditor === undefined ? mainInputEditor : inputEditor;
    const ownerAgentId = context.agentId;
    const selectedSkills = parseSelectedSkillsFromEditorData(editorData);
    const selectedSkillIds = parseGatewaySkillIdsFromEditorData(editorData);
    const selectedTools = parseSelectedToolsFromEditorData(editorData);
    if (
      isGoalPrompt(message) &&
      !selectedTools.some(({ identifier }) => identifier === GoalIdentifier)
    ) {
      selectedTools.push({ identifier: GoalIdentifier, name: 'Goal' });
    }
    const mentionedAgents = parseMentionedAgentsFromEditorData(editorData);

    const localFileReferences = mergeLocalFileReferences(
      parseLocalFileReferencesFromEditorData(editorData),
    );

    // Use context from params (required)
    // If creating new thread (isNew + scope='thread'), threadId will be created by server
    const isCreatingNewThread = context.isNew && context.scope === 'thread';
    // Shared with the gateway transport so both send paths materialise a staged
    // subtopic the same way.
    const newThread = resolveNewThreadIntent(context);

    if (!ownerAgentId) {
      onPreflightFailure?.();
      return;
    }

    // A single explicit @Agent is an execution route, not a supervisor turn.
    // Keep the current conversation as the owner, but resolve runtime/config
    // from the mentioned agent so Lobe AI is never invoked for this message.
    const directMentionRoute = !context.groupId
      ? parseSingleAgentMentionDirectRoute(editorData)
      : undefined;
    const agentId = directMentionRoute?.agent.id ?? ownerAgentId;

    let agentState = getAgentStoreState();
    let agentConfig = agentSelectors.getAgentConfigById(agentId)(agentState);
    if (directMentionRoute && !agentConfig) {
      const targetAgentConfig = await agentService.getAgentConfigById(agentId);
      if (!targetAgentConfig) throw new Error(`Mentioned agent not found: ${agentId}`);

      agentState.internal_dispatchAgentMap(agentId, targetAgentConfig);
      agentState = getAgentStoreState();
      agentConfig = agentSelectors.getAgentConfigById(agentId)(agentState);
    }
    const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
    const currentUserId = userProfileSelectors.userId(getUserStoreState());
    // Author-or-admin, mirroring the picker (`useAgentManagementAccess`) and
    // the server (`isResourceAuthorOrAdmin`) β€” an admin's own override must
    // survive a `fixed` selection policy just like the author's does. On a
    // cold load or a direct mention the picker's hook may never have run, so
    // resolve access from the server first (no-op for authors and members
    // whose answer is already cached).
    await ensureAgentManagementAccess({
      agentId,
      agentUserId: agent?.userId,
      currentUserId,
      visibility: agent?.visibility,
      workspaceId: agent?.workspaceId,
    });
    const canManage = getRuntimeCanManageAgent({
      agentId,
      agentUserId: agent?.userId,
      currentUserId,
    });
    const usesWorkspaceMemberSelection =
      !!agent?.workspaceId && agent.visibility !== 'private' && !canManage;
    // Every workspace caller's override matters β€” a manager's / private owner's
    // `local` pick also lives in `agentDeviceOverrides` (the shared row must
    // never reference a personal device); `resolveAgentAgencyConfig` decides
    // how it applies per role.
    const deviceOverride = agent?.workspaceId
      ? getUserStoreState().workspaceUserPreference.agentDeviceOverrides?.[agentId]
      : undefined;
    // Runtime selection uses the switcher's per-user device override (a private
    // workspace-local pick is safe to run in-process on this member's desktop);
    // an existing conversation then stays on the machine it already ran on.
    const topicBinding = applyTopicDeviceBinding(
      {
        agencyConfig: resolveAgentAgencyConfig(agentConfig?.agencyConfig, deviceOverride, {
          canManage,
          visibility: agent?.visibility,
          workspaceId: agent?.workspaceId,
        }),
        workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),
      },
      getTopicBoundDeviceId(
        context.topicId ? topicSelectors.getTopicById(context.topicId)(this.#get()) : undefined,
        agentId,
      ),
      getElectronStoreState().gatewayDeviceInfo?.deviceId,
      { isHetero: isHeterogeneousAgentModelId(agentConfig?.model) },
    );
    const { workspaceScoped } = topicBinding;
    let { agencyConfig } = topicBinding;
    const isGatewayMode =
      this.#get().isGatewayModeEnabled(agentId) || pageConversationNeedsGateway(context);
    const boundTopic = context.topicId
      ? topicSelectors.getTopicById(context.topicId)(this.#get())
      : undefined;
    const pendingDirectory = this.#get().pendingNewTopicDirectory;
    const { inheritedTopic, ...projectRun } = await resolveSendProjectRun({
      agencyConfig,
      boundDirectoryId: boundTopic?.projectWorkingDirectoryId,
      context,
      directMentionRoute: !!directMentionRoute && !(agentId === ownerAgentId && firstSendWorktree),
      isGatewayMode,
      ownerAgentId,
      pendingDirectory,
      sourceTopic,
    });
    ({ agencyConfig } = projectRun);
    const { newTopicProject, stagedDirectory, stagedProjectId } = projectRun;
    if (stagedDirectory) consumePendingTopicRepos(ownerAgentId); // a cloud repo pick conflicts

    // Legacy agents may only carry `model: '<cli-type>'`. Keep gateway routing
    // unchanged when it is available. Recover the provider when gateway mode is
    // off so desktop can still spawn locally and non-desktop (Android/web) still
    // routes through Gateway instead of the Provider API.
    const heterogeneousProvider =
      agencyConfig?.heterogeneousProvider ??
      (!isGatewayMode && isHeterogeneousAgentModelId(agentConfig?.model)
        ? { type: agentConfig.model }
        : undefined);
    const runtimeType = selectRuntimeType({
      boundDeviceId: agencyConfig?.boundDeviceId,
      executionTarget: agencyConfig?.executionTarget,
      heterogeneousProvider,
      isGatewayMode,
      isWorkspaceAgent: !!agent?.workspaceId,
      // Callers that need to pin the runtime (e.g. task topics that were
      // started server-side via runTask) pass `forceRuntime` to override
      // the agent's local/cloud preference.
      parentRuntime: forceRuntime,
      workspaceScoped,
    });

    // ── Command Bus: extract and process built-in commands from editorData ──
    const commandOverrides: CommandSendOverrides = processCommands({
      message,
      editorData,
      files,
      onlyAddUserMessage,
      context,
      messages: inputMessages,
      parentId: inputParentId,
      pageSelections,
      contextSelections,
    });

    // /compact β€” directly compress context without sending any message
    if (commandOverrides.triggerCompression) {
      const compressContext = { ...context };
      if (
        compressContext.topicId &&
        !hasRunningCompressionOperation(Object.values(this.#get().operations), compressContext)
      ) {
        await this.executeCompression(compressContext, '');
      }
      return;
    }

    // /newTopic β€” force a fresh topic regardless of current context
    let forceNewTopicFromExisting = false;
    if (commandOverrides.forceNewTopic) {
      const hasFile = files && files.length > 0;
      // If no message content besides the action tag and no files, just navigate to a new topic without sending
      if (!hasNonActionContent(editorData) && !hasFile) {
        await this.#get().switchTopic(null);
        return;
      }

      if (context.topicId) {
        const originalTopic = topicSelectors.getTopicById(context.topicId)(this.#get());
        const topicTitle = originalTopic?.title || '';
        // Inject referTopic into content for LLM context
        const referTag = `<refer_topic name="${topicTitle}" id="${context.topicId}" />`;
        message = `${referTag}\n${message}`;
        // Inject refer-topic node into editorData for rich text display
        editorData = injectReferTopicNode(editorData, context.topicId, topicTitle);
        forceNewTopicFromExisting = true;
      }
      context = { ...context, topicId: undefined };
    }

    // When creating new thread, override threadId to undefined (server will create it)
    // Check if current agentId is the supervisor agent of the group
    let isGroupSupervisor = false;
    if (context.groupId) {
      const group = agentGroupByIdSelectors.groupById(context.groupId)(getChatGroupStoreState());
      isGroupSupervisor = group?.supervisorAgentId === agentId;
    }
    // In non-group context, @agent mentions make the current agent act as supervisor
    const hasMentionedAgents =
      !context.groupId && !directMentionRoute && mentionedAgents.length > 0;

    const activePageDocumentId = await preparePageConversation(context);

    // Whether this send has to create the topic. From here on this flag β€” NOT
    // `!operationContext.topicId` β€” is the "new topic" test: the conversation
    // adopts its client-minted topic id below, so the context CARRIES a topicId
    // for a topic that does not exist on the server yet.
    const willCreateNewTopic = !context.topicId;

    // The optimistic topic, its messages and the server share one final id.
    // Isolated callers re-subscribe via onTopicCreated instead.
    const mintedTopicId =
      willCreateNewTopic && !context.isolatedTopic ? generateEntityId('topics') : undefined;

    const operationContext = {
      ...context,
      agentId: ownerAgentId,
      ...(isCreatingNewThread && { threadId: undefined }),
      // Only set the supervisor markers for actual group supervisors β€” NOT for
      // @agent mentions. These drive group-specific UI rendering (SupervisorMessage
      // with group avatars). orchestrationRole is the canonical field; isSupervisor
      // is kept for back-compat.
      ...(isGroupSupervisor && { isSupervisor: true, orchestrationRole: 'supervisor' as const }),
      ...(activePageDocumentId ? { documentId: activePageDocumentId } : {}),
      ...(mintedTopicId ? { topicId: mintedTopicId } : {}),
    };

    const fileIdList = files?.map((f) => f.id);
    const isLocalSystemEnabled =
      chatConfigByIdSelectors.isLocalSystemEnabledById(agentId)(getAgentStoreState());
    const canMaterializeLocalFiles =
      isDesktop &&
      localFileReferences.length > 0 &&
      !metadata?.localSystemToolSnapshots?.length &&
      (!!heterogeneousProvider || isLocalSystemEnabled);
    const localSystemToolSnapshots = canMaterializeLocalFiles
      ? await materializeLocalSystemToolSnapshots(localFileReferences).catch((error) => {
          onPreflightFailure?.();
          throw error;
        })
      : [];
    const userMessageMetadata =
      metadata ||
      contextSelections?.length ||
      pageSelections?.length ||
      localSystemToolSnapshots.length
        ? {
            ...metadata,
            ...(contextSelections?.length ? { contextSelections } : undefined),
            ...(pageSelections?.length ? { pageSelections } : undefined),
            ...(localSystemToolSnapshots.length ? { localSystemToolSnapshots } : undefined),
          }
        : undefined;

    // Enrich selected skills/tools with preloaded content, injected directly
    // via SelectedSkillInjector/SelectedToolInjector β€” no fake tool-call preload messages
    const enrichedSelectedSkills = await resolveSelectedSkillsWithContent({
      message,
      selectedSkills,
    }).catch((error) => {
      onPreflightFailure?.();
      throw error;
    });
    const enrichedSelectedTools = resolveSelectedToolsWithContent({
      message,
      selectedTools,
    });
    const requestTrigger = (metadata as Pick<MessageMetadata, 'trigger'> | undefined)?.trigger;
    const requestMetadata = requestTrigger ? { trigger: requestTrigger } : undefined;

    throwIfSendAborted(signal);

    const hasFile = !!fileIdList && fileIdList.length > 0;

    // if message is empty or no files, then stop
    if (!message && !hasFile) {
      onPreflightFailure?.();
      return;
    }

    const newTopicTitle = toTitleText(message).slice(0, 80) || t('defaultTitle', { ns: 'topic' });

    // ━━━ Message Queue: enqueue if this context is already busy ━━━
    // Include the initial `sendMessage` persist/create-topic phase: while a first
    // send is still creating topic A, a fast second Enter queues on
    // `main_<agent>_new` instead of starting topic B.
    const currentContextKey = messageMapKey(operationContext);
    // A new-topic send must ALSO queue behind a send still creating its topic for
    // this surface. That send's operation is registered under ITS minted topic's
    // bucket, so probing only this send's key would miss it and a fast second
    // Enter would start a concurrent topic. `creatingTopicIds` names those buckets.
    const queueCandidateKeys = [
      currentContextKey,
      ...(willCreateNewTopic
        ? [
            // The pre-mint `_new` key: ops that predate topic adoption (or any
            // legacy caller) still register here.
            messageMapKey({ ...operationContext, topicId: null }),
            ...this.#get().creatingTopicIds.map((creatingId) =>
              messageMapKey({ ...operationContext, topicId: creatingId }),
            ),
          ].filter((key) => key !== currentContextKey)
        : []),
    ];
    let queueTargetKey = currentContextKey;
    let runningQueueBlockingOp: ReturnType<typeof findRunningBlockingOp>;
    for (const key of queueCandidateKeys) {
      runningQueueBlockingOp = findRunningBlockingOp(this.#get, key, optimisticUserMessageId);
      if (runningQueueBlockingOp) {
        queueTargetKey = key;
        break;
      }
    }
    // The head of a queue drained one per turn starts its turn; the rest waits behind it.
    const queueDrainPending =
      !runningQueueBlockingOp &&
      !onlyAddUserMessage &&
      !queueHead &&
      operationSelectors.isQueueDrainPending(operationContext)(this.#get());
    const canQueue = (key: string) =>
      !onlyAddUserMessage &&
      canQueueOnServer(this.#get, key, {
        context: operationContext,
        isGatewayRun: runtimeType === 'gateway' && !directMentionRoute && !willCreateNewTopic,
      });
    /** Queue this send behind what holds `key`; on the server when the run can join it there. */
    const queueThisSend = (key: string) => {
      const queuedId = nanoid();
      const queueOnServer = canQueue(key);
      this.#get().enqueueMessage(
        key,
        {
          id: queuedId,
          content: message,
          editorData: editorData ?? undefined,
          files: fileIdList,
          filesPreview: snapshotQueuedFiles(files),
          ...(forceRuntime ? { forceRuntime } : {}),
          interruptMode: 'soft',
          metadata: userMessageMetadata,
          createdAt: Date.now(),
          ...(queueOnServer && { serverDelivery: 'appending' as const }),
        },
        runningQueueBlockingOp?.id,
      );
      if (queueOnServer)
        void handOffQueuedMessage(this.#get, key, operationContext, queuedId, () =>
          buildQueuedFollowUpRequest(this.#get, {
            context: operationContext,
            contextSelections,
            fileIds: fileIdList,
            mentionedAgents: hasMentionedAgents ? mentionedAgents : undefined,
            message,
            pageSelections,
            selectedSkillIds,
            selectedToolIds: selectedTools.map((tool) => tool.identifier),
            trigger: requestTrigger,
          }),
        );
      notifyMessageAccepted();
    };
    // A live hetero run this tab lost track of takes the send as a steer, never a parallel run.
    const untrackedHetero =
      canQueue(currentContextKey) && !!findUntrackedHeteroMarker(this.#get, operationContext);
    if (runningQueueBlockingOp || queueDrainPending || untrackedHetero)
      return void queueThisSend(queueTargetKey);

    // Nothing runs: take server-queued follow-ups back; one still being delivered keeps its place.
    await Promise.all(queueCandidateKeys.map((key) => reclaimServerQueuedMessages(this.#get, key)));
    const heldKey = findServerHeldQueueKey(this.#get, queueCandidateKeys);
    if (heldKey && !onlyAddUserMessage) return void queueThisSend(heldKey);

    const orphanedQueueKey = findOrphanedQueueKey(
      this.#get,
      queueCandidateKeys,
      willCreateNewTopic,
    );
    if (orphanedQueueKey && !onlyAddUserMessage && !queueHead) {
      this.#get().enqueueMessage(orphanedQueueKey, {
        content: message,
        createdAt: Date.now(),
        editorData: editorData ?? undefined,
        files: fileIdList,
        filesPreview: snapshotQueuedFiles(files),
        ...(forceRuntime ? { forceRuntime } : {}),
        id: nanoid(),
        interruptMode: 'soft',
        metadata: userMessageMetadata,
      });
      const restarted = drainQueuedTurn(this.#get, orphanedQueueKey);
      notifyMessageAccepted();

      setTimeout(() => {
        sendQueuedTurn(this.#get, operationContext, restarted).catch((error: unknown) => {
          console.error('[sendMessage] restarting queued content after Stop failed:', error);
        });
      }, 0);

      return;
    }

    const serverRuntimeOperations = queueCandidateKeys
      .flatMap((key) => this.#get().operationsByContext[key] || [])
      .map((id) => this.#get().operations[id])
      .filter((operation) => operation?.type === 'execServerAgentRuntime');

    const replaceableGatewayOperationId = serverRuntimeOperations.findLast(
      (operation) =>
        operation.status === 'running' &&
        (operation.metadata.isAborting || operation.metadata.visibleLoadingDone),
    )?.metadata.serverOperationId;

    // What this client believes about the conversation's server runs. The
    // server keeps it only when the send has to stop a run left live.
    const clientOperations = serverRuntimeOperations
      .filter((operation) => operation.metadata.serverOperationId)
      .slice(-MAX_CLIENT_OPERATION_SNAPSHOT)
      .map((operation) => ({
        isAborting: operation.metadata.isAborting,
        operationId: operation.metadata.serverOperationId!,
        status: operation.status,
        visibleLoadingDone: operation.metadata.visibleLoadingDone,
      }));

    if (onlyAddUserMessage) {
      await this.#get().addUserMessage({
        message,
        fileList: fileIdList,
        metadata: userMessageMetadata,
      });
      notifyMessagePersisted();

      return;
    }

    // Use provided messages or query from store
    // For /newTopic from existing topic, start with empty message list (fresh topic)
    const contextKey = messageMapKey(context);
    const messages = (
      forceNewTopicFromExisting
        ? []
        : (inputMessages ??
          displayMessageSelectors.getDisplayMessagesByKey(contextKey)(this.#get()))
    ).filter((item) => !isLocalOnlyMessage(item));
    // Historical callback/tool sibling forks are rendered with the recovered
    // taskCallback card as supplemental history. It is not the active
    // conversational tail: using it here lets findLastMessageId descend into
    // the callback's inactive assistant branch, so the next user message is
    // persisted there and disappears from the main flow after reconciliation.
    const lastMessage =
      messages.findLast((message) => message.role !== 'taskCallback') ?? messages.at(-1);

    useUserMemoryStore.getState().setActiveMemoryContext({
      agent: agentSelectors.getAgentMetaById(agentId)(getAgentStoreState()),
      topic: topicSelectors.currentActiveTopic(this.#get()),
      latestUserMessage: lastMessage?.content,
      sendingMessage: message,
    });

    // Use provided parentId or calculate from messages
    let parentId: string | undefined = forceNewTopicFromExisting ? undefined : inputParentId;
    if (!parentId && lastMessage) {
      parentId = displayMessageSelectors.findLastMessageId(lastMessage.id)(this.#get());
    }

    // Mint the ids this turn will live under, up front. These are the FINAL
    // ids: the server honours them verbatim (`newUserMessage.id` /
    // `newAssistantMessage.id`), so the optimistic rows never have to be
    // re-keyed when the response lands. That is what keeps the conversation's
    // identity β€” and therefore the mounted message list β€” stable across the
    // whole send.
    const tempId = optimisticUserMessageId ?? generateEntityId('messages');
    const tempAssistantId = generateEntityId('messages');
    const steeredTurnStartTime = (metadata as Pick<MessageMetadata, 'steer'> | undefined)?.steer
      ? operationSelectors.getLatestAgentRuntimeTurnStartTime(operationContext)(this.#get())
      : undefined;
    // Editor state for cancel restoration, on the op from its start: a Stop during
    // the preflight awaits below must find it, or the draft is never handed back.
    const jsonState = preserveComposer
      ? undefined
      : (inputEditorData ?? targetInputEditor?.getJSONState());
    const { operationId, abortController } = this.#get().startOperation({
      type: 'sendMessage',
      context: { ...operationContext, messageId: tempId },
      label: 'Send Message',
      metadata: {
        // Mark this as thread operation if threadId exists
        inThread: !!operationContext.threadId,
        inputEditorTempState: jsonState,
        ...(steeredTurnStartTime === undefined ? {} : { turnStartTime: steeredTurnStartTime }),
      },
    });
    sendOperationId = operationId;
    // Voice recording starts before a first-send topic exists, so its upload
    // transaction and local row initially live in the legacy `_new` bucket.
    // Adopt the client-minted topic context before looking up that row; otherwise
    // the formal send would create a duplicate in the minted bucket.
    this.#get().moveVoiceMessages(context, operationContext);

    const cleanupTempMessages = (options?: { preserveOptimisticUser?: boolean }) => {
      const ids = options?.preserveOptimisticUser ? [tempAssistantId] : [tempId, tempAssistantId];
      this.#get().internal_dispatchMessage({ ids, type: 'deleteMessages' }, { operationId });
    };
    /**
     * Put the typed message back in the composer when a send fails before the
     * user message was persisted. The composer is cleared the instant Enter is
     * pressed, so without this the text is gone for good β€” the run never
     * happened, and there is no persisted row to recover it from.
     *
     * Shared by all three runtime branches. Gateway and hetero previously only
     * logged and deleted the optimistic pair, so a server-side start refusal
     * (e.g. the topic-start reservation reporting the topic busy) was
     * indistinguishable from the message being silently swallowed.
     */
    const restoreComposerAfterFailedSend = (error: unknown) => {
      if (preserveComposer || hasNotifiedMessageAccepted) return;

      // A Stop (an AbortError, or the signal's own reason a transport rethrows) has its
      // own restore path (the cancel flow replays `inputEditorTempState`); don't fight it.
      const isAbort =
        (abortController.signal.aborted && error === abortController.signal.reason) ||
        (error instanceof Error &&
          (error.message.includes('aborted') || error.name === 'AbortError'));
      if (isAbort) return;

      this.#get().updateOperationMetadata(operationId, {
        inputSendErrorMsg: error instanceof Error ? error.message : 'Unknown error',
      });

      const op = this.#get().operations[operationId];
      if (op?.metadata.inputEditorTempState) {
        targetInputEditor?.setJSONState(op.metadata.inputEditorTempState);
      } else {
        targetInputEditor?.setDocument('markdown', message);
      }

      // The editor snapshot covers only text. A send rejected after the composer
      // was cleared (e.g. the server refusing an offline bound device) would
      // otherwise still swallow the cleared uploads and context selections β€”
      // hand them back to the caller that captured them before clearing.
      onPreflightFailure?.();
    };
    const restoreUnacceptedVoiceMessageContext = () => {
      if (!optimisticUserMessageId || hasNotifiedMessageAccepted) return;

      // The minted topic is rolled back on a pre-accept failure. Return the
      // retry-owned upload operation and playable local row to the visible
      // `_new` conversation instead of leaving them under a deleted topic id.
      this.#get().moveVoiceMessages(operationContext, context);
    };
    if (signal) {
      const cancelFromCaller = () => {
        const operation = this.#get().operations[operationId];
        if (hasNotifiedMessageAccepted || operation?.status !== 'running') return;

        this.#get().cancelOperation(operationId, 'Caller cancelled before message acceptance');
      };

      if (signal.aborted) {
        cancelFromCaller();
      } else {
        signal.addEventListener('abort', cancelFromCaller, { once: true });
        detachCallerAbort = () => signal.removeEventListener('abort', cancelFromCaller);
      }
    }
    throwIfSendAborted(signal);

    // Shared run lifecycle for the post-persist topic-title hook. Built once here
    // so all three runtime branches fire the SAME `afterUserMessagePersisted`
    // β€” gateway/hetero previously had no LLM title before the unified lifecycle.
    // `parentMessage*` are unused by this hook.
    const sendRunScope: RunScope =
      operationContext.scope === 'sub_agent' ? 'sub_agent' : 'top_level';
    const sendRunLifecycle = buildRunLifecycle(this.#get, {
      context: operationContext,
      parentMessageId: parentId ?? tempId,
      parentMessageType: 'user',
      runId: operationId,
      runScope: sendRunScope,
      runtimeType,
    });

    const optimisticUserMessage = {
      content: message,
      editorData: editorData ?? undefined,
      // if message has attached with files, then add files to message and the agent
      files: fileIdList,
      role: 'user' as const,
      agentId: operationContext.agentId,
      // if there is topicId, then add topicId to message
      topicId: operationContext.topicId ?? undefined,
      threadId: operationContext.threadId ?? undefined,
      ...getOptimisticMessageMedia(files),
      // Pass metadata for immediate display
      metadata: userMessageMetadata,
    };
    const operationMessageKey = messageMapKey(
      this.#get().internal_getConversationContext({ operationId }),
    );
    const existingOptimisticUserMessage = this.#get().dbMessagesMap[operationMessageKey]?.find(
      (item) => item.id === tempId && item.role === 'user',
    );

    // Voice uploads and forced steers can render a local-only row before sending. Adopt
    // that row in place so the formal send keeps its position and never duplicates it.
    if (existingOptimisticUserMessage) {
      this.#get().internal_dispatchMessage(
        {
          id: tempId,
          type: 'updateMessage',
          value: {
            ...optimisticUserMessage,
            groupId: operationContext.groupId,
            metadata: {
              ...existingOptimisticUserMessage.metadata,
              ...userMessageMetadata,
              scope: existingOptimisticUserMessage.metadata?.scope,
            },
          },
        },
        { operationId },
      );
    } else {
      // use optimistic update to avoid the slow waiting (now with operationId for correct context)
      this.#get().optimisticCreateTmpMessage(optimisticUserMessage, {
        operationId,
        tempMessageId: tempId,
      });
    }
    this.#get().optimisticCreateTmpMessage(
      {
        content: LOADING_FLAT,
        role: 'assistant',
        agentId,
        // if there is topicId, then add topicId to message
        topicId: operationContext.topicId ?? undefined,
        threadId: operationContext.threadId ?? undefined,
        // Pass isSupervisor metadata for group orchestration (consistent with server)
        metadata: operationContext.isSupervisor
          ? { isSupervisor: true, orchestrationRole: 'supervisor' as const }
          : undefined,
      },
      { operationId, tempMessageId: tempAssistantId },
    );

    // Associate temp messages with operation
    this.#get().associateMessageWithOperation(tempId, operationId);
    this.#get().associateMessageWithOperation(tempAssistantId, operationId);

    // Group main topic lists are keyed by `group_${groupId}`. Keeping the
    // supervisor agent id here would write "group first message" placeholders
    // into `group_agent_${groupId}_${agentId}`, invisible to the group sidebar.
    const topicListAgentId =
      operationContext.groupId && operationContext.scope === 'group'
        ? undefined
        : operationContext.agentId;
    const optimisticTopicScope = {
      agentId: topicListAgentId,
      groupId: operationContext.groupId ?? undefined,
    };
    // A topic created by this send pins the model it was started with, same as
    // the manual createTopic/saveToTopic and Gateway (AiAgentService) paths. The
    // snapshot goes to the top-level `topics.model`/`provider` columns (config
    // source of truth) β€” generation and ChatInput display resolve from it
    // (topicSelectors.getTopicModelById).
    const newTopicModelSnapshot = willCreateNewTopic
      ? snapshotAgentModel(operationContext.agentId)
      : undefined;

    // Adopt the minted topic id NOW, synchronously with the optimistic message
    // dispatch above: insert the sidebar row and point `activeTopicId` at it in
    // the same React commit that shows the optimistic pair. The conversation's
    // contextKey is therefore final from its very first painted frame β€” nothing
    // remounts when the server later confirms the topic, which is the flicker
    // this whole flow used to have. Everything after this point (cwd
    // resolution, the runtime branches) awaits, so it must come before them.
    if (mintedTopicId) {
      this.#get().internal_dispatchTopic(
        {
          ...optimisticTopicScope,
          optimistic: true,
          type: 'addTopic',
          value: {
            id: mintedTopicId,
            ...newTopicModelSnapshot,
            // Shown under its project group from the first frame.
            ...newTopicProject,
            ...(operationContext.groupId ? {} : { sessionId: operationContext.agentId }),
            title: newTopicTitle,
          },
        },
        'sendMessage/optimisticCreateTopic',
      );
      getFileStoreState().moveChatComposerAttachments(
        messageMapKey({ ...operationContext, topicId: null }),
        currentContextKey,
      );
      // Adopt the minted bucket only while the user is still on the view this
      // send started from. If they navigated away while the awaits above
      // (access check, snapshots) were in flight, don't yank them onto the new
      // topic's bucket. The agent/group pins cover the blank-view case: a
      // null topic origin and another conversation's null topic view are
      // indistinguishable without them.
      await this.#get().switchTopic(mintedTopicId, {
        onlyIfActiveAgentId: sendOriginActiveAgentId,
        onlyIfActiveGroupId: sendOriginActiveGroupId,
        onlyIfActiveTopicIn: [sendOriginActiveTopicId],
        skipRefreshMessage: true,
      });
    }

    // The topic list store is paginated β€” a deep-linked older topic can be the
    // ACTIVE topic yet miss `getTopicById`. For hetero runs that miss used to
    // silently resolve the agent/device default cwd instead of the topic's
    // bound workingDirectory and drop `--resume` (fresh CLI session, context
    // lost, no error) β€” fall back to the server row. A topic this send is
    // about to create has no server row, so the lookup is skipped entirely.
    const existingTopic = await resolveExistingTopicForRun({
      fetchTopicDetail: (id) => topicService.getTopicDetail(id),
      isHetero: !!heterogeneousProvider,
      storeTopic:
        operationContext.topicId && !willCreateNewTopic
          ? topicSelectors.getTopicById(operationContext.topicId)(this.#get())
          : undefined,
      topicId: willCreateNewTopic ? undefined : operationContext.topicId,
    });
    const currentDeviceId = await getElectronStoreState().resolveGatewayDeviceId();
    const { runCwdDeviceId, runEffectiveTarget, workingDirectory, workingDirectoryConfig } =
      await resolveSendRunCwd({
        agencyConfig,
        chatConfig: agentConfig?.chatConfig,
        currentDeviceId,
        draftWorkingDirectory:
          willCreateNewTopic && agentId === ownerAgentId ? newTopicWorkingDirectory : undefined,
        existingTopic,
        heterogeneousProvider,
        inheritedTopic,
        isGatewayMode,
        legacyAgentWorkingDirectory: agentState.localAgentWorkingDirectoryMap[agentId],
        stagedDirectoryPath: stagedDirectory?.path,
        workspaceScoped,
      });
    // Record which machine a new conversation runs on, so its next turn β€” and
    // the device picker β€” stay on it after the agent default changes. `auto`
    // has not picked a machine yet; the server stamps the one it routes to.
    const newTopicDeviceId =
      runEffectiveTarget === 'local' || runEffectiveTarget === 'device'
        ? runCwdDeviceId
        : undefined;
    const pendingTopicRepos =
      runtimeType === 'gateway' && willCreateNewTopic && operationContext.agentId
        ? getPendingTopicRepos(operationContext.agentId)
        : [];
    // Example: a pending repo topic without this metadata renders under "No
    // directory" until the server row lands.
    const newTopicReasoningSnapshot = newTopicModelSnapshot
      ? await snapshotAgentReasoning(operationContext.agentId, newTopicModelSnapshot)
      : undefined;
    const workingDirectoryMetadata: ChatTopicMetadata | undefined =
      pendingTopicRepos.length > 0
        ? {
            repos: pendingTopicRepos,
            workingDirectory: pendingTopicRepos[0],
            workingDirectoryConfig: { path: pendingTopicRepos[0], repoType: 'github' },
          }
        : workingDirectory
          ? {
              ...(newTopicDeviceId ? { boundDeviceId: newTopicDeviceId } : {}),
              workingDirectory,
              ...(workingDirectoryConfig ? { workingDirectoryConfig } : {}),
            }
          : // No directory is a valid state for a native agent, but the machine
            // still has to be recorded: the client runtime creates this topic
            // itself, so no server turn would stamp it afterwards.
            newTopicDeviceId
            ? { boundDeviceId: newTopicDeviceId }
            : undefined;
    // Chosen in the composer while no topic existed to write it to. Not gated
    // on runtime: the map is only ever filled by the sandbox picker, which only
    // renders under a cloud-sandbox target.
    const pendingSandboxSelection =
      willCreateNewTopic && operationContext.agentId
        ? await resolvePendingSandboxSelection(operationContext.agentId)
        : undefined;
    const sandboxInstanceMetadata = toSandboxTopicMetadata(pendingSandboxSelection);
    /** First-send persistence bypasses turnSetup, so both runtime paths must carry the effort snapshot. */
    const optimisticTopicMetadata =
      newTopicReasoningSnapshot || sandboxInstanceMetadata
        ? {
            ...workingDirectoryMetadata,
            ...sandboxInstanceMetadata,
            ...newTopicReasoningSnapshot,
          }
        : workingDirectoryMetadata;

    // The sidebar row was already inserted (title + model) before the awaits
    // above; the cwd/repos metadata only resolves here, so patch it on now.
    // `optimisticTopic` keeps carrying the full snapshot for the resolve /
    // rollback helpers below.
    const optimisticTopic: OptimisticTopicPlaceholder | undefined = mintedTopicId
      ? {
          id: mintedTopicId,
          ...(optimisticTopicMetadata ? { metadata: optimisticTopicMetadata } : {}),
          ...newTopicModelSnapshot,
          title: newTopicTitle,
        }
      : undefined;
    let optimisticTopicActive = false;

    const resolveOptimisticTopic = (topicId: string, title = optimisticTopic?.title) => {
      const value = {
        ...(optimisticTopic?.metadata ? { metadata: optimisticTopic.metadata } : {}),
        ...(optimisticTopic?.model
          ? { model: optimisticTopic.model, provider: optimisticTopic.provider }
          : {}),
        ...(operationContext.groupId ? {} : { sessionId: operationContext.agentId }),
        title: title || t('defaultTitle', { ns: 'topic' }),
      };
      if (!optimisticTopic || !optimisticTopicActive) {
        this.#get().internal_dispatchTopic(
          { ...optimisticTopicScope, type: 'addTopic', value: { ...value, id: topicId } },
          'sendMessage/reconcileOptimisticTopic/add',
        );
        return;
      }

      this.#get().internal_replaceTopicId({
        ...optimisticTopicScope,
        nextId: topicId,
        previousId: optimisticTopic.id,
        value,
      });
      optimisticTopicActive = false;
    };

    const rollbackOptimisticTopic = (action: string) => {
      if (!optimisticTopic || !optimisticTopicActive) return;

      getFileStoreState().moveChatComposerAttachments(
        currentContextKey,
        messageMapKey({ ...operationContext, topicId: null }),
      );
      if (this.#get().activeTopicId === optimisticTopic.id) {
        const op = this.#get().operations[operationId];
        // A cancel or a refused send restores the editor before the topic rolls back. Read the
        // live editor (the user may have edited it meanwhile) and carry it, plus the refusal
        // notice, to the blank conversation: both are keyed by the topic being discarded.
        const sendError = op?.status === 'failed' ? op.metadata.inputSendErrorMsg : undefined;
        if (!hasNotifiedMessageAccepted && (op?.status === 'cancelled' || sendError) && jsonState) {
          const blankContext = { ...operationContext, topicId: null };
          saveDraft(messageMapKey(blankContext), targetInputEditor?.getJSONState() ?? jsonState);
          if (sendError) showSendErrorInContext(this.#get(), blankContext, sendError);
        }
        void this.#get().switchTopic(null, { skipRefreshMessage: true });
        // Adopting the minted topic consumed the staging; the topic never came
        // to be, so the blank conversation still belongs to that directory.
        if (newTopicProject) this.#get().setPendingNewTopicDirectory(pendingDirectory);
      }
      this.#get().internal_dispatchTopic(
        { ...optimisticTopicScope, type: 'deleteTopic', id: optimisticTopic.id },
        action,
      );
      optimisticTopicActive = false;
    };

    if (optimisticTopic) {
      // The row itself (title + model, marked `optimistic`) was inserted before
      // the awaits above so it shares the first paint with the optimistic
      // messages. The cwd/repos metadata only resolved after those awaits β€”
      // patch it on now instead of re-adding the row (an addTopic here would
      // unshift a duplicate).
      if (optimisticTopic.metadata) {
        this.#get().internal_dispatchTopic(
          {
            ...optimisticTopicScope,
            id: optimisticTopic.id,
            type: 'updateTopic',
            value: { metadata: optimisticTopic.metadata },
          },
          'sendMessage/optimisticTopicMetadata',
        );
      }
      optimisticTopicActive = true;
    }

    if (firstSendWorktree && willCreateNewTopic && ownerAgentId === agentId) {
      return submitFirstSendWorktree(this.#get, {
        abandon: (error) => {
          restoreComposerAfterFailedSend(error);
          cleanupTempMessages({ preserveOptimisticUser: Boolean(optimisticUserMessageId) });
          detachUnacceptedCallerAbort();
          rollbackOptimisticTopic('sendMessage/worktreeSubmissionFailed');
          restoreUnacceptedVoiceMessageContext();
        },
        accepted: () => hasNotifiedMessageAccepted,
        complete: () => {
          optimisticTopicActive = false;
          cleanupTempMessages({ preserveOptimisticUser: true });
        },
        mintedTopicId,
        onMessagePersisted: notifyMessagePersisted,
        onTopicCreated: context.isolatedTopic ? onTopicCreated : undefined,
        operationId,
        request: () => ({
          ...newTopicProject,
          agentId,
          assistantMessageId: tempAssistantId,
          fileIds: fileIdList,
          mentionedAgents: hasMentionedAgents ? mentionedAgents : undefined,
          prompt: message,
          selectedSkillIds,
          selectedToolIds: selectedTools.map(({ identifier }) => identifier),
          topicId: mintedTopicId ?? generateEntityId('topics'),
          userInterventionConfig: resolveUserInterventionConfig(),
          userMessage: toComposerUserMessage({ editorData, metadata: userMessageMetadata }),
          userMessageId: tempId,
          worktree: firstSendWorktree,
        }),
        scope: optimisticTopicScope,
        workspaceId: sendOriginWorkspaceId,
      });
    }

    // ── External agent mode: delegate to heterogeneous agent CLI (desktop only) ──
    // Per-agent heterogeneousProvider config takes priority over the global gateway mode.
    if (runtimeType === 'hetero' && heterogeneousProvider) {
      // Resolve cwd up-front so the new topic is bound to a project at
      // creation time. Otherwise the row stays NULL until the post-execution
      // metadata write β€” which never lands on cancel/error and meanwhile
      // makes By-Project grouping miss the topic and `--resume` unsafe.
      //
      // Priority: topic-level cwd (once a topic is bound to a project) wins
      // over the agent-level default. Without this, a topic pinned to dir A
      // would silently execute under the agent's current default dir B and
      // lose resume.
      // Persist messages to DB first (same as client mode)
      let heteroData: SendMessageServerResponse | undefined;
      try {
        throwIfSendAborted(signal);
        heteroData = await aiChatService.sendMessageInServer(
          {
            agentId: operationContext.agentId,
            groupId: operationContext.groupId ?? undefined,
            // External CLIs own model selection and may reroute independently
            // from the agent's requested model. Persist only the runtime
            // provider up front; the adapter backfills the actual model later
            // if the CLI reports it.
            newAssistantMessage: {
              agentId: directMentionRoute ? agentId : undefined,
              id: tempAssistantId,
              provider: heterogeneousProvider.type,
            },
            newTopic: willCreateNewTopic
              ? {
                  // Same id the optimistic sidebar row already uses.
                  id: optimisticTopic?.id,
                  metadata: optimisticTopicMetadata,
                  ...newTopicModelSnapshot,
                  projectId: stagedProjectId,
                  title: newTopicTitle,
                  topicMessageIds: messages.map((m) => m.id),
                }
              : undefined,
            newUserMessage: {
              content: message,
              editorData,
              files: fileIdList,
              id: tempId,
              metadata: userMessageMetadata,
              contextSelections,
              pageSelections,
              parentId,
            },
            threadId: operationContext.threadId ?? undefined,
            topicFilter: this.#getTopicFilter(
              topicListAgentId,
              operationContext.groupId ?? undefined,
            ),
            topicPageSize: systemStatusSelectors.topicPageSize(useGlobalStore.getState()),
            // While creating, the topic exists only client-side β€” the server
            // sees `newTopic` (with the minted id) and no topicId, exactly the
            // shape an older client sends.
            topicId: willCreateNewTopic ? undefined : (operationContext.topicId ?? undefined),
          },
          abortController,
        );
      } catch (e) {
        console.error('[HeterogeneousAgent] Failed to persist messages:', e);
        if (this.#get().operations[operationId]?.status !== 'cancelled') {
          this.#get().failOperation(operationId, {
            message: e instanceof Error ? e.message : 'Unknown error',
            type: 'HeterogeneousAgentError',
          });
          restoreComposerAfterFailedSend(e);
        }
        cleanupTempMessages({ preserveOptimisticUser: Boolean(optimisticUserMessageId) });
        detachUnacceptedCallerAbort();
        rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');
        restoreUnacceptedVoiceMessageContext();
        return;
      }

      if (!heteroData) {
        cleanupTempMessages({ preserveOptimisticUser: Boolean(optimisticUserMessageId) });
        detachUnacceptedCallerAbort();
        rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');
        restoreUnacceptedVoiceMessageContext();
        return;
      }
      notifyMessageAccepted();

      // Update context with server-created topicId. Once the server has returned a
      // persisted topic, the hetero stream must target the real topic bucket; keeping
      // `isNew` would route chunks to `main_<agent>_<topic>_new`.
      const heteroTopicId = heteroData.topicId ?? operationContext.topicId;
      const shouldResolveNewTopicKey = !!heteroTopicId && operationContext.scope !== 'thread';
      const heteroContext = {
        ...operationContext,
        // startOperation inherits from the parent op before merging this context.
        // Use an explicit false so the child exec op does not inherit `isNew: true`.
        ...(shouldResolveNewTopicKey ? { isNew: false } : {}),
        topicId: heteroTopicId,
      };
      const heteroResponseMeta = heteroData as SendMessageServerResponseMeta;
      const heteroMessageKey = messageMapKey(heteroContext);
      this.#get().moveQueuedMessages(currentContextKey, heteroMessageKey);
      getFileStoreState().moveChatComposerAttachments(currentContextKey, heteroMessageKey);
      // Legacy queue location: follow-ups enqueued behind an op still
      // registered under the pre-mint `_new` key.
      if (willCreateNewTopic)
        this.#get().moveQueuedMessages(
          messageMapKey({ ...operationContext, topicId: null }),
          heteroMessageKey,
        );
      this.#get().moveVoiceMessages(operationContext, heteroContext);
      const heteroMessages = heteroResponseMeta.__isPartialMessages
        ? mergePartialPersistedMessages(
            this.#get().messagesMap[heteroMessageKey] || [],
            heteroData.messages,
            [tempId, tempAssistantId],
          )
        : heteroData.messages;

      // Replace optimistic messages with persisted ones
      this.#get().replaceMessages(heteroMessages, {
        action: 'sendMessage/serverResponse',
        context: heteroContext,
      });

      // Handle new topic creation
      if (heteroData.isCreateNewTopic && heteroData.topicId) {
        if (heteroData.topics) {
          if (optimisticTopic && optimisticTopicActive) {
            resolveOptimisticTopic(heteroData.topicId, newTopicTitle);
          }
          const pageSize = systemStatusSelectors.topicPageSize(useGlobalStore.getState());
          this.#get().internal_updateTopics(topicListAgentId, {
            groupId: operationContext.groupId,
            items: heteroData.topics.items,
            pageSize,
            total: heteroData.topics.total,
          });
        } else if (!context.isolatedTopic) {
          resolveOptimisticTopic(heteroData.topicId, newTopicTitle);
          void Promise.resolve(this.#get().refreshTopic()).catch(console.error);
        }
        if (context.isolatedTopic) await onTopicCreated?.(heteroData.topicId);
        await leaveBlankConversationBucket(this.#get, operationContext, {
          isolated: context.isolatedTopic,
          topicId: heteroData.topicId,
        });
      }

      let directMentionThreadId: string | undefined;
      let heteroExecutionAssistantId = heteroData.assistantMessageId;
      let heteroExecutionContext = heteroContext;

      if (directMentionRoute) {
        if (!heteroTopicId) throw new Error('Direct mention requires a persisted topic');

        const task = await aiAgentService.createClientTaskThread({
          agentId,
          assistantMessage: { provider: heterogeneousProvider.type },
          instruction: message,
          parentMessageId: heteroData.assistantMessageId,
          title: toDirectMentionThreadTitle(message),
          topicId: heteroTopicId,
        });
        if (!task.assistantMessageId) {
          throw new Error('Direct mention thread is missing an assistant placeholder');
        }

        directMentionThreadId = task.threadId;
        heteroExecutionAssistantId = task.assistantMessageId;
        heteroExecutionContext = {
          ...heteroContext,
          agentId,
          scope: 'sub_agent',
          subAgentId: agentId,
          threadId: task.threadId,
        };
        this.#get().replaceMessages(task.threadMessages, { context: heteroExecutionContext });
        void this.#get().refreshThreads();
      }

      // No temp-message cleanup: the optimistic rows were created under the very
      // ids the server just persisted, so `replaceMessages` above already
      // reconciled them in place. Deleting them here would delete the real ones.

      // Complete sendMessage operation, start ACP execution as child operation
      this.#get().completeOperation(operationId);
      notifyMessagePersisted();

      if (abortController.signal.aborted) {
        return {
          assistantMessageId: heteroData.assistantMessageId,
          createdTopicId: heteroData.isCreateNewTopic ? heteroData.topicId : undefined,
          userMessageId: heteroData.userMessageId,
        };
      }

      // Topic title: hetero used to set only a sliced placeholder
      // title on new topics β€” upgrade it to the LLM summary via the shared hook
      // (reads the just-persisted conversation from the store). Fire-and-forget.
      void sendRunLifecycle
        .afterUserMessagePersisted({
          assistantMessageId: heteroData.assistantMessageId,
          context: heteroContext,
          isCreateNewTopic: heteroData.isCreateNewTopic,
          operationId,
          runId: operationId,
          runScope: sendRunScope,
          runtimeType,
          topicId: heteroData.topicId,
        })
        .catch(console.error);

      // Sidebar "running" spinner for hetero runs is driven off the persisted
      // `topic.status === 'running'` (written by the executor's writeTopicStatus,
      // and bucketed by resolveStatusBucket) plus the running
      // execHeterogeneousAgent operation below (operations-driven overlay).

      // Start heterogeneous agent execution
      const { operationId: heteroOpId } = this.#get().startOperation({
        context: heteroExecutionContext,
        label: 'Heterogeneous Agent Execution',
        metadata: { heteroAutoRetryAvailable: true, heterogeneousType: heterogeneousProvider.type },
        parentOperationId: operationId,
        type: 'execHeterogeneousAgent',
      });

      this.#get().associateMessageWithOperation(heteroData.assistantMessageId, heteroOpId);
      this.#get().associateMessageWithOperation(heteroExecutionAssistantId, heteroOpId);

      try {
        const { executeHeterogeneousAgent } =
          await import('../../transports/hetero/heterogeneousAgentExecutor');
        // Extract imageList from the persisted user message (chatUploadFileList
        // may already be cleared by this point, so we read from DB instead)
        const userMsg = heteroData.messages.find((m: any) => m.id === heteroData.userMessageId);
        const persistedImageList = userMsg?.imageList;
        const persistedAttachedFiles = userMsg ? collectHeteroAttachedFiles(userMsg) : [];
        const persistedMetadata = userMsg?.metadata as MessageMetadata | undefined;
        const effectiveContextSelections = contextSelections?.length
          ? contextSelections
          : persistedMetadata?.contextSelections;
        const effectivePageSelections = pageSelections?.length
          ? pageSelections
          : persistedMetadata?.pageSelections;

        // Read heterogeneous-agent session id from topic metadata for multi-turn
        // resume. `resolveHeteroResume` drops the sessionId when the saved cwd
        // doesn't match the current one, so CC doesn't emit
        // "No conversation found with session ID". Pre-binding native rows
        // retain the old cwd-only behavior, independent of the Labs flag.
        // Store lookup first (freshest optimistic edits), but fall back to the
        // server row resolved above β€” the paginated store misses deep-linked
        // older topics, and a miss here silently dropped `--resume` even when
        // the cwd resolution already used the topic's bound workingDirectory.
        const topic =
          (heteroContext.topicId
            ? topicSelectors.getTopicById(heteroContext.topicId)(this.#get())
            : undefined) ?? existingTopic;
        const providerBinding = heterogeneousProvider.authMode === 'api';
        const { cwdChanged, reason, resumeBindingKey, resumeSessionId } = resolveHeteroResume(
          topic?.metadata,
          workingDirectory,
          {
            currentBindingKey: providerBinding
              ? undefined
              : getNativeHeteroSessionBindingKey(heterogeneousProvider.type),
            providerBinding,
          },
        );
        if (cwdChanged) {
          toast.info(t('heteroAgent.resumeReset.cwdChanged', { ns: 'chat' }));
        } else if (reason === 'binding_changed') {
          toast.info(t('heteroAgent.resumeReset.bindingChanged', { ns: 'chat' }));
        }
        const effectiveHeterogeneousProvider = applyTopicModelToHeterogeneousProvider(
          heterogeneousProvider,
          resolveTopicHeteroPin(topic),
        );

        await executeHeterogeneousAgent(() => this.#get(), {
          assistantMessageId: heteroExecutionAssistantId,
          attachedFiles: persistedAttachedFiles.length ? persistedAttachedFiles : undefined,
          context: heteroExecutionContext,
          contextSelections: effectiveContextSelections,
          heterogeneousProvider: effectiveHeterogeneousProvider,
          imageList: persistedImageList?.length ? persistedImageList : undefined,
          message,
          operationId: heteroOpId,
          pageSelections: effectivePageSelections,
          resumeBindingKey,
          resumeSessionId,
          workingDirectory,
          workingDirectoryConfig,
          workspaceId: sendOriginWorkspaceId,
        });

        if (directMentionThreadId) {
          const threadMessages =
            this.#get().dbMessagesMap[messageMapKey(heteroExecutionContext)] || [];
          const metrics = aggregateSubagentMetrics(threadMessages);
          const resultContent =
            threadMessages.findLast((item) => item.role === 'assistant')?.content || '';
          await aiAgentService.updateClientTaskThreadStatus({
            completionReason: 'done',
            metadata: {
              totalMessages: threadMessages.length,
              totalTokens: metrics.totalTokens,
              totalToolCalls: metrics.toolCalls,
            },
            resultContent,
            threadId: directMentionThreadId,
          });
          // updateClientTaskThreadStatus owns the durable source-message
          // projection. Mirror that result into the persisted Topic bucket
          // without issuing a second write whose returned message list can race
          // and restore the original loading placeholder.
          this.#get().internal_dispatchMessage(
            {
              id: heteroData.assistantMessageId,
              type: 'updateMessage',
              value: { content: resultContent },
            },
            { context: heteroContext },
          );
          void this.#get().refreshThreads();
        }
      } catch (e) {
        console.error('[HeterogeneousAgent] Execution failed:', e);
        this.#get().failOperation(heteroOpId, {
          message: e instanceof Error ? e.message : 'Unknown error',
          type: 'HeterogeneousAgentError',
        });
      }

      return {
        assistantMessageId: heteroData.assistantMessageId,
        createdTopicId: heteroData.isCreateNewTopic ? heteroData.topicId : undefined,
        userMessageId: heteroData.userMessageId,
      };
    }

    // ── Gateway mode: skip sendMessageInServer, let execAgentTask handle everything ──
    if (runtimeType === 'gateway' && !directMentionRoute) {
      try {
        // Pass `sendMessage` as `parentOperationId`: executeGatewayAgent completes it once
        // phase-1 init finishes, so the send button doesn't flicker back during the
        // round-trip. Once the request is out the server persists the turn, so a Stop
        // keeps it in the chat instead of handing the text back to the composer.
        const result = await this.#get().executeGatewayAgent({
          // Ids and branch tail the optimistic rows render under; the server honours
          // them like sendMessageInServer, so the turn stays on the visible branch.
          clientIds: {
            assistantMessageId: tempAssistantId,
            topicId: optimisticTopic?.id,
            userMessageId: tempId,
            userMessageParentId: willCreateNewTopic ? undefined : parentId,
          },
          // Execution context: what the SERVER should act on. While creating,
          // the topic exists only client-side, so the server must see no
          // topicId (that is what makes execAgent create it β€” under
          // `clientIds.topicId`). The message context below keeps the minted id
          // so streamed messages land in the bucket already on screen.
          context: willCreateNewTopic
            ? { ...operationContext, topicId: undefined }
            : operationContext,
          messageContext: operationContext,
          fileIds: fileIdList,
          message,
          // The server persists the user row on this path, so the steer mark
          // of a directly-steered send ("send now") must travel with the request.
          metadata: (metadata as Pick<MessageMetadata, 'steer'> | undefined)?.steer
            ? { ...requestMetadata, steer: true }
            : requestMetadata,
          onMessageAccepted: notifyMessageAccepted,
          onStartRequestSent: () =>
            this.#get().updateOperationMetadata(operationId, { inputEditorTempState: null }),
          onTopicCreated: context.isolatedTopic ? onTopicCreated : undefined,
          parentOperationId: operationId,
          clientOperations,
          replacesOperationId: replaceableGatewayOperationId,
          optimisticTopic,
          // An isolated handoff topic has no optimistic row to carry its cwd.
          newTopicMetadata: sourceTopic && !optimisticTopic ? workingDirectoryMetadata : undefined,
          ...newTopicProject,
          // Forward @-mentioned tool ids so the server runtime enables them for
          // this run β€” the gateway/server path otherwise never sees the mention
          // selection (only the client runtime did). Omit when empty.
          selectedToolIds:
            selectedTools.length > 0 ? selectedTools.map((tool) => tool.identifier) : undefined,
          // Forward both library and filesystem skill selections to the server.
          selectedSkillIds: selectedSkillIds.length ? selectedSkillIds : undefined,
          // Forward @-mentioned agents so the server supervisor can delegate to
          // them (multi-mention). Mirrors the client runtime's `initialContext`
          // injection: the server enables the callAgent tool and injects the
          // mentioned-agents delegation context so the supervisor calls them.
          // Omit when empty (single-mention executes the target directly and does
          // not need supervisor delegation context). Non-group only β€” group @member mentions are handled by
          // the group orchestration path, not agent-management delegation.
          mentionedAgents: hasMentionedAgents ? mentionedAgents : undefined,
          // Pass temp message IDs so the UI doesn't show a blank loading
          // state while waiting for the first step_start event to replace
          // messages with the server's real IDs.
          tempMessageIds: [tempAssistantId],
          // The server persists the user row here: build it from the metadata the
          // optimistic row shows, the same object `sendMessageInServer` persists.
          userMessage: toComposerUserMessage({ editorData, metadata: userMessageMetadata }),
        });
        const cancelledAfterPersistence = abortController.signal.aborted;

        // Record created threadId in operation metadata
        if (result.createdThreadId) {
          this.#syncCreatedThread(operationId, result.createdThreadId, context.sourceMessageId);
        }

        // Topic title: gateway-created topics had no LLM-summarized
        // title. executeGatewayAgent has already replaced messages + switched to
        // the new topic, so the shared hook reads the persisted conversation from
        // the store and titles it. Fire-and-forget.
        if (result.topicId) {
          // executeGatewayAgent resolved the optimistic topic row via
          // internal_replaceTopicId; nothing to release here β€” the sidebar
          // spinner is operations-driven plus the persisted
          // `status === 'running'`.
          if (optimisticTopic && optimisticTopicActive) {
            optimisticTopicActive = false;
          }
          if (!cancelledAfterPersistence) {
            void sendRunLifecycle
              .afterUserMessagePersisted({
                assistantMessageId: result.assistantMessageId,
                context: {
                  ...operationContext,
                  // The turn was persisted inside the thread the server just
                  // created, so the lifecycle must read that bucket β€” not the
                  // topic's main spine β€” when it loads the conversation.
                  ...(result.createdThreadId && {
                    isNew: false,
                    threadId: result.createdThreadId,
                  }),
                  topicId: result.topicId,
                },
                isCreateNewTopic: willCreateNewTopic,
                operationId,
                runId: operationId,
                runScope: sendRunScope,
                runtimeType,
                topicId: result.topicId,
              })
              .catch(console.error);
          }
        } else {
          rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');
        }

        notifyMessagePersisted();

        return {
          assistantMessageId: result.assistantMessageId,
          createdThreadId: result.createdThreadId,
          createdTopicId: willCreateNewTopic ? result.topicId : undefined,
          userMessageId: result.userMessageId,
        };
      } catch (e) {
        // A Stop keeps 'cancelled'; a refused turn gets its text back unless typed over.
        const op = this.#get().operations[operationId];
        if (op?.status === 'cancelled') {
          if (!targetInputEditor?.getMarkdownContent?.().trim()) restoreComposerAfterFailedSend(e);
          cleanupTempMessages({
            preserveOptimisticUser: Boolean(optimisticUserMessageId && !hasNotifiedMessageAccepted),
          });
          detachUnacceptedCallerAbort();
          rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');
          restoreUnacceptedVoiceMessageContext();
          return;
        }

        console.error('[Gateway] Failed to start server-side agent:', e);
        this.#get().failOperation(operationId, {
          message: e instanceof Error ? e.message : 'Unknown error',
          type: 'GatewayError',
        });
        restoreComposerAfterFailedSend(e);
        cleanupTempMessages({
          preserveOptimisticUser: Boolean(optimisticUserMessageId && !hasNotifiedMessageAccepted),
        });
        detachUnacceptedCallerAbort();
        rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');
        restoreUnacceptedVoiceMessageContext();
        return;
      }
    }

    // ── Client mode: send via server API then run agent locally ──
    let data: SendMessageServerResponse | undefined;
    const isCreatedTopicResponse = (response?: SendMessageServerResponse) =>
      Boolean(
        response && (response.isCreateNewTopic || (willCreateNewTopic && !!response.topicId)),
      );

    try {
      throwIfSendAborted(signal);
      const { model, provider } = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());

      const topicId = operationContext.topicId;

      // Persist selected skill/tool context into user message content so it survives across turns.
      // Deduplicate: skip skills/tools already @mentioned in earlier messages (via editorData).
      const previouslyMentionedSkills = new Set<string>();
      const previouslyMentionedTools = new Set<string>();

      for (const m of messages) {
        if (m.role !== 'user') continue;
        for (const s of parseSelectedSkillsFromEditorData(m.editorData ?? undefined)) {
          previouslyMentionedSkills.add(s.identifier);
        }
        for (const t of parseSelectedToolsFromEditorData(m.editorData ?? undefined)) {
          previouslyMentionedTools.add(t.identifier);
        }
      }
      const dedupedSkills = enrichedSelectedSkills.filter(
        (s) => !previouslyMentionedSkills.has(s.identifier),
      );
      const dedupedTools = enrichedSelectedTools.filter(
        (t) => !previouslyMentionedTools.has(t.identifier),
      );

      const skillContext = formatSelectedSkillsContext(dedupedSkills);
      const toolContext = formatSelectedToolsContext(dedupedTools);
      const contextSuffix = [skillContext, toolContext].filter(Boolean).join('\n');
      const persistedContent = contextSuffix ? `${message}\n\n${contextSuffix}` : message;
      data = await aiChatService.sendMessageInServer(
        {
          newUserMessage: {
            content: persistedContent,
            editorData,
            files: fileIdList,
            id: tempId,
            metadata: userMessageMetadata,
            contextSelections,
            pageSelections,
            parentId,
          },
          preloadMessages: undefined,
          // While creating, the topic exists only client-side β€” the server
          // sees `newTopic` (with the minted id) and no topicId.
          topicId: willCreateNewTopic ? undefined : (topicId ?? undefined),
          topicFilter: this.#getTopicFilter(
            topicListAgentId,
            operationContext.groupId ?? undefined,
          ),
          topicPageSize: systemStatusSelectors.topicPageSize(useGlobalStore.getState()),
          threadId: operationContext.threadId ?? undefined,
          // Support creating new thread along with message
          newThread: newThread
            ? {
                sourceMessageId: newThread.sourceMessageId,
                type: newThread.type,
              }
            : undefined,
          newTopic: willCreateNewTopic
            ? {
                ...newTopicModelSnapshot,
                // Same id the optimistic sidebar row already uses.
                id: optimisticTopic?.id,
                // Born bound to the directory this run resolved β€” the client
                // runtime creates the topic here, so nothing downstream would
                // ever write the cwd back (the server-side binding only exists
                // on the gateway path).
                metadata: optimisticTopicMetadata,
                projectId: stagedProjectId,
                topicMessageIds: forceNewTopicFromExisting ? [] : messages.map((m) => m.id),
                title: newTopicTitle,
              }
            : undefined,
          agentId: operationContext.agentId,
          // Pass groupId for group chat scenarios
          groupId: operationContext.groupId ?? undefined,
          newAssistantMessage: {
            agentId: directMentionRoute ? agentId : undefined,
            id: tempAssistantId,
            // Pass isSupervisor metadata for group orchestration
            metadata: operationContext.isSupervisor
              ? { isSupervisor: true, orchestrationRole: 'supervisor' as const }
              : undefined,
            model,
            provider: provider!,
          },
        },
        abortController,
      );
      notifyMessageAccepted();
      const responseMeta = data as SendMessageServerResponseMeta;
      // Use created topicId/threadId if available, otherwise use original from context
      let finalTopicId = data.topicId ?? operationContext.topicId;
      const finalThreadId = data.createdThreadId ?? operationContext.threadId;
      const isCreateNewTopic = isCreatedTopicResponse(data);

      // refresh the total data
      if (data?.topics) {
        finalTopicId = data.topicId;

        // Skip writing the returned topic list into the main chat's topicDataMap
        // when the caller owns an isolated topic scope (e.g. Task Manager panel).
        // Otherwise the newly created isolated-trigger topic would flash in the
        // main sidebar until the next SWR revalidation filters it out.
        if (!context.isolatedTopic) {
          if (optimisticTopic && optimisticTopicActive && data.topicId) {
            resolveOptimisticTopic(data.topicId, newTopicTitle);
          }
          const pageSize = systemStatusSelectors.topicPageSize(useGlobalStore.getState());
          this.#get().internal_updateTopics(topicListAgentId, {
            groupId: operationContext.groupId,
            items: data.topics.items,
            pageSize,
            total: data.topics.total,
          });

          // Record the created topicId in metadata (not context)
          this.#get().updateOperationMetadata(operationId, { createdTopicId: data.topicId });
        }
      } else if (isCreateNewTopic && data.topicId && !context.isolatedTopic) {
        resolveOptimisticTopic(data.topicId, newTopicTitle);
        this.#get().updateOperationMetadata(operationId, { createdTopicId: data.topicId });
        void Promise.resolve(this.#get().refreshTopic()).catch(console.error);
      } else if (operationContext.topicId) {
        // Optimistically bump the sort key (`sortUpdatedAt`, the sidebar's activity-time
        // sort/group key) so the topic jumps to the top immediately, before the SWR
        // refetch returns the server's fresh `topicActivityAt`. Bumping `updatedAt` here
        // would no longer reorder anything β€” the sidebar sorts by `sortUpdatedAt`.
        this.#get().internal_dispatchTopic({
          type: 'updateTopic',
          id: operationContext.topicId,
          value: { sortUpdatedAt: Date.now() },
        });
      }

      // Record created threadId in operation metadata
      if (data.createdThreadId) {
        this.#syncCreatedThread(operationId, data.createdThreadId, context.sourceMessageId);
      }

      // Create final context with updated topicId/threadId from server response
      const finalContext = {
        ...operationContext,
        isNew: data.createdThreadId || isCreateNewTopic ? false : operationContext.isNew,
        threadId: finalThreadId,
        topicId: finalTopicId,
      };
      const finalMessageKey = messageMapKey(finalContext);
      this.#get().moveQueuedMessages(currentContextKey, finalMessageKey);
      getFileStoreState().moveChatComposerAttachments(currentContextKey, finalMessageKey);
      // Legacy queue location: follow-ups enqueued behind an op still
      // registered under the pre-mint `_new` key.
      if (willCreateNewTopic)
        this.#get().moveQueuedMessages(
          messageMapKey({ ...operationContext, topicId: null }),
          finalMessageKey,
        );
      this.#get().moveVoiceMessages(operationContext, finalContext);
      data = {
        ...data,
        messages: resolveSendResponseMessages({
          currentMessages: this.#get().messagesMap[finalMessageKey] || [],
          isPartial: !!responseMeta.__isPartialMessages,
          messages: data.messages,
          replacedMessageIds: [tempId, tempAssistantId],
          userMessageId: data.userMessageId,
          userMessageMetadata,
        }),
      };

      // The send response skips Work summaries; keep the ones earlier replies already carry.
      this.#get().replaceMessages(data.messages, {
        context: finalContext,
        action: 'sendMessage/serverResponse',
        preserveWorks: true,
      });

      if (isCreateNewTopic && data.topicId) {
        // Notify the isolated caller immediately so its UI re-subscribes to
        // the new topic key and picks up the streaming AI response.
        if (context.isolatedTopic) await onTopicCreated?.(data.topicId);
        await leaveBlankConversationBucket(this.#get, operationContext, {
          isolated: context.isolatedTopic,
          topicId: data.topicId,
        });
      }
    } catch (e) {
      console.error(e);
      rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');
      // Fail operation on error
      if (this.#get().operations[operationId]?.status !== 'cancelled') {
        this.#get().failOperation(operationId, {
          type: e instanceof Error ? e.name : 'unknown_error',
          message: e instanceof Error ? e.message : 'Unknown error',
        });
      }

      restoreComposerAfterFailedSend(e);
    } finally {
      // Roll the optimistic pair back only when the send did not land (cancel or
      // failure). On success there is nothing to clean up: the rows were created
      // under the ids the server persisted, so `replaceMessages` reconciled them
      // in place β€” and for a brand-new topic `switchTopic({ clearNewKey: true })`
      // drops the now-empty `_new` bucket anyway.
      if (!data)
        cleanupTempMessages({
          preserveOptimisticUser: Boolean(optimisticUserMessageId && !hasNotifiedMessageAccepted),
        });
    }

    if (!data) {
      detachUnacceptedCallerAbort();
      rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');
      restoreUnacceptedVoiceMessageContext();
      return;
    }

    rollbackOptimisticTopic('sendMessage/rollbackUnresolvedOptimisticTopic');

    if (abortController.signal.aborted) {
      this.#get().completeOperation(operationId);
      notifyMessagePersisted();

      return {
        assistantMessageId: data.assistantMessageId,
        createdThreadId: data.createdThreadId,
        createdTopicId: isCreatedTopicResponse(data) ? data.topicId : undefined,
        userMessageId: data.userMessageId,
      };
    }
    // Topic title auto-generation, now via the shared `afterUserMessagePersisted`
    // hook. The client passes its freshly-created `data.messages`
    // (not yet in the store under the real topicId); gateway/hetero call the same
    // hook from their branches and let it read the persisted conversation.
    void sendRunLifecycle
      .afterUserMessagePersisted({
        assistantMessageId: data.assistantMessageId,
        context: operationContext,
        isCreateNewTopic: isCreatedTopicResponse(data),
        messages: data.messages,
        operationId,
        runId: operationId,
        runScope: sendRunScope,
        runtimeType,
        topicId: data.topicId,
      })
      .catch(console.error);

    const execContext = {
      ...operationContext,
      // The persisted topic/thread is now the identity of this conversation.
      // Clear the draft marker before creating the child runtime operation so
      // Stop from the re-rendered ConversationProvider matches it.
      isNew: data.createdThreadId || isCreatedTopicResponse(data) ? false : operationContext.isNew,
      topicId: data.topicId ?? operationContext.topicId,
      threadId: data.createdThreadId ?? operationContext.threadId,
    };

    // ── Auto-dismiss pending tool interventions ──
    // Uses direct dispatch (updateMessage) instead of optimisticUpdatePlugin because
    // agent runtime checks pluginIntervention.status, not plugin.intervention.status.
    {
      const msgs = displayMessageSelectors.getDisplayMessagesByKey(messageMapKey(execContext))(
        this.#get(),
      );

      const pendingToolMsgIds = msgs.flatMap((m) => {
        const ids: string[] = [];
        if (m.role === 'tool' && m.pluginIntervention?.status === 'pending') ids.push(m.id);

        const childIds =
          m.children?.flatMap((child) =>
            (child.tools ?? [])
              .filter((t) => t.intervention?.status === 'pending' && t.result_msg_id)
              .map((t) => t.result_msg_id!),
          ) ?? [];

        return [...ids, ...childIds];
      });

      for (const msgId of pendingToolMsgIds) {
        this.#get().internal_dispatchMessage({
          id: msgId,
          type: 'updateMessage',
          value: {
            pluginIntervention: { status: 'aborted' },
            content: 'User bypassed this interaction by sending a message directly.',
          },
        });
        void messageService.updateMessagePlugin(
          msgId,
          { intervention: { status: 'aborted' } },
          {
            agentId: execContext.agentId,
            groupId: execContext.groupId,
            threadId: execContext.threadId,
            topicId: execContext.topicId,
          },
        );
      }
    }

    // ── AI execution (client mode) ──
    {
      let sendOperationHandedOff = false;
      const handoffSendOperation = () => {
        if (sendOperationHandedOff) return;

        sendOperationHandedOff = true;
        // Keep the send operation running until the child runtime is ready to start. This makes
        // `_new` β†’ persisted-topic migration one continuous queue barrier for follow-up turns.
        this.#get().completeOperation(operationId);
        notifyMessagePersisted();
      };

      try {
        if (directMentionRoute) {
          const directMentionRun = executeDirectMention(
            {
              context: execContext,
              instruction: message,
              parentOperationId: operationId,
              runtimeType: runtimeType === 'gateway' ? 'gateway' : 'client',
              sourceMessageId: data.assistantMessageId,
              targetAgentId: agentId,
            },
            this.#get,
          );
          handoffSendOperation();
          await directMentionRun;
        } else {
          const displayMessages = displayMessageSelectors
            .getDisplayMessagesByKey(messageMapKey(execContext))(this.#get())
            .filter((item) => !isLocalOnlyMessage(item));

          // When agents are @mentioned, inject a slim callAgent-only manifest
          // so the AI can delegate directly without activating the full agent-management tool
          const injectedManifests = hasMentionedAgents ? [createCallAgentManifest()] : undefined;
          const activeTopicDocumentInitialContext =
            await resolveActiveTopicDocumentInitialContext(execContext);

          const hasInitialContext = hasMentionedAgents || !!injectedManifests;

          // Note: selectedSkills and selectedTools are NOT passed here β€” they are
          // persisted into the user message content above so they survive across
          // turns without re-injection.
          const agentRuntimeInitialContext = hasInitialContext
            ? {
                initialContext: {
                  // Only inject mentionedAgents in non-group context to avoid
                  // group @member mentions (including ALL_MEMBERS) leaking into agent-management
                  ...(hasMentionedAgents ? { mentionedAgents } : undefined),
                  ...(injectedManifests ? { injectedManifests } : undefined),
                },
                phase: 'init' as const,
              }
            : undefined;
          const mergedAgentRuntimeInitialContext = mergeAgentRuntimeInitialContexts(
            activeTopicDocumentInitialContext,
            agentRuntimeInitialContext,
          );

          const clientRun = executeClientAgent({
            context: execContext,
            initialContext: mergedAgentRuntimeInitialContext,
            metadata: requestMetadata,
            messages: displayMessages,
            parentMessageId: data.assistantMessageId,
            parentMessageType: 'assistant',
            parentOperationId: operationId,
            inPortalThread: !!data.createdThreadId,
            skipCreateFirstMessage: true,
            userMessageId: data.userMessageId,
          });
          handoffSendOperation();
          await clientRun;
        }

        const userFiles = dbMessageSelectors
          .dbUserFiles(this.#get())
          .map((f) => f?.id)
          .filter(Boolean) as string[];

        if (userFiles.length > 0) {
          await getAgentStoreState().addFilesToAgent(userFiles, false);
        }
      } catch (e) {
        console.error(e);
      } finally {
        handoffSendOperation();
      }
    }

    // Return result for callers who need message IDs
    return {
      assistantMessageId: data.assistantMessageId,
      createdThreadId: data.createdThreadId,
      createdTopicId: isCreatedTopicResponse(data) ? data.topicId : undefined,
      userMessageId: data.userMessageId,
    };
  };

  /**
   * Execute context compression for /compact command.
   *
   * @returns Whether the history was replaced by a summary.
   */
  executeCompression = async (
    context: Record<string, any>,
    parentOperationId: string,
    options?: ContextCompressionOptions,
  ): Promise<boolean> =>
    executeContextCompression({ ...options, context, parentOperationId }, this.#get);
}

export type ConversationLifecycleAction = Pick<
  ConversationLifecycleActionImpl,
  keyof ConversationLifecycleActionImpl
>;