Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

28.9 KB
Raw Blame
import i18n from "i18next";
import { isRemoteSession, sessionAllows } from "../../lib/remote-session-safety";
import type {
  UiMessage,
} from "@pi-desktop/shared";
import { isRenderableAttachment } from "@pi-desktop/shared";
import { api } from "../../lib/api";
import { resolveComposerSmartStop } from "../../lib/composer-smart-stop";
import {
  clearSessionPermissions,
  removePermission,
  sessionPermissions,
} from "../../lib/pending-permissions";
import {
  mergeLiveSessionMessages,
} from "../../lib/session-transcript";
import { optimisticUserMessage } from "../../lib/session-transcript";
import { withReviewChangeState } from "../../lib/workspace-review";
import { settleStoppedAssistantMetrics } from "../../lib/context-usage";
import type { AppState } from "../app-state";
import type { SessionRuntime } from "../runtime/session-runtime";
import { prepareTranscriptAction } from "../runtime/transcript-action";
import type { StoreAccess } from "./types";

export type TranscriptSliceDependencies = StoreAccess & {
  runtime: SessionRuntime;
  promptAttachmentsFromMessage: (
    attachments: UiMessage["attachments"],
  ) => NonNullable<Parameters<typeof api.prompt>[0]["attachments"]>;
  viewingSessionIdForPrompt: (
    state: Pick<AppState, "page" | "activeSessionId">,
    sessionId: string,
  ) => string | null;
  flushPendingSessionConfiguration: (sessionId: string) => Promise<void>;
};

export function createTranscriptSlice({
  get,
  set,
  runtime,
  promptAttachmentsFromMessage,
  viewingSessionIdForPrompt,
  flushPendingSessionConfiguration,
}: TranscriptSliceDependencies): Pick<
  AppState,
  | "compactContext"
  | "retryAssistantMessage"
  | "editUserMessage"
  | "prepareUserMessageEdit"
  | "retryLastPrompt"
  | "clearError"
  | "activateMessageRevision"
  | "deleteMessage"
  | "rollbackWorkspaceChange"
  | "abort"
