Skip to content

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

35.2 KB
Raw Blame
import i18n from "i18next";
import type {
  Mode,
  PendingInteractiveRequests,
  PlanProposal,
  ProposalKind,
  SessionDetail,
  SessionSummary,
  UiMessage,
} from "@pi-desktop/shared";
import {
  isActivePlanExecution,
  isPendingPlan,
  latestPlanProposal,
  terminalizeMissingPlan,
} from "../../lib/plan-mode-state";
import {
  EMPTY_SESSION_WINDOW,
  sessionIsReusableEmpty,
} from "../../lib/session-create";
import {
  pinnedSessionModelBinding,
  sessionNeedsModelPin,
} from "../../lib/session-model";
import {
  retainSessionPane,
} from "../../lib/session-panes";
import {
  projectPathsForNewSessions,
  sessionMatchesProject,
} from "../../lib/sidebar-session-groups";
import {
  sessionIsArchived,
  sessionIsPinned,
  type SessionMeta,
} from "../../lib/sidebar-preferences";
import { api } from "../../lib/api";
import { dropAskDraft } from "../../lib/pending-asks";
import { isRemoteSession, safeSessionSummary, sessionAllows } from "../../lib/remote-session-safety";
import { createRefreshCoordinator } from "../../lib/refresh-coordinator";
import { openRemoteProjectSession, remoteProjectForSession } from "../../lib/remote-project-session";
import {
  applyOptimisticSessionConfiguration,
} from "../../lib/session-thinking";
import {
  durableCoversLiveSessionMessages,
  mergeLiveSessionMessages,
} from "../../lib/session-transcript";
import { sessionReadLooksEmpty } from "../../lib/session-transcript-read";
import { transcriptViewMessages } from "../../lib/transcript-reading";
import type {
  AppState,
  DraftSessionConfiguration,
  SessionHistoryWindow,
} from "../app-state";
import {
  type SessionRuntime,
} from "../runtime/session-runtime";
import { modeAfterPlanningUpdate, visiblePlanningState } from "../helpers/planning-projection";
import type { StoreAccess } from "./types";
import { switchWorkPanelSession } from "./work-panel-slice";

export type SessionSliceDependencies = StoreAccess & {
  runtime: SessionRuntime;
  flushPendingSessionConfiguration: (sessionId: string) => Promise<void>;
  decorateSessions: (
    sessions: SessionSummary[],
    meta: Record<string, SessionMeta>,
  ) => SessionSummary[];
  withoutRecordKey: <T>(record: Record<string, T>, key: string) => Record<string, T>;
  sessionModeForPlanningState: (
    state: AppState["planningStates"][string],
    kind: ProposalKind | undefined,
  ) => Mode;
  openPlanArtifact: (
    proposal: PlanProposal,
    openWorkPanelTabForSession: AppState["openWorkPanelTabForSession"],
    pluginViews: AppState["pluginViews"],
  ) => void;
  rememberSessionCompactions: (
    sessionId: string,
    session:
      | {
          compaction?: import("@pi-desktop/shared").ContextCompactionRecord;
          compactions?: import("@pi-desktop/shared").ContextCompactionRecord[];
        }
      | null
      | undefined,
  ) => void;
  commitForkedSession: (
    session: SessionDetail,
    options: { activate: boolean; clearError?: boolean },
  ) => void;
  persistSessionAndSelect: (options: {
    intent: number;
    projectPath?: string | null;
    draftConfiguration?: DraftSessionConfiguration | null;
  }) => Promise<string | null>;
};

function reconcilePendingQueue<T extends { requestId: string }>(
  current: T[],
  initialRequestIds: ReadonlySet<string>,
  restored: T[],
): T[] {
  const restoredById = new Map(
    restored.map((entry) => [entry.requestId, entry] as const),
  );
  const currentRequestIds = new Set<string>();
  const next = current.flatMap((entry) => {
    currentRequestIds.add(entry.requestId);
    if (
      initialRequestIds.has(entry.requestId) &&
      !restoredById.has(entry.requestId)
    ) {
      return [];
    }
    return [restoredById.get(entry.requestId) ?? entry];
  });
  const appendedRequestIds = new Set<string>();
  for (const entry of restored) {
    if (
      currentRequestIds.has(entry.requestId) ||
      initialRequestIds.has(entry.requestId) ||
      appendedRequestIds.has(entry.requestId)
    ) {
      continue;
    }
    next.push(entry);
    appendedRequestIds.add(entry.requestId);
  }
  return next;
}

