diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index f28aacac6174252eb3777705c59773abbd16a556..bc14843cf4c46180b6755a2fb00ab95a4668c21f 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -108,6 +108,12 @@ export default function BranchToolbar({ envMode, onEnvModeChange, envLocked }: B const setThreadBranch = (branch: string | null, worktreePath: string | null) => { if (!activeThreadId) return; + // If the effective cwd is about to change, stop the running session so the + // next message creates a new one with the correct cwd. + const sessionId = activeThread?.session?.sessionId; + if (sessionId && worktreePath !== activeWorktreePath) { + void api?.providers.stopSession({ sessionId }).catch(() => undefined); + } dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath }); }; diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 2ac4e173a8a95914d0f2a3f05799c7ee2b5260dc..a073c924289899daf7745e39785d76b056a983d3 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -376,15 +376,23 @@ export function reducer(state: AppState, action: Action): AppState { })), }; - case "SET_THREAD_BRANCH": + case "SET_THREAD_BRANCH": { return { ...state, - threads: updateThread(state.threads, action.threadId, (t) => ({ - ...t, - branch: action.branch, - worktreePath: action.worktreePath, - })), + threads: updateThread(state.threads, action.threadId, (t) => { + // When the effective cwd changes (worktreePath differs), the old + // session is no longer valid — clear it so ensureSession creates a + // new one with the correct cwd on the next message. + const cwdChanged = t.worktreePath !== action.worktreePath; + return { + ...t, + branch: action.branch, + worktreePath: action.worktreePath, + ...(cwdChanged ? { session: null } : {}), + }; + }), }; + } case "SET_RUNTIME_MODE": return {