> {
  // Keep each delete's read/optimistic update/Host result together. Main's
  // mutation lock alone cannot prevent a second renderer read of old history.
  const pendingMessageDeletes = new Map<string, Promise<void>>();
  const canEdit = () => {
    const state = get();
    return sessionAllows(state.sessions.find((session) => session.id === state.activeSessionId)
      ?? { id: state.activeSessionId ?? "" }, "canEditMessages");
  };
  return {
    compactContext: async () => {
      const state = get();
      const sessionId = state.activeSessionId;
      if (!sessionId || state.isRunning) return;
      set((current) => ({
        isRunning: true,
        runningSessions: {
          ...current.runningSessions,
          [sessionId]: true,
        },
      }));
      try {
        await api.compact({ sessionId });
      } catch (error) {
        set((current) => ({
          isRunning:
            current.activeSessionId === sessionId ? false : current.isRunning,
          runningSessions: {
            ...current.runningSessions,
            [sessionId]: false,
          },
        }));
        if ((error as { code?: string })?.code !== "CONTEXT_COMPACTION_FAILED") {
          get().showToast(
            error instanceof Error
              ? error.message
              : i18n.t("contextCompaction.failed"),
            { variant: "error" },
          );
        }
      }
    },

    retryAssistantMessage: async (messageId) => {
      if (!canEdit()) return;
      const prepared = await prepareTranscriptAction({ get, set }, runtime, messageId);
      const state = get();
      if (!prepared || state.activeSessionId !== prepared.activeSessionId || state.isRunning) return;
      const index = state.messages.findIndex((message) => message.id === messageId);
      if (index < 0) return;
      const target = state.messages[index];
      if (target.role !== "assistant") return;
      let userIndex = -1;
      for (let i = index - 1; i >= 0; i -= 1) {
        const candidate = state.messages[i];
        if (
          candidate.role === "user" &&
          (candidate.content.trim() || candidate.attachments?.length)
        ) {
          userIndex = i;
          break;
        }
      }
      if (userIndex < 0) return;
      const root = state.messages[userIndex];
      await get().editUserMessage(root.id, root.content, root.attachments);
    },

    prepareUserMessageEdit: async (messageId, signal) => {
      if (!canEdit()) return null;
      const prepared = await prepareTranscriptAction({ get, set }, runtime, messageId, signal);
      const state = get();
      if (!prepared || state.activeSessionId !== prepared.activeSessionId || state.isRunning) return null;
      const message = state.messages.find((candidate) => candidate.id === messageId);
      return message?.role === "user" && !message.sessionMessage ? message : null;
    },

    editUserMessage: async (messageId, content, attachments) => {
      if (!canEdit()) return false;
      const prepared = await prepareTranscriptAction({ get, set }, runtime, messageId);
      const state = get();
      if (!prepared || state.activeSessionId !== prepared.activeSessionId || state.isRunning) return false;
      const sessionId = state.activeSessionId;
      if (!sessionId) return false;
      if (state.pendingPlans[sessionId]?.status === "pending") return false;
      const prompt = content.trim();
      const userIndex = state.messages.findIndex(
        (message) => message.id === messageId,
      );
      if (userIndex < 0 || state.messages[userIndex].role !== "user") return false;
      if (
        !prompt &&
        !(attachments ?? state.messages[userIndex].attachments)?.length
      ) {
        return false;
      }
      const promptAttachments = promptAttachmentsFromMessage(
        attachments ?? state.messages[userIndex].attachments,
      );
      const kept = state.messages.slice(0, userIndex);
      const truncateFromMessageId = state.messages[userIndex].id;
      const optimisticMessage = optimisticUserMessage(
        crypto.randomUUID(),
        prompt,
        (attachments ?? state.messages[userIndex].attachments ?? [])
          // A session reference re-resolves from its link text on send; it is
          // not an optimistic file reference.
          .filter(isRenderableAttachment)
          .map((attachment) => ({
            path: attachment.ref,
            name: attachment.name,
            kind: attachment.kind,
            mimeType: attachment.mimeType,
          })),
      );

      set((current) => ({
        messages: [...kept, optimisticMessage],
        isRunning: true,
        error: null,
        errorCode: null,
        errorRetriable: null,
        runningSessions: { ...current.runningSessions, [sessionId]: true },
        latestTurnResults: withoutRecordKey(current.latestTurnResults, sessionId),
        sessionOutcomes: withoutRecordKey(current.sessionOutcomes, sessionId),
      }));

      try {
        await api.prompt({
          sessionId,
          content: prompt,
          messageId: optimisticMessage.id,
          viewingSessionId: viewingSessionIdForPrompt(get(), sessionId),
          attachments: promptAttachments,
          truncateFromMessageId,
        });
        return true;
      } catch (error) {
        try {
          const detail = await api.getSession(sessionId);
          set((current) => ({
            messages:
              current.activeSessionId === sessionId
                ? detail.session?.messages ?? kept
                : current.messages,
            isRunning:
              current.activeSessionId === sessionId ? false : current.isRunning,
            runningSessions: { ...current.runningSessions, [sessionId]: false },
            latestTurnResults: {
              ...current.latestTurnResults,
              [sessionId]: {
                status: "failed",
                turnId: `${sessionId}:${Date.now()}`,
                finishedAt: Date.now(),
                errorCode: (error as { code?: string })?.code,
              },
            },
            sessionOutcomes: { ...current.sessionOutcomes, [sessionId]: "failed" },
            error: error instanceof Error ? error.message : String(error),
            errorCode: (error as { code?: string })?.code ?? null,
          }));
        } catch {
          set((current) => ({
            isRunning:
              current.activeSessionId === sessionId ? false : current.isRunning,
            runningSessions: { ...current.runningSessions, [sessionId]: false },
            latestTurnResults: {
              ...current.latestTurnResults,
              [sessionId]: {
                status: "failed",
                turnId: `${sessionId}:${Date.now()}`,
                finishedAt: Date.now(),
                errorCode: (error as { code?: string })?.code,
              },
            },
            sessionOutcomes: { ...current.sessionOutcomes, [sessionId]: "failed" },
            error: error instanceof Error ? error.message : String(error),
            errorCode: (error as { code?: string })?.code ?? null,
          }));
        }
        return false;
      }
    },

    retryLastPrompt: async () => {
      if (!canEdit()) return;
      const state = get();
      if (state.isRunning) return;
      const sessionId = state.activeSessionId;
      if (!sessionId) return;
      if (state.pendingPlans[sessionId]?.status === "pending") return;
      let userIndex = -1;
      for (let i = state.messages.length - 1; i >= 0; i -= 1) {
        const candidate = state.messages[i];
        if (
          candidate.role === "user" &&
          (candidate.content.trim() || candidate.attachments?.length)
        ) {
          userIndex = i;
          break;
        }
      }
      if (userIndex < 0) return;
      const prompt = state.messages[userIndex].content;
      const promptAttachments = promptAttachmentsFromMessage(
        state.messages[userIndex].attachments,
      );
      const kept = state.messages.slice(0, userIndex);
      const truncateFromMessageId = state.messages[userIndex].id;
      set((current) => ({
        messages: kept,
        isRunning: true,
        error: null,
        errorCode: null,
        errorRetriable: null,
        runningSessions: { ...current.runningSessions, [sessionId]: true },
        latestTurnResults: withoutRecordKey(current.latestTurnResults, sessionId),
        sessionOutcomes: withoutRecordKey(current.sessionOutcomes, sessionId),
      }));
      try {
        await api.prompt({
          sessionId,
          content: prompt,
          viewingSessionId: viewingSessionIdForPrompt(get(), sessionId),
          attachments: promptAttachments,
          truncateFromMessageId,
        });
      } catch (error) {
        set((current) => ({
          isRunning:
            current.activeSessionId === sessionId ? false : current.isRunning,
          runningSessions: { ...current.runningSessions, [sessionId]: false },
          latestTurnResults: {
            ...current.latestTurnResults,
            [sessionId]: {
              status: "failed",
              turnId: `${sessionId}:${Date.now()}`,
              finishedAt: Date.now(),
              errorCode: (error as { code?: string })?.code,
            },
          },
          sessionOutcomes: { ...current.sessionOutcomes, [sessionId]: "failed" },
          error: error instanceof Error ? error.message : String(error),
          errorCode: (error as { code?: string })?.code ?? null,
          errorRetriable: false,
        }));
      }
    },

    clearError: () => set({ error: null, errorCode: null, errorRetriable: null }),

    activateMessageRevision: async (rootUserId, revisionIndex) => {
      if (!canEdit()) return;
      let state = get();
      if (state.isRunning) return;
      const sessionId = state.activeSessionId;
      if (!sessionId) return;
      if (state.sessionHistory[sessionId]?.hasMoreBefore) {
        const fullMessages = await runtime.loadFullSessionMessages(sessionId);
        if (!fullMessages || get().activeSessionId !== sessionId) return;
        set((current) =>
          current.activeSessionId === sessionId && !current.isRunning
            ? {
                messages: fullMessages,
                sessionHistory: {
                  ...current.sessionHistory,
                  [sessionId]: { messageStart: 0, hasMoreBefore: false },
                },
              }
            : {},
        );
        state = get();
      }
      const rootIndex = state.messages.findIndex((message) => message.id === rootUserId);
      if (rootIndex < 0) return;
      const root = state.messages[rootIndex];
      const revisionFamilyId = root.revisionRootId || root.id;
      try {
        const result = await api.activateSessionRevision({
          sessionId,
          rootUserId: revisionFamilyId,
          revisionIndex,
          requireCanonicalPrefix: true,
        });
        set((current) => ({
          messages:
            current.activeSessionId === sessionId && !current.isRunning
              ? result.messages
              : current.messages,
          sessionHistory:
            current.activeSessionId === sessionId && !current.isRunning
              ? {
                  ...current.sessionHistory,
                  [sessionId]: { messageStart: 0, hasMoreBefore: false },
                }
              : current.sessionHistory,
          error: null,
          errorCode: null,
        }));
      } catch (error) {
        set({
          error: error instanceof Error ? error.message : String(error),
          errorCode: (error as { code?: string })?.code ?? null,
        });
      }
    },

    deleteMessage: async (messageId) => {
      if (!canEdit()) return;
      const sessionId = get().activeSessionId;
      if (!sessionId || get().isRunning) return;
      const previousDelete = pendingMessageDeletes.get(sessionId);
      let releaseDelete!: () => void;
      const completion = new Promise<void>((resolve) => { releaseDelete = resolve; });
      pendingMessageDeletes.set(sessionId, completion);
      try {
        await previousDelete;
        if (get().activeSessionId !== sessionId || get().isRunning || !canEdit()) return;
        const fullMessages = await runtime.loadFullSessionMessages(sessionId);
        // Re-read the store after the reload: writes that landed during the
        // await (an aborted turn's final message_end, a late tool_end) exist
        // only here, so merging the pre-await snapshot would erase them
        // (#1614) — the same post-await read abort() below relies on. A turn
        // that started during the reload also bails: no rewrite under a live
        // stream.
        if (
          !fullMessages ||
          get().activeSessionId !== sessionId ||
          get().isRunning
        ) {
          return;
        }
        const merged = mergeLiveSessionMessages(fullMessages, get().messages);
        set((current) =>
          current.activeSessionId === sessionId
            ? {
                messages: merged,
                sessionHistory: {
                  ...current.sessionHistory,
                  [sessionId]: { messageStart: 0, hasMoreBefore: false },
                },
              }
            : {},
        );
        if (!get().messages.some((message) => message.id === messageId)) return;
        const fullWindow = { messageStart: 0, hasMoreBefore: false };
        runtime.cacheSessionTranscript(sessionId, get().messages, fullWindow);
        set({ error: null, errorCode: null });
        try {
          const result = await api.deleteSessionMessage({ sessionId, messageId });
          if (!result.deleted) return;
          // Keep the projection intact until Host confirms the mutation. Late
          // terminal events can replace provisional IDs while this RPC waits;
          // restoring an earlier snapshot would resurrect those replaced rows.
          const current = get();
          const live = current.activeSessionId === sessionId
            ? current.messages
            : runtime.sessionTranscriptCache.get(sessionId) ?? current.retainedTranscripts[sessionId] ?? [];
          const index = live.findIndex((message) => message.id === messageId);
          if (index < 0) return;
          let end = index + 1;
          if (live[index].role === "user") {
            while (end < live.length && live[end].role !== "user") end += 1;
          }
          const next = [...live.slice(0, index), ...live.slice(end)];
          runtime.cacheSessionTranscript(sessionId, next, fullWindow);
          set((state) => ({
            messages: state.activeSessionId === sessionId ? next : state.messages,
            retainedTranscripts: state.retainedTranscripts[sessionId]
              ? { ...state.retainedTranscripts, [sessionId]: next }
              : state.retainedTranscripts,
          }));
        } catch (error) {
          set({
            error: error instanceof Error ? error.message : String(error),
            errorCode: (error as { code?: string })?.code ?? null,
          });
        }
      } finally {
        releaseDelete();
        if (pendingMessageDeletes.get(sessionId) === completion) {
          pendingMessageDeletes.delete(sessionId);
        }
      }
    },

    rollbackWorkspaceChange: async (messageId, snapshotId) => {
      if (!canEdit()) return null;
      const state = get();
      const sessionId = state.activeSessionId;
      if (!sessionId || state.isRunning) return null;
      try {
        const result = await api.workspaceReviewRollback({ sessionId, snapshotId });
        if (result.status === "rolledBack" || result.status === "alreadyRolledBack") {
          set((current) =>
            current.activeSessionId === sessionId
              ? {
                  messages: current.messages.map((message) =>
                    message.id === messageId
                      ? withReviewChangeState(message, "rolledBack")
                      : message,
                  ),
                }
              : {},
          );
        } else if (result.status === "conflict") {
          get().showToast(i18n.t("panel.review.rollbackConflict"), {
            variant: "warning",
          });
        } else if (result.status === "unavailable") {
          get().showToast(i18n.t("panel.review.rollbackUnavailable"), {
            variant: "warning",
          });
        }
        return result;
      } catch (error) {
        get().showToast(i18n.t("panel.review.rollbackError"), {
          variant: "error",
        });
        set({
          error: error instanceof Error ? error.message : String(error),
          errorCode: (error as { code?: string })?.code ?? null,
        });
        return null;
      }
    },

    abort: async () => {
      const stateBeforeAbort = get();
      const sessionId = stateBeforeAbort.activeSessionId;
      if (!sessionId) return;
      const target = stateBeforeAbort.sessions.find((session) => session.id === sessionId);
      if (!sessionAllows(target, "canStop")) return;
      if (target?.source === "pi-native" || isRemoteSession(target)) {
        await api.abort(sessionId);
        runtime.submittedComposerDrafts.delete(sessionId);
        set((current) => ({
          runningSessions: { ...current.runningSessions, [sessionId]: false },
          ...(current.activeSessionId === sessionId ? { isRunning: false } : {}),
        }));
        // Bypass in-flight pre-abort detail reads; request settled source state.
        const detail = await api.getSession(sessionId);
        // A turn that started while this settled-state read was in flight owns
        // the transcript now: the composer unlocked at the isRunning clear
        // above, so the user can already be streaming a new prompt. Its
        // optimistic rows are newer than any snapshot this read can return,
        // and forcing isRunning false would mute the new turn's spinner —
        // leave the newer state alone; the live flow reconciles from here.
        const stateAfterRead = get();
        const turnOwnsTranscript =
          stateAfterRead.runningSessions[sessionId] === true ||
          runtime.liveSessionTranscripts?.has(sessionId) === true ||
          (stateAfterRead.activeSessionId === sessionId &&
            stateAfterRead.isRunning === true);
        if (turnOwnsTranscript) return;
        const messages = detail.session?.messages;
        if (messages) runtime.cacheSessionTranscript(sessionId, messages);
        set((current) => ({
          runningSessions: { ...current.runningSessions, [sessionId]: false },
          ...(messages ? { retainedTranscripts: { ...current.retainedTranscripts, [sessionId]: messages } } : {}),
          ...(current.activeSessionId === sessionId ? { isRunning: false, ...(messages ? { messages } : {}) } : {}),
        }));
        return;
      }
      const submittedDraft = runtime.submittedComposerDrafts.get(sessionId);
      const pendingUserMessageId = stateBeforeAbort.messages
        .slice(submittedDraft?.messageCountBeforeSend ?? 0)
        .findLast((message) => message.role === "user")?.id;
      const preserveSteering = stateBeforeAbort.messages
        .slice(submittedDraft?.messageCountBeforeSend ?? 0)
        .findLast((message) => message.role === "user")?.steering;
      const stoppedAtMs = Date.now();
      let createdAbortResolution: Promise<boolean> | undefined;
      if (submittedDraft && !submittedDraft.abortResolution) {
        createdAbortResolution = new Promise<boolean>((resolve) => {
          submittedDraft.resolveAbort = resolve;
        });
        submittedDraft.abortResolution = createdAbortResolution;
      }
      const pendingForSession = sessionPermissions(
        stateBeforeAbort.pendingPermissions,
        sessionId,
      );
      const [abortResult, ...denials] = await Promise.allSettled([
        api.abort(sessionId),
        ...pendingForSession.map((permission) =>
          api.resolvePermission({
            requestId: permission.requestId,
            decision: "deny",
          }),
        ),
      ]);
      if (abortResult.status === "rejected") {
        // The turn is still running: keep its rows, running state and the
        // submitted draft so Stop can be retried. Only a waiter this call
        // created is released, so a submission awaiting it does not hang.
        if (createdAbortResolution && submittedDraft?.abortResolution === createdAbortResolution) {
          submittedDraft.resolveAbort?.(false);
          delete submittedDraft.abortResolution;
          delete submittedDraft.resolveAbort;
        }
        // A denial the Host accepted (or a request it no longer holds) is
        // settled even though the abort failed; its card must not linger.
        const settled = pendingForSession.filter((_, index) => {
          const denial = denials[index];
          return denial?.status === "fulfilled" ||
            (denial?.reason as { code?: unknown } | undefined)?.code === "NOT_FOUND";
        });
        if (settled.length) {
          set((current) => ({
            pendingPermissions: settled.reduce(
              (permissions, permission) =>
                removePermission(permissions, sessionId, permission.requestId),
              current.pendingPermissions,
            ),
          }));
        }
        throw abortResult.reason;
      }
      set((current) => ({
        pendingPermissions: clearSessionPermissions(
          current.pendingPermissions,
          sessionId,
        ),
      }));
      const state = get();
      if (state.activeSessionId !== sessionId) {
        submittedDraft?.resolveAbort?.(false);
        runtime.submittedComposerDrafts.delete(sessionId);
        set((current) => ({
          runningSessions: { ...current.runningSessions, [sessionId]: false },
        }));
        return;
      }
      const smartStop = preserveSteering
        ? { kind: "settle" as const }
        : resolveComposerSmartStop(state.messages, submittedDraft);
      let retainSubmittedDraft = false;
      if (smartStop.kind === "restore") {
        const fullMessages = await runtime.loadFullSessionMessages(sessionId);
        if (!fullMessages || get().activeSessionId !== sessionId) {
          submittedDraft?.resolveAbort?.(false);
          if (runtime.submittedComposerDrafts.get(sessionId) === submittedDraft) {
            runtime.submittedComposerDrafts.delete(sessionId);
          }
          set((current) => ({
            runningSessions: { ...current.runningSessions, [sessionId]: false },
            isRunning: current.activeSessionId === sessionId ? false : current.isRunning,
          }));
          return;
        }
        const merged = mergeLiveSessionMessages(fullMessages, get().messages);
        const fullStop = resolveComposerSmartStop(merged, submittedDraft);
        if (fullStop.kind === "restore") {
          const pendingUser = merged[fullStop.kept.length];
          try {
            if (!pendingUserMessageId || pendingUser?.id !== pendingUserMessageId) {
              throw new Error(i18n.t("chat.promptRetractionFailed"));
            }
            const result = await api.retractPendingSessionPrompt({
              sessionId,
              userMessageId: pendingUserMessageId,
            });
            if (!result.retracted) {
              throw new Error(i18n.t("chat.promptRetractionFailed"));
            }
            submittedDraft?.resolveAbort?.(true);
            if (runtime.submittedComposerDrafts.get(sessionId) === submittedDraft) {
              runtime.submittedComposerDrafts.delete(sessionId);
            }
            // A subsequent prompt can start after the host releases its mutation
            // lock. Never replace that prompt or its composer with this draft.
            const current = get();
            const latestMessages = current.activeSessionId === sessionId
              ? current.messages
              : runtime.sessionTranscriptCache.get(sessionId) ?? merged;
            const latestUser = latestMessages.findLast((message) => message.role === "user");
            if (latestUser?.id === pendingUserMessageId) {
              const fullWindow = { messageStart: 0, hasMoreBefore: false };
              runtime.cacheSessionTranscript(sessionId, fullStop.kept, fullWindow);
              set((current) => ({
                messages: current.activeSessionId === sessionId ? fullStop.kept : current.messages,
                sessionHistory: { ...current.sessionHistory, [sessionId]: fullWindow },
                composerPrefill: { ...fullStop.draft, sessionId },
                isRunning: current.activeSessionId === sessionId ? false : current.isRunning,
                runningSessions: { ...current.runningSessions, [sessionId]: false },
              }));
            }
            void flushPendingSessionConfiguration(sessionId);
            return;
          } catch (error) {
            retainSubmittedDraft = true;
            // agent_end may have removed the old submission while abort waited.
            // Preserve it for recovery without replacing a newer submission.
            if (submittedDraft && !runtime.submittedComposerDrafts.has(sessionId)) {
              runtime.submittedComposerDrafts.set(sessionId, submittedDraft);
            }
            set({
              error: error instanceof Error ? error.message : String(error),
              errorCode: (error as { code?: string })?.code ?? null,
            });
            const current = get();
            if (
              current.activeSessionId !== sessionId ||
              current.messages.findLast((message) => message.role === "user")?.id !== pendingUserMessageId
            ) {
              submittedDraft?.resolveAbort?.(false);
              return;
            }
          }
        }
        set((current) =>
          current.activeSessionId === sessionId
            ? {
                messages: mergeLiveSessionMessages(merged, current.messages),
                sessionHistory: {
                  ...current.sessionHistory,
                  [sessionId]: { messageStart: 0, hasMoreBefore: false },
                },
              }
            : {},
        );
      }
      submittedDraft?.resolveAbort?.(false);
      if (!retainSubmittedDraft && runtime.submittedComposerDrafts.get(sessionId) === submittedDraft) {
        runtime.submittedComposerDrafts.delete(sessionId);
      }
      const stoppedRows = (rows: UiMessage[]) =>
        rows.map((message) => {
          if (message.role === "assistant" && message.status === "streaming") {
            return {
              ...settleStoppedAssistantMetrics(message, stoppedAtMs),
              status: "aborted" as const,
            };
          }
          if (message.role === "tool" && message.toolStatus === "running") {
            return {
              ...message,
              toolStatus: "error" as const,
              status: "aborted" as const,
              toolCompletedAt:
                message.toolCompletedAt ?? new Date().toISOString(),
            };
          }
          return message;
        });
      set((current) => ({
        messages:
          current.activeSessionId === sessionId
            ? stoppedRows(current.messages)
            : current.messages,
        isRunning: current.activeSessionId === sessionId ? false : current.isRunning,
        runningSessions: { ...current.runningSessions, [sessionId]: false },
      }));
      void flushPendingSessionConfiguration(sessionId);
    },
  };
}

function withoutRecordKey<T>(record: Record<string, T>, key: string): Record<string, T> {
  const next = { ...record };
  delete next[key];
  return next;
}