Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

19.1 KB
Raw Blame
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import type { ChatMode, CodexThread, CodexEvent } from '../types/codex'
import { resolveCodexMode, type CodexMode } from '../lib/codex-mode'

/**
 * A finished plan waiting for "Approve and run" (plan 2.6.6, C1 / blocker S7).
 * `planText` is the model's FULL final answer, not the todo titles: the user is
 * approving concrete commands and target paths, and the titles alone are not a
 * basis for that.
 */
export interface CodexPlanApproval {
  planText: string
  /** Message id the plan came from, so a later run does not resurrect it. */
  messageId: string
  createdAt: number
}

/**
 * Ring size for a thread's event log.
 *
 * The log grew without a ceiling and kept every event of the session: each
 * terminal_output carries the UNTRUNCATED shell result (the 60k-char cap in
 * useCodex applies to what goes back to the MODEL, not to what is stored here)
 * and each file_change carries a full unified diff. A 200-iteration run is tens
 * of megabytes held for as long as the app is open.
 *
 * Nothing reads the CONTENT. The only consumer in the tree is CodexView, which
 * uses `events.length` as one trigger of its auto-scroll key — and that hook
 * re-pins through a ResizeObserver on every content-height change anyway, with
 * the last message's text as the other half of the key. So a length that stops
 * growing at the cap costs the pin nothing. 500 keeps the log long enough to be
 * worth having if it ever gains a real reader.
 */
const CODEX_EVENT_LOG_MAX = 500

interface CodexState {
  chatMode: ChatMode
  threads: Record<string, CodexThread>
  workingDirectory: string
  /**
   * Bump counter, incremented every time a Codex run mutates the working
   * directory (file_write, file_change, terminal commands that can modify
   * files). The explorer panel subscribes to this and reloads when it changes,
   * so new/deleted files appear without a manual refresh.
   */
  fileTreeVersion: number

  /**
   * Ask / Bypass / Plan per conversation (plan 2.6.6, C1). The ONLY persisted
   * part of the mode slice, and additive: codexStore stays at persist version 0
   * so a 2.6.5 build can read this state back without zustand discarding it
   * (R1 DOWNGRADE-KONTRAKT). A downgrade plus re-upgrade loses the conversation
   * modes and nothing else, and they fall back to settings.codexDefaultMode.
   */
  modeByConversation: Record<string, CodexMode>
  /**
   * The last Ask or Bypass the user picked anywhere. A NEW conversation is
   * stamped with it when it is created (startConversationMode), instead of
   * falling back to Ask, which made every "New" undo the user's choice
   * (Gegenprobe 01.10.2026). Stamped, not used as a fallback: an older
   * conversation that never picked keeps running in what it always ran in.
   * Plan is per task and never carried over: a fresh conversation does not
   * start read-only. Persisted, additive, a downgrade only loses this key.
   */
  lastPickedMode: Exclude<CodexMode, 'plan'> | null
  /**
   * A mode picked while a run is in flight. It does NOT touch the running turn:
   * a switch takes effect from the next send, which is what the dropdown says.
   * Transient on purpose, an app restart has no run to park anything for.
   */
  parkedModeByConversation: Record<string, CodexMode>
  /**
   * A mode picked on the Code start screen, before any conversation exists
   * (A37, 26.10.2026). The dropdown used to show the global default there and
   * drop a pick on the floor ("Open a coding chat first"), while the first
   * send stamped the new conversation with `lastPickedMode`. A user who had
   * once picked Bypass saw "Ask" and got an unattended run. The next
   * conversation created is stamped with this, then it is cleared.
   * Transient: a restart shows lastPickedMode again, which is also what runs.
   */
  draftMode: CodexMode | null
  /** The mode this conversation had before it went into Plan mode. */
  prePlanModeByConversation: Record<string, CodexMode>
  /** Plan finished, waiting for approval. Cleared when the run is approved. */
  planApprovalByConversation: Record<string, CodexPlanApproval>

  /**
   * Sends that have begun and not yet finished. Counted synchronously at the
   * top of sendInstruction, because the thread status only flips to 'running'
   * after five awaits and the folder was changeable for that whole gap
   * (A8 review, S1). Runtime only, never persisted: a crash must not leave a
   * ghost send holding the working directory hostage.
   */
  sendsInFlight: number
  beginSend: () => void
  endSend: () => void