function replacePendingQueue<T>(
  queues: Record<string, T[]>,
  sessionId: string,
  queue: T[],
): Record<string, T[]> {
  if (queue.length === 0) {
    if (!queues[sessionId]) return queues;
    const next = { ...queues };
    delete next[sessionId];
    return next;
  }
  if (queues[sessionId] === queue) return queues;
  return { ...queues, [sessionId]: queue };
}

/** Resolve a visible reply fork anchor without hydrating the live source transcript. */
function findVisibleAssistantForkAnchor(
  state: Pick<AppState, "messages" | "transcriptViews">,
  sessionId: string,
  messageId: string,
): UiMessage | undefined {
  const fromLive = state.messages.find((candidate) => candidate.id === messageId);
  if (fromLive) return fromLive;
  // Historical pages are already on screen via transcriptViews. Do not copy
  // them onto state.messages: that would overwrite a concurrently streaming tail.
  return transcriptViewMessages(state.messages, state.transcriptViews[sessionId]).find(
    (candidate) => candidate.id === messageId,
  );
}

export function createSessionSlice({
  get,
  set,
  runtime,
  decorateSessions,
  withoutRecordKey,
  sessionModeForPlanningState,
  openPlanArtifact,
  rememberSessionCompactions,
  commitForkedSession,
  persistSessionAndSelect,
  flushPendingSessionConfiguration,
}: SessionSliceDependencies): Pick<
  AppState,
  | "refreshSessions"
  | "restorePendingInteractive"
  | "restorePendingPlan"
  | "refreshPlanCheckpoints"
  | "prefetchSession"
  | "selectSession"
  | "newSession"
  | "forkSession"
  | "forkAssistantMessage"
  | "configureActiveSession"
  | "abortSession"
