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.

fix(code): A8-Nachbesserung, der Store ist die Wahrheit und die Sperre ist echt

purpled22bf34abc14
diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsx
index 66e31b99..025e2455 100644
--- a/src/components/chat/CodexView.tsx
+++ b/src/components/chat/CodexView.tsx
@@ -21,6 +21,14 @@ import { GoalBar } from './GoalBar'
import { LoopBar } from './LoopBar'
import { useSettingsStore } from '../../stores/settingsStore'
import { useModelStore } from '../../stores/modelStore'
+import { useAgentLoopStore } from '../../stores/agentLoopStore'
+import { useAgentModeStore } from '../../stores/agentModeStore'
+import {
+ CODEX_WORKDIR_LOCK_TITLE,
+ codexBusyReason,
+ codexFallbackLabel,
+} from '../../lib/codex-workdir'
+import { resolveWorkspacePath } from '../../api/agents/workspace-resolve'
import { StagedChangesPanel } from './StagedChangesPanel'
import { SlashStepsBlock } from './SlashStepsBlock'
import { User, Code, Eye, GitBranch, Download, RefreshCw, RotateCcw, Folder, FolderX, Check, AlertTriangle } from 'lucide-react'
@@ -79,15 +87,27 @@ export function CodexView() {
const createConversation = useChatStore((s) => s.createConversation)
const codexWorkingDir = useCodexStore((s) => s.workingDirectory)
const clearWorkingDirectory = useCodexStore((s) => s.clearWorkingDirectory)
- const anyThreadRunning = useCodexStore((s) =>
- Object.values(s.threads).some((t) => t.status === 'running'),
- )
// A8 (2.6.8): the same Remove sits in the explorer column, but that column
// can be collapsed, and two users looked for a way out of their folder and
// found none. The header always shows the folder, so it also carries the way
- // to give it back. Locked, not hidden, while a coding turn is in flight.
- const removeFolderLocked =
- anyThreadRunning || Object.values(generatingMap).some(Boolean)
+ // to give it back. Locked, not hidden, while a coding turn is in flight, and
+ // the verdict is the shared one so the two buttons cannot drift apart.
+ const sendsInFlight = useCodexStore((s) => s.sendsInFlight)
+ const threads = useCodexStore((s) => s.threads)
+ const loop = useAgentLoopStore((s) => s.loop)
+ const lockReason = codexBusyReason({ sendsInFlight, threads, loop })
+
+ // Where the agent goes while no folder is picked: a per-chat workspace or
+ // settings.defaultWorkspace both beat an empty picker, so the header and the
+ // empty state have to name the winner instead of always saying sandbox
+ // (review S4).
+ const perChatWorkspace = useAgentModeStore((s) =>
+ activeConversationId ? s.workspaces[activeConversationId] : undefined,
+ )
+ const defaultWorkspace = useSettingsStore((s) => s.settings.defaultWorkspace)
+ const fallbackLabel = codexFallbackLabel(
+ resolveWorkspacePath({ perChat: perChatWorkspace, defaultWorkspace }),
+ )
// Git availability for the Codex view (v2.5.0). Codex shells out to git for
// git_status/diff/commit/log; if git is missing those tools fail. Probe on
@@ -147,24 +167,25 @@ export function CodexView() {
~/agent-workspace, which is also where shell output now lands. */}
<span
className="flex items-center gap-1 text-[0.5rem] text-gray-500 dark:text-gray-500 font-mono truncate max-w-[200px]"
- title={codexWorkingDir || 'Sandbox: ~/agent-workspace/<chat>'}
+ title={codexWorkingDir || `No folder picked, the agent works in ${fallbackLabel}`}
>
<Folder size={9} className="shrink-0 opacity-70" />
- <span className="truncate">{codexWorkingDir || 'sandbox · ~/agent-workspace'}</span>
+ <span className="truncate">{codexWorkingDir || fallbackLabel}</span>
</span>
{codexWorkingDir && (
<button
- onClick={() => { if (!removeFolderLocked) clearWorkingDirectory() }}
- disabled={removeFolderLocked}
+ onClick={() => { if (!lockReason) clearWorkingDirectory() }}
+ disabled={!!lockReason}
data-testid="codex-remove-folder"
+ aria-label="Remove the working directory"
title={
- removeFolderLocked
- ? 'Wait for the current run to finish, then you can remove the folder.'
- : 'Remove this folder. The agent falls back to its own sandbox under ~/agent-workspace until you pick a new one.'
+ lockReason
+ ? CODEX_WORKDIR_LOCK_TITLE[lockReason]
+ : `Remove this folder. The agent falls back to ${fallbackLabel} until you pick a new one.`
}
- className="p-0.5 rounded text-gray-400 dark:text-gray-600 hover:text-red-500 dark:hover:text-red-400 hover:bg-gray-100 dark:hover:bg-white/5 disabled:opacity-30 disabled:hover:text-gray-400 transition-colors shrink-0"
+ className="p-1 rounded text-gray-400 dark:text-gray-600 hover:text-red-500 dark:hover:text-red-400 hover:bg-gray-100 dark:hover:bg-white/5 disabled:opacity-30 disabled:hover:text-gray-400 transition-colors shrink-0"
>
- <FolderX size={9} />
+ <FolderX size={11} />
</button>
)}
<div className="flex-1" />
@@ -234,8 +255,8 @@ export function CodexView() {
</p>
{!codexWorkingDir && (
<p className="text-[0.55rem] text-amber-500/70 mt-2" data-testid="codex-no-folder-hint">
- No folder set. The agent works in its own sandbox under ~/agent-workspace.
- Pick a project with "Select folder..." in the file tree panel on the right.
+ No folder picked. The agent works in {fallbackLabel}. Pick a project with
+ "Select folder..." in the file tree panel on the right.
</p>
)}
</div>
diff --git a/src/components/chat/ExplorerPanel.tsx b/src/components/chat/ExplorerPanel.tsx
index dbc665f5..a2588a44 100644
--- a/src/components/chat/ExplorerPanel.tsx
+++ b/src/components/chat/ExplorerPanel.tsx
@@ -36,11 +36,19 @@ import {
PanelRightClose,
PanelRightOpen,
RefreshCw,
- X,
+ FolderX,
} from 'lucide-react'
import { useCodexStore } from '../../stores/codexStore'
-import { useGenerationStore } from '../../stores/generationStore'
+import { useAgentLoopStore } from '../../stores/agentLoopStore'
+import { useAgentModeStore } from '../../stores/agentModeStore'
+import { useSettingsStore } from '../../stores/settingsStore'
import { useUIStore } from '../../stores/uiStore'
+import {
+ CODEX_WORKDIR_LOCK_TITLE,
+ codexBusyReason,
+ codexFallbackLabel,
+} from '../../lib/codex-workdir'
+import { resolveWorkspacePath } from '../../api/agents/workspace-resolve'
import { backendCall, isTauri, isMacOS } from '../../api/backend'
import {
EMPTY_LISTING,
@@ -72,31 +80,47 @@ export function ExplorerPanel({ onApprovePlan }: Props) {
const clearWorkingDirectory = useCodexStore((s) => s.clearWorkingDirectory)
const fileTreeVersion = useCodexStore((s) => s.fileTreeVersion)
- // A8 (2.6.8): the folder is GLOBAL, so removing it while any coding turn is
- // in flight would pull the rug out from under a run in another chat as well.
- // Locked with a reason on the button while that is the case, not hidden.
- const anyTurnGenerating = useGenerationStore((s) =>
- Object.values(s.generating).some(Boolean),
- )
- const anyThreadRunning = useCodexStore((s) =>
- Object.values(s.threads).some((t) => t.status === 'running'),
- )
- const runActive = anyTurnGenerating || anyThreadRunning
+ // A8 (2.6.8): the folder is GLOBAL, so moving it mid-run would send the next
+ // turn somewhere the user is not looking. Locked with a reason on the button
+ // while that is the case, not hidden, and the SAME lock on both buttons: a
+ // picker that stays free while Remove is held is the same hole (review S8).
+ //
+ // Only Coding Agent signals count. Reading every conversation's generating
+ // flag locked this column whenever any Chat tab was streaming (review S3).
+ const sendsInFlight = useCodexStore((s) => s.sendsInFlight)
+ const threads = useCodexStore((s) => s.threads)
+ const loop = useAgentLoopStore((s) => s.loop)
+ const lockReason = codexBusyReason({ sendsInFlight, threads, loop })
+ const lockTitle = lockReason ? CODEX_WORKDIR_LOCK_TITLE[lockReason] : null
+
+ // Read up here because the workspace fallback below needs it too. The plan
+ // moved into this column, so a collapsed column would hide it, and with it
+ // the only Approve-and-run button there is. The rail says so instead.
+ const activeConversationId = useChatStore((s) => s.activeConversationId)
const width = useUIStore((s) => s.explorerWidth)
const collapsed = useUIStore((s) => s.explorerCollapsed)
const setExplorerWidth = useUIStore((s) => s.setExplorerWidth)
const setExplorerCollapsed = useUIStore((s) => s.setExplorerCollapsed)
+ // Where the agent ACTUALLY goes while the picker is empty. The empty state
+ // used to promise ~/agent-workspace flat out, which is wrong for anybody who
+ // pinned a folder on this chat or set a default workspace: both beat an
+ // empty picker in the run resolver (review S4).
+ const perChatWorkspace = useAgentModeStore((s) =>
+ activeConversationId ? s.workspaces[activeConversationId] : undefined,
+ )
+ const defaultWorkspace = useSettingsStore((s) => s.settings.defaultWorkspace)
+ const fallbackLabel = codexFallbackLabel(
+ resolveWorkspacePath({ perChat: perChatWorkspace, defaultWorkspace }),
+ )
+
const [listings, setListings] = useState<Record<string, ExplorerListing>>({})
const [expanded, setExpanded] = useState<string[]>([])
const [busy, setBusy] = useState<string[]>([])
const [error, setError] = useState<string | null>(null)
const [selected, setSelected] = useState<ExplorerNode | null>(null)
- // The plan moved into this column, so a collapsed column would hide it, and
- // with it the only Approve-and-run button there is. The rail says so instead.
- const activeConversationId = useChatStore((s) => s.activeConversationId)
const planWaiting = useCodexStore((s) =>
activeConversationId ? !!s.planApprovalByConversation[activeConversationId] : false,
)
@@ -177,7 +201,7 @@ export function ExplorerPanel({ onApprovePlan }: Props) {
// Clearing the store also unpins every open thread, so the CURRENT chat falls
// back to its own sandbox instead of keeping the tree it was born with.
const removeFolder = () => {
- if (runActive) return
+ if (lockReason) return
clearWorkingDirectory()
}
@@ -244,8 +268,10 @@ export function ExplorerPanel({ onApprovePlan }: Props) {
<div className="flex items-center gap-1 p-1.5 border-b border-gray-200 dark:border-white/[0.04]">
<button
onClick={pickFolder}
- title={root || 'Pick the folder the agent works in'}
- className="flex-1 min-w-0 flex items-center gap-1 px-1.5 py-1 rounded bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/[0.06] hover:border-gray-400 dark:hover:border-white/15 transition-colors text-left"
+ disabled={!!lockReason}
+ data-testid="explorer-pick-folder"
+ title={lockTitle || root || 'Pick the folder the agent works in'}
+ className="flex-1 disabled:opacity-40 min-w-0 flex items-center gap-1 px-1.5 py-1 rounded bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/[0.06] hover:border-gray-400 dark:hover:border-white/15 transition-colors text-left"
>
<FolderOpen size={10} className="text-gray-500 shrink-0" />
{root ? (
@@ -257,16 +283,16 @@ export function ExplorerPanel({ onApprovePlan }: Props) {
{root && (
<button
onClick={removeFolder}
- disabled={runActive}
+ disabled={!!lockReason}
data-testid="explorer-remove-folder"
+ aria-label="Remove the working directory"
title={
- runActive
- ? 'Wait for the current run to finish, then you can remove the folder.'
- : 'Remove this folder. The agent falls back to its own sandbox until you pick a new one.'
+ lockTitle ||
+ `Remove this folder. The agent falls back to ${fallbackLabel} until you pick a new one.`
}
className="p-1 rounded hover:bg-gray-100 dark:hover:bg-white/5 text-gray-400 dark:text-gray-600 hover:text-red-500 dark:hover:text-red-400 disabled:opacity-30 disabled:hover:text-gray-400 transition-colors shrink-0"
>
- <X size={10} />
+ <FolderX size={11} />
</button>
)}
<button
@@ -293,8 +319,8 @@ export function ExplorerPanel({ onApprovePlan }: Props) {
data-testid="explorer-no-folder"
className="text-[0.5rem] text-gray-400 dark:text-gray-600 px-1 py-2 leading-relaxed"
>
- No folder. The agent works in its own sandbox under ~/agent-workspace.
- Click "Select folder..." above to point it at a project.
+ No folder picked. The agent works in {fallbackLabel} until you
+ click "Select folder..." above.
</p>
) : error ? (
<p className="text-[0.5rem] text-red-500/80 px-1 py-2 break-words">{error}</p>
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 3de1d6be..06850911 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -18,6 +18,7 @@ import { buildHermesToolPrompt, buildHermesToolResult, buildHermesToolCall, pars
import { streamProviderTurn, type StreamedProviderTurn } from '../lib/provider-stream'
import { createHermesDisplayFilter, createThinkStreamSplitter, createTurnThinkingSink } from '../lib/hermes-stream'
import { beginAgentRun, endAgentRun, setActiveAgentModel, type AgentRunContext } from '../api/agent-context'
+import { resolveCodexWorkDir } from '../lib/codex-workdir'
import { resolveChatWorkspaceSlug } from '../api/workspace-slug'
import { codexModeKnobs, CODEX_MODE_LABELS, type CodexMode } from '../lib/codex-mode'
import { CODEX_PLAN_SYSTEM_PROMPT } from '../lib/codex-plan-prompt'
@@ -257,7 +258,7 @@ export function useCodex() {
* another pass on the run they just killed. Cleared when a new run starts. */
const userStoppedRef = useRef(false)
- const sendInstruction = useCallback(async (
+ const runInstruction = useCallback(async (
rawInstruction: string,
opts?: {
displayContent?: string
@@ -268,6 +269,7 @@ export function useCodex() {
const { activeModel } = useModelStore.getState()
if (!activeModel) return
+
// Coding-Agent slash commands (David 2026-06-12): "/review", "/commit",
// "/test", … live HERE, in the Code view, its full file_*/shell/git tools
// + working directory are exactly what these templates drive. Expand the
@@ -353,26 +355,29 @@ export function useCodex() {
defaultWorkspace: settings.defaultWorkspace,
})
- // Init codex thread if needed
- if (!codexStore.getThread(convId)) {
- codexStore.initThread(convId, codexStore.workingDirectory || '.')
+ // Init codex thread if needed. Read LIVE, never from the `codexStore`
+ // snapshot taken at the top of this function: `resolveChatWorkspaceSlug`
+ // above is IPC, and a Remove pressed during it used to be undone here by
+ // a thread born with the old path (A8 review, B1).
+ if (!useCodexStore.getState().getThread(convId)) {
+ useCodexStore.getState().initThread(convId, useCodexStore.getState().workingDirectory)
}
+ // Pull THIS conversation's thread onto the folder the picker shows now.
+ // Only this one: another chat's thread may carry a deliberate per-chat
+ // workspace, and rewriting all of them took that away (A8 review, S5).
+ const liveWorkingDir = useCodexStore.getState().syncThreadWorkingDirectory(convId)
- const thread = codexStore.getThread(convId)!
- // Resolve working directory with this precedence:
- // 1. Explicit codex thread.workingDirectory (file-tree picker)
- // 2. Resolved agent workspace path (when folder-kind)
- // 3. Global codexStore.workingDirectory
- // 4. '.' (bridge's per-chat sandbox)
+ const thread = useCodexStore.getState().getThread(convId)!
const workspacePath =
codexWorkspace && codexWorkspace.kind === 'folder' && codexWorkspace.path
? codexWorkspace.path
: null
- const workDir =
- (thread.workingDirectory && thread.workingDirectory !== '.' ? thread.workingDirectory : null) ||
- workspacePath ||
- codexStore.workingDirectory ||
- '.'
+ // Precedence lives in src/lib/codex-workdir.ts, with its cases tested.
+ const workDir = resolveCodexWorkDir({
+ threadDir: thread.workingDirectory,
+ workspacePath,
+ storeDir: liveWorkingDir,
+ })
// Pin the tool-containment workspace to the SAME folder the model is told
// to use (workDir). resolveWorkspace() above only sees the agent-mode
@@ -2547,6 +2552,32 @@ export function useCodex() {
}
}, [])
+ /**
+ * The public send. Its only job on top of `runInstruction` is to hold the
+ * working directory for the whole turn (A8 review, S1).
+ *
+ * `beginSend` runs SYNCHRONOUSLY, before the first await inside, which is
+ * the point: `setThreadStatus('running')` is five awaits down the page
+ * (workspace slug over IPC, server tool support, token budget, memory
+ * search, .lurules), and both folder buttons used to be free for that whole
+ * stretch. The marker lives out here rather than inside the body because the
+ * body has four early returns and a handful of unguarded awaits: one finally
+ * around the call covers every exit, a thrown error included. A leaked
+ * counter would lock the folder for the rest of the session, which is the
+ * same trap A8 is about.
+ */
+ const sendInstruction = useCallback(async (
+ rawInstruction: string,
+ opts?: Parameters<typeof runInstruction>[1],
+ ) => {
+ useCodexStore.getState().beginSend()
+ try {
+ await runInstruction(rawInstruction, opts)
+ } finally {
+ useCodexStore.getState().endSend()
+ }
+ }, [runInstruction])
+
// Self-reference so the /loop driver can start the next pass. A plain
// recursive call is not possible inside the useCallback that defines it.
const sendRef = useRef<typeof sendInstruction | null>(null)
diff --git a/src/lib/codex-workdir.ts b/src/lib/codex-workdir.ts
new file mode 100644
index 00000000..c978e11d
--- /dev/null
+++ b/src/lib/codex-workdir.ts
@@ -0,0 +1,92 @@
+/**
+ * Where the Coding Agent actually works, and when that may be changed.
+ *
+ * Both halves used to live inline in useCodex and in the two views, which is
+ * how A8 (2.6.8) got as far as it did: the precedence was a three-line boolean
+ * chain nobody could test, and "is a run in flight" was a different expression
+ * on every surface. They are pure functions here, with the tests next to them.
+ */
+
+export interface CodexWorkDirInput {
+ /** The folder pinned on this conversation's thread. */
+ threadDir: string | null | undefined
+ /** Per-chat agent workspace, or settings.defaultWorkspace, when folder-kind. */
+ workspacePath: string | null | undefined
+ /** The folder the Code tab's picker currently shows. */
+ storeDir: string | null | undefined
+}
+
+/** The bridge's per-chat sandbox under ~/agent-workspace. */
+export const CODEX_SANDBOX = '.'
+
+/**
+ * Precedence, unchanged from the inline version it replaces:
+ * 1. the thread's own folder (the picker value, synced at every send)
+ * 2. the resolved agent workspace, when it names a real folder
+ * 3. the picker value again, for a thread that has not been synced yet
+ * 4. the per-chat sandbox
+ *
+ * A thread carrying the literal '.' does NOT count as a pick. It is what
+ * `initThread` writes when there is no folder, and treating it as one used to
+ * hide a per-chat workspace behind a placeholder.
+ */
+export function resolveCodexWorkDir({
+ threadDir,
+ workspacePath,
+ storeDir,
+}: CodexWorkDirInput): string {
+ const fromThread = threadDir && threadDir !== CODEX_SANDBOX ? threadDir : null
+ return fromThread || workspacePath || storeDir || CODEX_SANDBOX
+}
+
+/**
+ * What the agent falls back to when the picker is empty, in the words the user
+ * needs. The empty state used to promise "~/agent-workspace" flat out, which is
+ * a lie for anybody who set a default workspace in Settings or pinned a folder
+ * on this chat: those win over an empty picker (see the precedence above).
+ */
+export function codexFallbackLabel(workspacePath: string | null | undefined): string {
+ return workspacePath || '~/agent-workspace'
+}
+
+/**
+ * Why the working directory is held right now, or null when it is free.
+ *
+ * 'run' a coding turn is in flight, from the moment the send starts.
+ * 'loop' a /loop is standing between two passes: the thread says idle, the
+ * next pass is on a timer, and moving the folder under it would send
+ * that pass somewhere else without anybody watching.
+ */
+export type CodexBusyReason = 'run' | 'loop'
+
+export interface CodexBusyInput {
+ /**
+ * Sends that have started and not yet finished. Counted synchronously at the
+ * top of sendInstruction: the thread status only flips to 'running' after
+ * five awaits (workspace slug, tool support, token budget, memory, rules),
+ * and the whole gap was unlocked before.
+ */
+ sendsInFlight: number
+ /** codexStore.threads, for a turn that is past those awaits. */
+ threads: Record<string, { status: string }>
+ /** agentLoopStore.loop, or null when no /loop is standing. */
+ loop: unknown | null
+}
+
+/**
+ * Only Coding Agent signals count. The first cut read every conversation's
+ * generating flag, so a streaming Chat tab in another conversation locked the
+ * folder picker on Code for no reason at all.
+ */
+export function codexBusyReason({ sendsInFlight, threads, loop }: CodexBusyInput): CodexBusyReason | null {
+ if (sendsInFlight > 0) return 'run'
+ if (Object.values(threads).some((t) => t.status === 'running')) return 'run'
+ if (loop) return 'loop'
+ return null
+}
+
+/** One sentence per reason, so the two buttons cannot drift apart. */
+export const CODEX_WORKDIR_LOCK_TITLE: Record<CodexBusyReason, string> = {
+ run: 'Wait for the current run to finish, then you can change the folder.',
+ loop: 'A loop is still running. Stop it first, then you can change the folder.',
+}
diff --git a/src/stores/codexStore.ts b/src/stores/codexStore.ts
index 5d2279b2..91e3fa12 100644
--- a/src/stores/codexStore.ts
+++ b/src/stores/codexStore.ts
@@ -47,21 +47,45 @@ interface CodexState {
/** 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. It also re-pins every EXISTING thread,
- * because a thread copies the folder once at init and never looked at the
- * store again: a mis-click used to stay the agent's root for the rest of the
- * conversation, no matter what the picker said afterwards (A8, 2.6.8).
+ * 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. Same re-pin as above, so the current conversation
- * falls back to its per-chat sandbox instead of staying attached to a tree
- * the user never meant to open. The empty string is persisted on purpose:
- * a restart must not resurrect the folder (A8, 2.6.8).
+ * 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
/**
@@ -89,40 +113,12 @@ function omit<T>(map: Record<string, T>, key: string): Record<string, T> {
return next
}
-/**
- * Point every open thread at `dir`.
- *
- * `initThread` copies the store's folder into the thread ONCE, and the run
- * resolver prefers `thread.workingDirectory` over the store. Without this the
- * store and the thread drift apart the moment the user picks again, which is
- * exactly what A8 reads like from the outside: the picker says one folder, the
- * agent keeps walking the old one, and clearing the store changes nothing.
- *
- * Returns the SAME object when there is nothing to change, so a no-op set does
- * not re-render every subscriber.
- */
-function pinThreads(
- threads: Record<string, CodexThread>,
- dir: string,
-): Record<string, CodexThread> {
- let changed = false
- const next: Record<string, CodexThread> = {}
- for (const [id, thread] of Object.entries(threads)) {
- if (thread.workingDirectory === dir) {
- next[id] = thread
- continue
- }
- next[id] = { ...thread, workingDirectory: dir }
- changed = true
- }
- return changed ? next : threads
-}
-
export const useCodexStore = create<CodexState>()(
persist(
(set, get) => ({
chatMode: 'lu',
threads: {},
+ sendsInFlight: 0,
workingDirectory: '',
fileTreeVersion: 0,
modeByConversation: {},
@@ -130,14 +126,33 @@ export const useCodexStore = create<CodexState>()(
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((state) => ({ workingDirectory: dir, threads: pinThreads(state.threads, dir) })),
+ 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((state) => ({ workingDirectory: '', threads: pinThreads(state.threads, '') })),
+ 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) =>