  setChatMode: (mode: ChatMode) => void
  /**
   * Pick the folder the agent works in. The store is the single truth; open
   * threads are pulled along one at a time by `syncThreadWorkingDirectory` at
   * the next send of THAT conversation. Writing every thread here would
   * silently overwrite a deliberate per-chat workspace (A8 review, S5).
   */
  setWorkingDirectory: (dir: string) => void
  /**
   * Give the folder back. The empty string is persisted on purpose: a restart
   * must not resurrect the folder (A8, 2.6.8).
   */
  clearWorkingDirectory: () => void
  /** Pin ONE conversation's thread to a folder. */
  setThreadWorkingDirectory: (conversationId: string, dir: string) => void
  /**
   * Point one conversation's thread at the folder the picker shows RIGHT NOW,
   * and return that folder.
   *
   * A thread copies the folder once at init and never looked at the store
   * again, while the run resolver prefers the thread. So a mis-click stayed the
   * agent's root for the rest of the conversation no matter what the picker
   * said afterwards, and a Remove pressed during the awaits at the top of a
   * send was overwritten by the stale snapshot the send had already taken
   * (A8 review, B1). Reads its own live state, so there is no snapshot to go
   * stale, and touches nothing but the named conversation.
   */
  syncThreadWorkingDirectory: (conversationId: string) => string
  bumpFileTreeVersion: () => void

  /**
   * The user picked a mode in the dropdown. While a run is active the pick is
   * PARKED and applied by the next send; otherwise it lands immediately.
   */
  chooseCodexMode: (conversationId: string, mode: CodexMode, runActive: boolean) => void
  /** A pick on the start screen, before a conversation exists (see draftMode). */
  chooseDraftMode: (mode: CodexMode) => void
  /** A Code conversation was just created: it starts in the start-screen pick,
   *  else the last Ask/Bypass pick. */
  startConversationMode: (conversationId: string) => void
  /** Apply a parked pick. Called once at the start of every send. */
  applyParkedMode: (conversationId: string) => void
  /** The conversation's mode, falling back to the global default. */
  codexModeFor: (conversationId: string | null | undefined, defaultMode: unknown) => CodexMode
  /**
   * The mode the NEXT send in this conversation runs under, or, without a
   * conversation, the mode the one a send creates will run under. The dropdown
   * shows exactly this, so what it says and what runs come from one function
   * (A37). A parked pick counts: the next send applies it.
   */
  nextSendMode: (conversationId: string | null | undefined, defaultMode: unknown) => CodexMode
  /** Pin a conversation to a mode without touching lastPickedMode or parks. */
  alignConversationMode: (conversationId: string, mode: CodexMode) => void
  setPlanApproval: (conversationId: string, approval: CodexPlanApproval | null) => void

  getThread: (conversationId: string) => CodexThread | undefined
  initThread: (conversationId: string, workingDir: string) => string
  addEvent: (conversationId: string, event: CodexEvent) => void
  setThreadStatus: (conversationId: string, status: CodexThread['status']) => void
  /**
   * Everything this store holds under one conversation id, dropped in one
   * `set()`. Called by `chatStore.dropConversationSideState` when the chat is
   * deleted — see the comment on the implementation for why all FIVE maps go
   * and not just `threads`.
   */
  dropConversation: (conversationId: string) => void
}

/** Drop one key from a record without leaving an undefined hole behind. */
function omit<T>(map: Record<string, T>, key: string): Record<string, T> {
  if (!(key in map)) return map
  const next = { ...map }
  delete next[key]
  return next
}