> {
  const pendingInteractiveRestoreGenerations = new Map<string, number>();

  const refreshSessionList = createRefreshCoordinator(async () => {
    const result = await api.listSessions();
    set((state) => {
      const next = result.sessions.map(safeSessionSummary);
      const active = state.sessions.find((session) => session.id === state.activeSessionId);
      // A disconnected host may temporarily disappear from inventory; keep the
      // active identity fail-closed until an authoritative detail/list replaces it.
      if (active && isRemoteSession(active) && !next.some((session) => session.id === active.id)) next.push(safeSessionSummary(active));
      return { sessions: decorateSessions(next, state.sessionMeta) };
    });
    return result;
  });

  return {
    refreshSessions: async (options) => {
      const previousSessions = get().sessions;
      const sessions = await refreshSessionList();
      if (options?.revealImportedProjects) {
        get().restoreProjects(
          projectPathsForNewSessions(previousSessions, sessions.sessions),
        );
      }
    },

    restorePendingPlan: async (sessionId) => {
      if (!sessionId) return "unavailable";
      const generation = runtime.nextPlanSyncGeneration(sessionId);
      try {
        const result = await api.pendingPlans(sessionId);
        if (generation !== runtime.planSyncGeneration(sessionId)) return "unavailable";
        const existingCheckpoint = get().planCheckpoints[sessionId];
        const wasPending = existingCheckpoint?.status === "pending";
        const proposal = latestPlanProposal(result.plans, sessionId);
        const durableMode = get().sessions.find(
          (session) => session.id === sessionId,
        )?.mode;
        const hostState =
          result.state ??
          (proposal?.status === "pending"
            ? "awaiting_approval"
            : durableMode === "plan" || durableMode === "goal"
              ? "planning"
              : "inactive");
        // Goal and user modes are not Plan negotiations (ADR mode-definitions).
        const nextState = visiblePlanningState(
          durableMode,
          hostState,
          proposal?.status === "pending" || wasPending,
        );
        const nextKind: ProposalKind | undefined =
          result.kind ??
          proposal?.kind ??
          (durableMode === "plan" ? "plan" : durableMode === "goal" ? "goal" : undefined);
        const checkpoint =
          proposal ??
          (existingCheckpoint?.status === "pending" &&
          nextState === "awaiting_approval"
            ? existingCheckpoint
            : terminalizeMissingPlan(existingCheckpoint, hostState));
        const activeProposal =
          nextState === "awaiting_approval" && isPendingPlan(checkpoint)
            ? checkpoint
            : undefined;
        const executionActive = isActivePlanExecution(checkpoint);
        const planRunSettled = Boolean(activeProposal || executionActive || wasPending);
        set((state) => ({
          planningStates: {
            ...state.planningStates,
            [sessionId]: nextState,
          },
          planCheckpoints: checkpoint
            ? { ...state.planCheckpoints, [sessionId]: checkpoint }
            : state.planCheckpoints,
          pendingPlans: activeProposal
            ? { ...state.pendingPlans, [sessionId]: activeProposal }
            : withoutRecordKey(state.pendingPlans, sessionId),
          runningSessions: planRunSettled
            ? { ...state.runningSessions, [sessionId]: executionActive }
            : state.runningSessions,
          isRunning:
            state.activeSessionId === sessionId && planRunSettled
              ? executionActive
              : state.isRunning,
          sessions: state.sessions.map((session) =>
            session.id === sessionId
              ? {
                  ...session,
                  mode: modeAfterPlanningUpdate(durableMode, hostState, () =>
                    sessionModeForPlanningState(hostState, nextKind),
                    wasPending ? checkpoint : undefined,
                  ),
                }
              : session,
          ),
        }));
        if (checkpoint && activeProposal) {
          openPlanArtifact(
            checkpoint,
            get().openWorkPanelTabForSession,
            get().pluginViews,
          );
        }
        return activeProposal ? "pending" : "terminal";
      } catch {
        return "unavailable";
      }
    },

    /**
     * Reconcile a session's decision cards with the Host-owned read.
     *
     * `pendingAsks` / `pendingPermissions` live in renderer memory only, so a
     * renderer reload forgets both. A successful read is authoritative for
     * requests that existed when the read started: answered or completed cards
     * are removed, while requests delivered during the read are preserved.
     * Failed reads remain non-destructive, and an older overlapping read cannot
     * overwrite a newer result.
     *
     * Only this desktop's own sessions have that read. `native-pi:` sessions
     * are read-mostly imports and remote sessions are driven over RACP-WS, so
     * both keep their own transports.
     */
    restorePendingInteractive: async (sessionId) => {
      if (!sessionId || sessionId.startsWith("native-pi:")) return;
      const session = get().sessions.find(
        (candidate) => candidate.id === sessionId,
      );
      if (!session) return;
      if (session.source === "pi-native" || session.source === "remote") return;

      const generation =
        (pendingInteractiveRestoreGenerations.get(sessionId) ?? 0) + 1;
      pendingInteractiveRestoreGenerations.set(sessionId, generation);
      const beforeRead = get();
      const initialAskIds = new Set(
        (beforeRead.pendingAsks[sessionId] ?? []).map((ask) => ask.requestId),
      );
      const initialPermissionIds = new Set(
        (beforeRead.pendingPermissions[sessionId] ?? []).map(
          (permission) => permission.requestId,
        ),
      );

      let pending: PendingInteractiveRequests;
      try {
        pending = await api.pendingInteractive(sessionId);
      } catch {
        // Silent and non-destructive: an unavailable Main leaves the queues
        // exactly as the live stream left them.
        return;
      }
      if (
        pendingInteractiveRestoreGenerations.get(sessionId) !== generation
      ) {
        return;
      }

      set((state) => {
        if (!state.sessions.some((candidate) => candidate.id === sessionId)) {
          return {};
        }
        const pendingAsks = reconcilePendingQueue(
          state.pendingAsks[sessionId] ?? [],
          initialAskIds,
          pending.asks,
        );
        const pendingPermissions = reconcilePendingQueue(
          state.pendingPermissions[sessionId] ?? [],
          initialPermissionIds,
          pending.permissions,
        );
        const nextPendingAsks = replacePendingQueue(
          state.pendingAsks,
          sessionId,
          pendingAsks,
        );
        const nextPendingPermissions = replacePendingQueue(
          state.pendingPermissions,
          sessionId,
          pendingPermissions,
        );
        const keptAskIds = new Set(pendingAsks.map((ask) => ask.requestId));
        let askDrafts = state.askDrafts;
        for (const ask of state.pendingAsks[sessionId] ?? []) {
          if (!keptAskIds.has(ask.requestId)) {
            askDrafts = dropAskDraft(askDrafts, ask.requestId);
          }
        }
        if (
          nextPendingAsks === state.pendingAsks &&
          nextPendingPermissions === state.pendingPermissions &&
          askDrafts === state.askDrafts
        ) {
          return {};
        }
        return {
          pendingAsks: nextPendingAsks,
          pendingPermissions: nextPendingPermissions,
          askDrafts,
        };
      });
    },

    refreshPlanCheckpoints: async () => {
      const sessionIds = get().sessions.map((session) => session.id);
      await Promise.allSettled(
        sessionIds.map(async (sessionId) => {
          await get().restorePendingPlan(sessionId);
          // A sidecar restart or reload is when a forgotten card has to come
          // back, so both reads run in the same per-session batch.
          await get().restorePendingInteractive(sessionId);
        }),
      );
    },

    prefetchSession: async (id) => {
      if (!id || runtime.sessionTranscriptCache.has(id)) return;
      await runtime.loadSessionDetail(id, {
        messageLimit: 100,
        contentLimit: 64 * 1024,
      });
    },

    selectSession: async (id, opts) => {
      const intent = opts?.navigationIntent ?? runtime.beginNavigationIntent();
      const selection = runtime.beginSessionSelection(id, intent);
      const stateAtStart = get();
      const runningAtSelection = stateAtStart.runningSessions[id] === true;
      if (runningAtSelection) runtime.liveSessionTranscripts.add(id);
      if (stateAtStart.activeSessionId) {
        runtime.cacheSessionTranscript(
          stateAtStart.activeSessionId,
          stateAtStart.messages,
          stateAtStart.sessionHistory[stateAtStart.activeSessionId],
        );
      }
      set({ selectingSessionId: id, page: "chat", settingsOpen: false });
      const outcomeAcknowledgement = get().acknowledgeSessionOutcome(id);

      const commitSelection = (
        messages: UiMessage[],
        revalidating: boolean,
        historyWindow: SessionHistoryWindow =
          runtime.sessionHistoryCache.get(id) ?? {
            messageStart: 0,
            hasMoreBefore: false,
          },
      ) => {
        const record = opts?.record !== false;
        const commit = (state: AppState) => ({
          ...(state.activeSessionId === id ? {} : switchWorkPanelSession(state, id)),
          ...retainSessionPane(state, id, messages),
          activeSessionId: id,
          selectingSessionId: revalidating ? id : undefined,
          messages,
          sessionHistory: { ...state.sessionHistory, [id]: historyWindow },
          page: "chat" as const,
          isRunning: state.runningSessions[id] ?? false,
        });
        if (!record) {
          set(commit);
          return;
        }
        set((state) => {
          const stack = state.navStack.slice(0, state.navIndex + 1);
          const last = stack[stack.length - 1];
          const same = last?.page === "chat" && last?.sessionId === id;
          const nextStack = same ? stack : [...stack, { page: "chat" as const, sessionId: id }].slice(-50);
          return {
            ...commit(state),
            navStack: nextStack,
            navIndex: nextStack.length - 1,
          };
        });
      };

      const alignWorkspace = async (session?: SessionSummary | null) => {
        if (isRemoteSession(session)) return runtime.navigationIntentIsCurrent(intent);
        const projectPath = session?.projectPath;
        if (projectPath) {
          if (
            !sessionMatchesProject(
              { projectPath: get().activeProjectPath },
              projectPath,
            )
          ) {
            const workspace = await get().activateProject(projectPath, {
              navigationIntent: intent,
            });
            if (!runtime.navigationIntentIsCurrent(intent)) return false;
            if (!workspace) throw new Error(i18n.t("errors.workspaceActivationFailed"));
          }
        } else if (get().workspace) {
          await get().clearProject({ navigationIntent: intent });
          if (!runtime.navigationIntentIsCurrent(intent)) return false;
        }
        return runtime.navigationIntentIsCurrent(intent);
      };

      try {
        if (!runtime.navigationIntentIsCurrent(intent)) return;
        const summary = get().sessions.find((session) => session.id === id);
        const detailPromise = runtime.loadSessionDetail(id, {
          messageLimit: 100,
          contentLimit: 64 * 1024,
        });
        let detail: Awaited<typeof detailPromise> | undefined;
        const retainedMessages =
          runtime.sessionTranscriptCache.get(id) ?? get().retainedTranscripts[id];
        if (retainedMessages && get().activeSessionId !== id && summary) {
          commitSelection(retainedMessages, true);
        } else if (
          summary &&
          get().activeSessionId !== id &&
          sessionIsReusableEmpty(summary, {
            running: runningAtSelection,
            liveMessageCount: retainedMessages?.length ?? 0,
            submitted: runtime.submittedComposerDrafts.has(id),
          })
        ) {
          runtime.cacheSessionTranscript(id, [], EMPTY_SESSION_WINDOW);
          commitSelection([], true, EMPTY_SESSION_WINDOW);
        }
        // Baseline for the stale-read guard below. It is taken after this
        // selection's own provisional commits (which can move the cache entry
        // themselves) but before workspace alignment, so an idle edit landing
        // during alignment or the read is still detected.
        const transcriptBeforeAlignment = runtime.sessionTranscriptCache.get(id);
        if (summary) {
          if (
            !(await runtime.queueWorkspaceAlignment(() =>
              alignWorkspace(summary),
            ))
          ) {
            return;
          }
        } else {
          detail = await detailPromise;
          if (!runtime.navigationIntentIsCurrent(intent)) return;
          if (
            !(await runtime.queueWorkspaceAlignment(() =>
              alignWorkspace(detail?.session),
            ))
          ) {
            return;
          }
        }

        const cachedMessages = runtime.sessionTranscriptCache.get(id);
        if (cachedMessages && runtime.navigationIntentIsCurrent(intent)) {
          runtime.cacheSessionTranscript(
            id,
            cachedMessages,
            runtime.sessionHistoryCache.get(id),
          );
          commitSelection(
            cachedMessages,
            true,
            runtime.sessionHistoryCache.get(id),
          );
        }

        detail ??= await detailPromise;
        if (!runtime.navigationIntentIsCurrent(intent)) return;
        if (detail.session && sessionReadLooksEmpty(detail.session)) {
          // A window read that comes back empty for a session the sidebar
          // counts as having history is not an empty conversation (#795). Ask
          // once more, and if the transcript still reads empty keep whatever
          // the user already has and say so, instead of committing nothing and
          // leaving a blank pane behind.
          const reread = await runtime.loadSessionDetail(id, {
            messageLimit: 100,
            contentLimit: 64 * 1024,
          });
          if (!runtime.navigationIntentIsCurrent(intent)) return;
          if (reread.session && sessionReadLooksEmpty(reread.session)) {
            const retained =
              runtime.sessionTranscriptCache.get(id) ??
              get().retainedTranscripts[id];
            if (retained && retained.length > 0) {
              commitSelection(retained, true);
            } else {
              get().showToast(i18n.t("chat.sessionTranscriptEmpty"), {
                variant: "error",
              });
            }
            return;
          }
          detail = reread;
        }
        const historyWindow = detail.session
          ? {
              messageStart: detail.session.messageStart ?? 0,
              hasMoreBefore: detail.session.hasMoreBefore === true,
              contentLimited: true,
            }
          : { messageStart: 0, hasMoreBefore: false };
        const currentState = get();
        // An idle-session edit (message delete, revision switch) that landed
        // while this selection aligned the workspace or awaited the bounded
        // read replaces the transcript cache entry; committing the stale
        // window now would revert that edit on screen. loadSessionDetail
        // already refuses to cache such a read, but its baseline predates this
        // selection's own provisional commits, so the caller keeps its own.
        // An entry that vanished (cache eviction) is not an edit.
        const transcriptNow = runtime.sessionTranscriptCache.get(id);
        const supersedingTranscript =
          transcriptNow !== undefined &&
          transcriptNow !== transcriptBeforeAlignment &&
          !runtime.liveSessionTranscripts.has(id) &&
          currentState.runningSessions[id] !== true
            ? transcriptNow
            : undefined;
        const transcriptMovedWhileReading = supersedingTranscript !== undefined;
        const liveMessages =
          (runningAtSelection ||
            currentState.runningSessions[id] === true ||
            runtime.liveSessionTranscripts.has(id))
            ? currentState.activeSessionId === id
              ? currentState.messages
              : runtime.sessionTranscriptCache.get(id) ??
                currentState.retainedTranscripts[id]
            : undefined;
        const selectedMessages = detail.session
          ? liveMessages
            ? mergeLiveSessionMessages(detail.session.messages ?? [], liveMessages)
            : detail.session.messages ?? []
          : liveMessages ?? [];
        const committedMessages = supersedingTranscript ?? selectedMessages;
        if (detail.session) {
          if (isRemoteSession(detail.session)) {
          const { messages: _messages, ...summary } = detail.session;
          set((state) => ({ sessions: decorateSessions([
            safeSessionSummary(summary), ...state.sessions.filter((session) => session.id !== id),
          ], state.sessionMeta) }));
          }
          if (!transcriptMovedWhileReading) {
            runtime.cacheSessionTranscript(id, selectedMessages, historyWindow);
          }
        }
        commitSelection(
          committedMessages,
          false,
          transcriptMovedWhileReading ? undefined : historyWindow,
        );
        if (
          currentState.runningSessions[id] !== true &&
          durableCoversLiveSessionMessages(detail.session?.messages ?? [], liveMessages)
        ) {
          runtime.liveSessionTranscripts.delete(id);
        }
        rememberSessionCompactions(id, detail.session);
        void get().restorePendingPlan(id);
        // Opening a session is where its unanswered cards become visible again
        // after a renderer reload; the live stream only re-delivers new ones.
        void get().restorePendingInteractive(id);
        const selected = get().sessions.find((session) => session.id === id);
        if (
          selected &&
          sessionAllows(selected, "canConfigureModel") &&
          sessionNeedsModelPin(selected) &&
          get().pendingPlans[id]?.status !== "pending"
        ) {
          const pin = pinnedSessionModelBinding({
            session: selected,
            messages: committedMessages,
            settings: get().settings,
            providers: get().providers,
            recentModels: get().recentModels,
            discovered: get().providers.flatMap((candidate) =>
              get().providerModels[candidate.id] ?? []),
          });
          if (pin.providerId && pin.modelId) {
            set((state) => ({
              sessions: state.sessions.map((session) =>
                session.id === id
                  ? applyOptimisticSessionConfiguration(session, pin)
                  : session,
              ),
            }));
            if (get().activeSessionId === id) {
              void get().configureActiveSession({
                mode: selected.mode,
                providerId: pin.providerId,
                modelId: pin.modelId,
                thinkingLevel: selected.thinkingLevel,
              });
            } else {
              // The active-session branch reports a refused write through its
              // flush; a background session must not drop the pin silently,
              // because the row keeps the optimistic value while the host
              // reverts to the previous model on the next launch.
              const pinWrite = api.configureSession(id, {
                mode: selected.mode,
                providerId: pin.providerId,
                modelId: pin.modelId,
              });
              void pinWrite.catch((error) => {
                get().showToast(
                  error instanceof Error ? error.message : String(error),
                  { variant: "error" },
                );
              });
            }
          }
        }
      } finally {
        await outcomeAcknowledgement;
        if (runtime.isCurrentSessionSelection(selection)) {
          runtime.clearSessionSelection(selection);
          set((state) =>
            state.selectingSessionId === id
              ? { selectingSessionId: undefined }
              : {},
          );
        }
      }
    },

    newSession: async (options) => {
      const activeSession = get().sessions.find((session) => session.id === get().activeSessionId);
      const remoteProject = options?.remoteProject ?? (
        options && "projectPath" in options ? undefined
          : remoteProjectForSession(activeSession)
      );
      if (remoteProject) return openRemoteProjectSession({ get, set, runtime }, remoteProject);
      if (!(options && "projectPath" in options) && isRemoteSession(activeSession ?? (
        get().activeSessionId?.startsWith("remote:") ? { id: get().activeSessionId! } : undefined
      ))) throw new Error(i18n.t("remote:REMOTE_PROJECT_REQUIRED"));
      // A global New Task (sidebar, titlebar, Cmd/Ctrl+N, palette, search)
      // starts a temporary conversation; only an explicit `projectPath` (a
      // project row's +, the home project picker, the project index, or a
      // worktree) attaches it to a project (issue #2455). An active remote
      // project is the exception above: it has no temporary group.
      const requestedProjectPath =
        options && "projectPath" in options
          ? options.projectPath ?? null
          : null;
      const isolated = options?.isolated === true;
      const scopeKey = `${runtime.newSessionScopeKey(requestedProjectPath)}${isolated ? "\u0000isolated" : ""}`;
      const pending = runtime.pendingNewSessionRequests.get(scopeKey);
      if (pending) {
        await pending;
        return;
      }

      const intent = runtime.beginNavigationIntent();
      const request = (async () => {
        if (
          requestedProjectPath &&
          !sessionMatchesProject(
            { projectPath: get().activeProjectPath },
            requestedProjectPath,
          )
        ) {
          const workspace = await get().activateProject(requestedProjectPath, {
            navigationIntent: intent,
          });
          if (!runtime.navigationIntentIsCurrent(intent)) return null;
          if (!workspace) throw new Error(i18n.t("errors.workspaceActivationFailed"));
        }
        if (requestedProjectPath === null && get().workspace) {
          await get().clearProject({ navigationIntent: intent });
          if (!runtime.navigationIntentIsCurrent(intent)) return null;
        }

        const latest = runtime.latestSessionInScope(
          get().sessions,
          requestedProjectPath,
          get().sessionMeta,
        );
        if (
          latest &&
          sessionIsReusableEmpty(latest, {
            isolated,
            running: get().runningSessions[latest.id] === true,
            liveMessageCount: runtime.liveMessageCountForSession(latest.id, get()),
            submitted: runtime.submittedComposerDrafts.has(latest.id),
          })
        ) {
          if (get().activeSessionId === latest.id && get().page === "chat") return latest.id;
          await get().selectSession(latest.id, { navigationIntent: intent });
          return runtime.navigationIntentIsCurrent(intent) ? latest.id : null;
        }

        return await persistSessionAndSelect({
          intent,
          projectPath: requestedProjectPath,
          draftConfiguration: null,
          ...(isolated ? { isolated: true } : {}),
        });
      })();
      runtime.pendingNewSessionRequests.set(scopeKey, request);
      try {
        await request;
      } finally {
        if (runtime.pendingNewSessionRequests.get(scopeKey) === request) {
          runtime.pendingNewSessionRequests.delete(scopeKey);
        }
      }
    },

    forkSession: async (id) => {
      const intent = runtime.beginNavigationIntent();
      const state = get();
      if (!id || state.runningSessions[id]) return;
      const source = state.sessions.find((session) => session.id === id);
      if (!source) throw new Error(i18n.t("errors.sessionNotFound"));
      if (!sessionAllows(source, "canEditMessages")) return;

      if (source.projectPath) {
        if (
          !sessionMatchesProject(
            { projectPath: state.activeProjectPath },
            source.projectPath,
          )
        ) {
          const workspace = await get().activateProject(source.projectPath, {
            navigationIntent: intent,
          });
          if (!runtime.navigationIntentIsCurrent(intent)) return;
          if (!workspace) throw new Error(i18n.t("errors.workspaceActivationFailed"));
        }
      } else if (state.workspace) {
        await get().clearProject({ navigationIntent: intent });
        if (!runtime.navigationIntentIsCurrent(intent)) return;
      }

      const sourceTitle = source.title.trim() || i18n.t("chat.untitledTask");
      const result = await api.forkSession(
        id,
        i18n.t("nav.branchTitle", { title: sourceTitle }),
      );
      commitForkedSession(result.session, {
        activate: runtime.navigationIntentIsCurrent(intent),
      });
    },

    forkAssistantMessage: async (messageId) => {
      const intent = runtime.beginNavigationIntent();
      // Fork needs only the anchor id: the host reads the canonical prefix.
      // Hydrating the source here would overwrite its concurrently streaming tail.
      const state = get();
      const sessionId = state.activeSessionId;
      if (!sessionId || state.selectingSessionId) return;
      const message = findVisibleAssistantForkAnchor(state, sessionId, messageId);
      const source = state.sessions.find((session) => session.id === sessionId);
      if (!message || message.role !== "assistant" || !source) return;
      if (!sessionAllows(source, "canEditMessages")) return;

      try {
        const sourceTitle = source.title.trim() || i18n.t("chat.untitledTask");
        const result = await api.forkSession(
          sessionId,
          i18n.t("nav.branchTitle", { title: sourceTitle }),
          messageId,
        );
        commitForkedSession(result.session, {
          activate: runtime.navigationIntentIsCurrent(intent),
          clearError: true,
        });
      } catch (error) {
        set({
          error: error instanceof Error ? error.message : String(error),
          errorCode: (error as { code?: string })?.code ?? null,
        });
      }
    },

    configureActiveSession: async (config) => {
      const sessionId = get().activeSessionId;
      if (!sessionId) {
        set((state) => ({
          draftConfiguration: {
            mode: config.mode,
            thinkingLevel: config.thinkingLevel,
            providerId:
              config.providerId ?? state.draftConfiguration?.providerId,
            modelId: config.modelId ?? state.draftConfiguration?.modelId,
            permissionMode:
              config.permissionMode ?? state.draftConfiguration?.permissionMode,
            fastMode: config.fastMode ?? state.draftConfiguration?.fastMode,
          },
        }));
        return;
      }
      if (!sessionAllows(get().sessions.find((session) => session.id === sessionId), "canConfigureModel")) return;
      if (get().pendingPlans[sessionId]?.status === "pending") return;
      if (config.mode !== get().sessions.find((session) => session.id === sessionId)?.mode) {
        runtime.sessionModeSelections.set(sessionId, (runtime.sessionModeSelections.get(sessionId) ?? 0) + 1);
      }
      if (
        get().runningSessions[sessionId] ||
        runtime.sessionConfigurationFlushes.has(sessionId)
      ) {
        runtime.pendingSessionConfigurations.set(
          sessionId,
          runtime.mergeSessionConfiguration(
            runtime.pendingSessionConfigurations.get(sessionId),
            config,
          ),
        );
        set((state) => ({
          sessions: state.sessions.map((session) =>
            session.id === sessionId
              ? applyOptimisticSessionConfiguration(session, config)
              : session,
          ),
        }));
        return;
      }
      const payload = runtime.mergeSessionConfiguration(
        runtime.pendingSessionConfigurations.get(sessionId),
        config,
      );
      runtime.pendingSessionConfigurations.delete(sessionId);
      const write = api.configureSession(sessionId, payload).then((result) => set((state) => ({
        sessions: state.sessions.map((session) =>
          session.id === sessionId
            ? {
                ...result.session,
                pinned: sessionIsPinned(sessionId, state.sessionMeta),
                archived: sessionIsArchived(sessionId, state.sessionMeta),
              }
            : session,
        ),
        planningStates: {
          ...state.planningStates,
          [sessionId]: result.session.mode === "plan" ? "planning" : "inactive",
        },
      })));
      runtime.sessionConfigurationFlushes.set(sessionId, write);
      try {
        await write;
      } finally {
        if (runtime.sessionConfigurationFlushes.get(sessionId) === write) {
          runtime.sessionConfigurationFlushes.delete(sessionId);
        }
        await flushPendingSessionConfiguration(sessionId);
      }
    },

    /** Abort one session's running turn, whether or not it is the visible one. */
    abortSession: async (sessionId) => {
      if (!sessionId) return;
      await api.abort(sessionId);
      set((state) => ({
        isRunning:
          state.activeSessionId === sessionId ? false : state.isRunning,
        runningSessions: { ...state.runningSessions, [sessionId]: false },
      }));
    },
  };
}