From fb9e3c89b2b4670a0eded99e7567e578ac6e502c Mon Sep 17 00:00:00 2001 From: Lifei Zhou Date: Mon, 19 Oct 2026 00:48:55 +0000 Subject: [PATCH] fix(desktop): inherit active chat folder for New Chat (#12941) --- ui/desktop/src/App.test.tsx | 49 ++++++++++++++++++- ui/desktop/src/App.tsx | 14 +++++- ui/desktop/src/components/Hub.test.tsx | 29 +++++++++-- ui/desktop/src/components/Hub.tsx | 13 +++-- ui/desktop/src/main.ts | 2 +- .../src/utils/__tests__/workingDir.test.ts | 4 ++ ui/desktop/src/utils/workingDir.ts | 4 +- 7 files changed, 101 insertions(+), 14 deletions(-) diff --git a/ui/desktop/src/App.test.tsx b/ui/desktop/src/App.test.tsx index 162304818..db55e4661 100644 --- a/ui/desktop/src/App.test.tsx +++ b/ui/desktop/src/App.test.tsx @@ -12,6 +12,8 @@ import { FeaturesProvider } from './contexts/FeaturesContext'; import { reconnectAcpAfterSystemResume } from './acp/acpConnection'; import { createSession } from './sessions'; import { RecipeParameterScopesUnsupportedError } from './acp/errors'; +import { acpChatSessionActions, acpChatSessionStore } from './acp/chatSessionStore'; +import type { Session } from './types/session'; const mockToastError = vi.hoisted(() => vi.fn()); @@ -144,6 +146,7 @@ vi.mock('./components/AnnouncementModal', () => ({ const mockNavigate = vi.fn(); const mockSearchParams = new URLSearchParams(); const mockSetSearchParams = vi.fn(); +const mockLocation = { state: null, pathname: '/', search: '' }; // Mock react-router to avoid HashRouter issues in tests vi.mock('react-router', () => ({ @@ -151,7 +154,7 @@ vi.mock('react-router', () => ({ Routes: ({ children }: { children: React.ReactNode }) => <>{children}, Route: ({ element }: { element: React.ReactNode }) => element, useNavigate: () => mockNavigate, - useLocation: () => ({ state: null, pathname: '/' }), + useLocation: () => mockLocation, useSearchParams: () => [mockSearchParams, mockSetSearchParams], Outlet: () => null, })); @@ -213,6 +216,8 @@ describe('App Component - Brand New State', () => { vi.clearAllMocks(); mockNavigate.mockClear(); mockSetSearchParams.mockClear(); + mockLocation.pathname = '/'; + mockLocation.search = ''; mockAppConfig.get.mockImplementation((key: string): string | null => { if (key === 'GOOSE_WORKING_DIR') return '/test/dir'; return null; @@ -230,6 +235,8 @@ describe('App Component - Brand New State', () => { afterEach(() => { vi.clearAllMocks(); + acpChatSessionActions.deleteSnapshot('website'); + acpChatSessionActions.deleteSnapshot('payments'); }); it('should redirect to "/" when app is brand new (no provider configured)', async () => { @@ -313,6 +320,7 @@ describe('App Component - Brand New State', () => { }); it('should navigate home when the main process emits new-chat', async () => { + mockLocation.pathname = '/sessions'; mockElectron.getConfig.mockReturnValue({ GOOSE_DEFAULT_PROVIDER: 'openai', GOOSE_DEFAULT_MODEL: 'gpt-4', @@ -332,7 +340,44 @@ describe('App Component - Brand New State', () => { newChatHandler?.({} as any); - expect(mockNavigate).toHaveBeenCalledWith('/'); + expect(mockNavigate).toHaveBeenCalledWith('/', { state: { workingDir: undefined } }); + }); + + it('inherits the active session folder without changing other sessions', async () => { + mockLocation.pathname = '/pair'; + mockLocation.search = '?resumeSessionId=website'; + acpChatSessionActions.setSessionMetadata('website', { + id: 'website', + working_dir: '/projects/website', + } as Session); + acpChatSessionActions.setSessionMetadata('payments', { + id: 'payments', + working_dir: '/projects/payments', + } as Session); + + render(, { wrapper: AppInnerTestWrapper }); + + await waitFor(() => expect(mockElectron.reactReady).toHaveBeenCalled()); + + // Read the folder at shortcut time, including a change made since the render. + acpChatSessionActions.setSessionMetadata('website', { + id: 'website', + working_dir: '/projects/website/frontend', + } as Session); + const newChatHandler = mockElectron.on.mock.calls.find( + ([channel]) => channel === 'new-chat' + )?.[1]; + newChatHandler?.({} as any); + + expect(mockNavigate).toHaveBeenCalledWith('/', { + state: { workingDir: '/projects/website/frontend' }, + }); + expect(acpChatSessionStore.getSnapshot('website')?.session?.working_dir).toBe( + '/projects/website/frontend' + ); + expect(acpChatSessionStore.getSnapshot('payments')?.session?.working_dir).toBe( + '/projects/payments' + ); }); it('should reconnect ACP when the main process emits system-resume', async () => { diff --git a/ui/desktop/src/App.tsx b/ui/desktop/src/App.tsx index 9e52fa6fc..42201a235 100644 --- a/ui/desktop/src/App.tsx +++ b/ui/desktop/src/App.tsx @@ -16,6 +16,7 @@ import TelemetryConsentPrompt from './components/TelemetryConsentPrompt'; import OnboardingGuard from './components/onboarding/OnboardingGuard'; import { createSession } from './sessions'; import { acpListSessions, acpDeleteSession } from './acp/sessions'; +import { acpChatSessionStore } from './acp/chatSessionStore'; import { ChatType } from './types/chat'; import Hub from './components/Hub'; @@ -545,12 +546,21 @@ export function AppInner() { useEffect(() => { const handleNewChat = (_event: IpcRendererEvent, ..._args: unknown[]) => { - navigate('/'); + if (location.pathname === '/') return; + + const sessionId = + location.pathname === '/pair' + ? new URLSearchParams(location.search).get('resumeSessionId') + : null; + const workingDir = sessionId + ? acpChatSessionStore.getSnapshot(sessionId)?.session?.working_dir + : undefined; + navigate('/', { state: { workingDir } }); }; window.electron.on('new-chat', handleNewChat); return () => window.electron.off('new-chat', handleNewChat); - }, [navigate]); + }, [navigate, location.pathname, location.search]); useEffect(() => { const handleFocusInput = (_event: IpcRendererEvent, ..._args: unknown[]) => { diff --git a/ui/desktop/src/components/Hub.test.tsx b/ui/desktop/src/components/Hub.test.tsx index fbf930ddd..bde1c3521 100644 --- a/ui/desktop/src/components/Hub.test.tsx +++ b/ui/desktop/src/components/Hub.test.tsx @@ -3,6 +3,7 @@ */ import { act, render, waitFor } from '@testing-library/react'; import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { MemoryRouter } from 'react-router'; import Hub from './Hub'; import { IntlTestWrapper } from '../i18n/test-utils'; import { createSession } from '../sessions'; @@ -14,6 +15,8 @@ import type { LiveVoiceController } from '../liveVoice/useLiveVoice'; type ChatInputCapture = { draftRef?: { current: string }; handleSubmit: (input: UserInput) => void; + workingDir: string; + onWorkingDirChange: (dir: string) => void; liveVoice?: { availability: { status: string; message: string } | null; start: () => Promise; @@ -52,7 +55,8 @@ vi.mock('../sessions', () => ({ createSession: vi.fn() })); vi.mock('../utils/workingDir', () => ({ getInitialWorkingDir: () => '/tmp/goose', - getEffectiveWorkingDir: () => Promise.resolve('/tmp/goose'), + getEffectiveWorkingDir: (inheritedWorkingDir?: string) => + Promise.resolve(inheritedWorkingDir ?? '/tmp/goose'), })); vi.mock('../utils/nextChatExtensions', () => ({ @@ -84,10 +88,12 @@ function pendingSession() { return settle; } -function renderHub(draftRef: { current: string }, setView = vi.fn()) { +function renderHub(draftRef: { current: string }, setView = vi.fn(), initialWorkingDir?: string) { return render( - + + + ); } @@ -109,6 +115,23 @@ describe('Hub', () => { vi.mocked(subscribeToAcpRecovery).mockReturnValue(() => undefined); }); + it.each([undefined, '/projects/payments'])( + 'starts in the inherited folder unless another folder is selected (%s)', + async (selectedDir) => { + vi.mocked(createSession).mockResolvedValue({ id: 'session-1' } as Session); + renderHub({ current: '' }, vi.fn(), '/projects/website'); + + await waitFor(() => expect(captured.chatInput?.workingDir).toBe('/projects/website')); + if (selectedDir) { + await act(async () => captured.chatInput?.onWorkingDirChange(selectedDir)); + } + await submit(); + expect(createSession).toHaveBeenCalledWith(selectedDir ?? '/projects/website', { + allExtensions: [], + }); + } + ); + it('requests Live voice availability again after ACP recovers', async () => { let recoveryChanged: ((recovering: boolean) => void) | undefined; const available = { status: 'ready' as const, message: 'Start Live voice' }; diff --git a/ui/desktop/src/components/Hub.tsx b/ui/desktop/src/components/Hub.tsx index c84230c7b..ec4c28df1 100644 --- a/ui/desktop/src/components/Hub.tsx +++ b/ui/desktop/src/components/Hub.tsx @@ -8,6 +8,7 @@ */ import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from 'react'; +import { useLocation } from 'react-router'; import { defineMessages, useIntl } from '../i18n'; import { AppEvents } from '../constants/events'; import ChatInput from './ChatInput'; @@ -60,8 +61,10 @@ export default function Hub({ liveVoice: LiveVoiceController; }) { const intl = useIntl(); + const { state } = useLocation(); + const initialWorkingDir = (state as { workingDir?: string } | null)?.workingDir; const { extensionsList } = useConfig(); - const [workingDir, setWorkingDir] = useState(getInitialWorkingDir()); + const [workingDir, setWorkingDir] = useState(initialWorkingDir ?? getInitialWorkingDir()); const userSelectedWorkingDirRef = useRef(false); const [isCreatingSession, setIsCreatingSession] = useState(false); const [liveVoiceAvailability, setLiveVoiceAvailability] = @@ -75,13 +78,13 @@ export default function Hub({ // creation, so a configured remote directory may have changed since then. useEffect(() => { let active = true; - void getEffectiveWorkingDir().then((dir) => { + void getEffectiveWorkingDir(initialWorkingDir).then((dir) => { if (active && !userSelectedWorkingDirRef.current) setWorkingDir(dir); }); return () => { active = false; }; - }, []); + }, [initialWorkingDir]); useEffect(() => { let requestGeneration = 0; @@ -155,7 +158,9 @@ export default function Hub({ // Resolve the effective directory at submit time: the IPC lookup may still // be pending when the user submits, and an explicit pick must win. - const dir = userSelectedWorkingDirRef.current ? workingDir : await getEffectiveWorkingDir(); + const dir = userSelectedWorkingDirRef.current + ? workingDir + : await getEffectiveWorkingDir(initialWorkingDir); const session = await createSession(dir, sessionOptions); setNextChatExtensionDraft(null); return session; diff --git a/ui/desktop/src/main.ts b/ui/desktop/src/main.ts index 49313996d..a9d020d4f 100644 --- a/ui/desktop/src/main.ts +++ b/ui/desktop/src/main.ts @@ -2603,7 +2603,7 @@ async function appMain() { accelerator: shortcuts.newChat, click() { const focusedWindow = BrowserWindow.getFocusedWindow(); - if (focusedWindow) focusedWindow.webContents.send('set-view', ''); + if (focusedWindow) focusedWindow.webContents.send('new-chat'); }, }) ); diff --git a/ui/desktop/src/utils/__tests__/workingDir.test.ts b/ui/desktop/src/utils/__tests__/workingDir.test.ts index 32829c55a..f4c1d7738 100644 --- a/ui/desktop/src/utils/__tests__/workingDir.test.ts +++ b/ui/desktop/src/utils/__tests__/workingDir.test.ts @@ -42,6 +42,9 @@ describe('getEffectiveWorkingDir', () => { workingDir: ' /home/goose/workspace ', }); await expect(getEffectiveWorkingDir()).resolves.toBe('/home/goose/workspace'); + await expect(getEffectiveWorkingDir('/home/goose/previous-project')).resolves.toBe( + '/home/goose/workspace' + ); }); it('honors the configured remote directory for env-mode backends regardless of enabled/url', async () => { @@ -64,6 +67,7 @@ describe('getEffectiveWorkingDir', () => { mockWindow(false, ''); getSettingMock.mockResolvedValue({ enabled: true, workingDir: '/home/goose/workspace' }); await expect(getEffectiveWorkingDir()).resolves.toBe('/Users/johannes/home/workspace'); + await expect(getEffectiveWorkingDir('/projects/website')).resolves.toBe('/projects/website'); }); it('falls back to the remembered directory when the bound backend no longer matches settings', async () => { diff --git a/ui/desktop/src/utils/workingDir.ts b/ui/desktop/src/utils/workingDir.ts index a0465208f..bac22cdf7 100644 --- a/ui/desktop/src/utils/workingDir.ts +++ b/ui/desktop/src/utils/workingDir.ts @@ -18,8 +18,8 @@ export const getInitialWorkingDir = (): string => { * use the configured directory (matching getActiveExternalBackend), while * settings-mode backends require the window-bound backend to still match. */ -export const getEffectiveWorkingDir = async (): Promise => { - const initial = getInitialWorkingDir(); +export const getEffectiveWorkingDir = async (inheritedWorkingDir?: string): Promise => { + const initial = inheritedWorkingDir ?? getInitialWorkingDir(); const boundUrl = window.appConfig?.get('GOOSE_EXTERNAL_BACKEND_URL') as string | undefined; const source = window.appConfig?.get('GOOSE_EXTERNAL_BACKEND_SOURCE') as string | undefined; if (window.appConfig?.get('GOOSE_EXTERNAL_BACKEND') !== true || !boundUrl) {