export const useCodexStore = create<CodexState>()(
  persist(
    (set, get) => ({
      chatMode: 'lu',
      threads: {},
      sendsInFlight: 0,
      workingDirectory: '',
      fileTreeVersion: 0,
      modeByConversation: {},
      lastPickedMode: null,
      parkedModeByConversation: {},
      draftMode: null,
      prePlanModeByConversation: {},
      planApprovalByConversation: {},

      // The counter never goes below zero: a double release (an early return
      // that also falls through a finally) must not open the lock for a send
      // that is still running.
      beginSend: () => set((state) => ({ sendsInFlight: state.sendsInFlight + 1 })),
      endSend: () => set((state) => ({ sendsInFlight: Math.max(0, state.sendsInFlight - 1) })),

      setChatMode: (mode) => set({ chatMode: mode }),
      setWorkingDirectory: (dir) => set({ workingDirectory: dir }),
      // '' and not `undefined`: partialize writes this key on every change, so
      // the empty string is what lands in localStorage and what a restart reads
      // back. Deleting the key would let an older persisted value survive.
      clearWorkingDirectory: () => set({ workingDirectory: '' }),

      setThreadWorkingDirectory: (conversationId, dir) =>
        set((state) => {
          const thread = state.threads[conversationId]
          if (!thread || thread.workingDirectory === dir) return state
          return {
            threads: { ...state.threads, [conversationId]: { ...thread, workingDirectory: dir } },
          }
        }),

      syncThreadWorkingDirectory: (conversationId) => {
        const live = get().workingDirectory
        get().setThreadWorkingDirectory(conversationId, live)
        return live
      },
      bumpFileTreeVersion: () => set((state) => ({ fileTreeVersion: state.fileTreeVersion + 1 })),

      chooseCodexMode: (conversationId, mode, runActive) =>
        set((state) => {
          // Parked either way: it is the user's last VISIBLE choice, which is
          // what "Approve and run" reads to decide its target mode. While a run
          // is active that is all it is, the running turn keeps its own mode.
          const parked = { ...state.parkedModeByConversation, [conversationId]: mode }
          const lastPickedMode = mode === 'plan' ? state.lastPickedMode : mode
          if (runActive) return { parkedModeByConversation: parked, lastPickedMode }
          const current = state.modeByConversation[conversationId]
          const prePlan =
            mode === 'plan' && current !== 'plan' && current
              ? { ...state.prePlanModeByConversation, [conversationId]: current }
              : state.prePlanModeByConversation
          return {
            parkedModeByConversation: parked,
            prePlanModeByConversation: prePlan,
            modeByConversation: { ...state.modeByConversation, [conversationId]: mode },
            lastPickedMode,
          }
        }),

      chooseDraftMode: (mode) =>
        set((state) => ({
          draftMode: mode,
          lastPickedMode: mode === 'plan' ? state.lastPickedMode : mode,
        })),

      startConversationMode: (conversationId) =>
        set((state) => {
          const stamp = state.draftMode ?? state.lastPickedMode
          if (!stamp || state.modeByConversation[conversationId]) return state
          return {
            draftMode: null,
            modeByConversation: { ...state.modeByConversation, [conversationId]: stamp },
          }
        }),

      applyParkedMode: (conversationId) =>
        set((state) => {
          const parked = state.parkedModeByConversation[conversationId]
          if (!parked) return state
          const current = state.modeByConversation[conversationId]
          const prePlan =
            parked === 'plan' && current !== 'plan' && current
              ? { ...state.prePlanModeByConversation, [conversationId]: current }
              : state.prePlanModeByConversation
          return {
            parkedModeByConversation: omit(state.parkedModeByConversation, conversationId),
            prePlanModeByConversation: prePlan,
            modeByConversation: { ...state.modeByConversation, [conversationId]: parked },
          }
        }),

      codexModeFor: (conversationId, defaultMode) =>
        resolveCodexMode(
          conversationId ? get().modeByConversation[conversationId] : undefined,
          defaultMode,
        ),

      nextSendMode: (conversationId, defaultMode) => {
        const state = get()
        if (!conversationId) {
          return resolveCodexMode(state.draftMode ?? state.lastPickedMode, defaultMode)
        }
        return resolveCodexMode(
          state.parkedModeByConversation[conversationId] ?? state.modeByConversation[conversationId],
          defaultMode,
        )
      },

      alignConversationMode: (conversationId, mode) =>
        set((state) => state.modeByConversation[conversationId] === mode
          ? state
          : { modeByConversation: { ...state.modeByConversation, [conversationId]: mode } }),

      setPlanApproval: (conversationId, approval) =>
        set((state) => ({
          planApprovalByConversation: approval
            ? { ...state.planApprovalByConversation, [conversationId]: approval }
            : omit(state.planApprovalByConversation, conversationId),
        })),

      getThread: (conversationId) => get().threads[conversationId],

      initThread: (conversationId, workingDir) => {
        const id = `codex-${Date.now()}`
        set((state) => ({
          threads: {
            ...state.threads,
            [conversationId]: {
              id,
              conversationId,
              events: [],
              status: 'idle',
              workingDirectory: workingDir,
            },
          },
        }))
        return id
      },

      addEvent: (conversationId, event) =>
        set((state) => {
          const thread = state.threads[conversationId]
          if (!thread) return state
          // Auto-bump fileTreeVersion for events that can mutate the working
          // directory. The explorer panel watches this and re-reads.
          const mutatesFs =
            event.type === 'file_change' ||
            event.type === 'terminal_output' // shell/code execution can touch files
          const next = [...thread.events, event]
          return {
            threads: {
              ...state.threads,
              [conversationId]: {
                ...thread,
                events: next.length > CODEX_EVENT_LOG_MAX
                  ? next.slice(next.length - CODEX_EVENT_LOG_MAX)
                  : next,
              },
            },
            fileTreeVersion: mutatesFs ? state.fileTreeVersion + 1 : state.fileTreeVersion,
          }
        }),

      setThreadStatus: (conversationId, status) =>
        set((state) => {
          const thread = state.threads[conversationId]
          if (!thread) return state
          return {
            threads: {
              ...state.threads,
              [conversationId]: { ...thread, status },
            },
          }
        }),

      /**
       * The chat is gone; so is everything this store filed under its id.
       *
       * FIVE maps, not one. `threads` is the expensive one — a thread carries
       * an event ring of up to CODEX_EVENT_LOG_MAX entries, and each entry is
       * either an UNTRUNCATED terminal result (the 60k cap in useCodex applies
       * to what goes back to the model, not to what is stored here) or a full
       * unified diff. That is tens of megabytes held for a chat that no longer
       * exists, and no id left to prove it is an orphan.
       *
       * The other four maps are small, and one of them is the reason this is
       * not merely bookkeeping: `modeByConversation` is the ONE part of the
       * mode slice that is persisted (see `partialize` below), so a deleted
       * chat's Ask/Bypass/Plan pick used to survive every restart from then on.
       * That is the difference between leaking until the next start and leaking
       * for good. `threads` has its own second cost: its status keeps voting in
       * `lib/run-idle.ts` for as long as the entry exists, so a chat deleted
       * mid-run could leave a thread at 'running' and defer every idle-gated
       * dialog for the rest of the session.
       *
       * One `set()` so a subscriber can never observe the conversation half
       * removed, and `omit` returns the same object when the key is absent, so
       * deleting a chat that never touched the Coding Agent is free.
       */
      dropConversation: (conversationId) =>
        set((state) => ({
          threads: omit(state.threads, conversationId),
          modeByConversation: omit(state.modeByConversation, conversationId),
          parkedModeByConversation: omit(state.parkedModeByConversation, conversationId),
          prePlanModeByConversation: omit(state.prePlanModeByConversation, conversationId),
          planApprovalByConversation: omit(state.planApprovalByConversation, conversationId),
        })),
    }),
    {
      // Persist key kept as 'locally-uncensored-codex' for storage
      // back-compat — renaming it would orphan every existing user's
      // coding working-directory. Internal id only; user-facing label is
      // "Coding Agent".
      name: 'locally-uncensored-codex',
      // chatMode is intentionally NOT persisted: newcomers should always land in
      // the Chat tab on startup, not whatever tab they left off in. If a user
      // wants to stay in the Coding Agent, they pick it from the sidebar
      // each session. workingDirectory still persists so it remembers the
      // last project path.
      // ADDITIVE ONLY, and the store version stays 0 (plan R1
      // DOWNGRADE-KONTRAKT). The D1 A/B has a 2.6.5 build and a 2.6.6 build
      // sharing one WebView profile, and zustand is hard about a version
      // mismatch: without a migrate it throws the whole persisted state away,
      // with one the old build stamps its version back and the migration runs
      // AGAIN on the next 2.6.6 start. Staying at version 0 and only adding a
      // key means the old build reads what it knows and ignores the rest; a
      // downgrade plus re-upgrade costs the conversation modes and nothing
      // else, and those fall back to settings.codexDefaultMode.
      partialize: (state) => ({
        workingDirectory: state.workingDirectory,
        modeByConversation: state.modeByConversation,
        lastPickedMode: state.lastPickedMode,
      }),
      // Existing installs have a persisted `chatMode: 'codex'` (or similar) in
      // localStorage from v2.3.8 and earlier. partialize only affects writes,
      // so rehydration would still restore the old value until the user next
      // switches tabs. Force it back to the default on every rehydrate so the
      // fix takes effect on existing users too, not just fresh installs.
      onRehydrateStorage: () => (state) => {
        if (state) state.chatMode = 'lu'
      },
    }
  )
)