fix(desktop): inherit active chat folder for New Chat (#12941)

This commit is contained in:
Lifei Zhou
2026-10-19 00:48:55 +00:00
committed by GitHub
parent 22413aba4f
commit fb9e3c89b2
7 changed files with 101 additions and 14 deletions
+47 -2
View File
@@ -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(<AppInner />, { 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 () => {
+12 -2
View File
@@ -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[]) => {
+26 -3
View File
@@ -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<void>;
@@ -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(
<IntlTestWrapper>
<Hub setView={setView} draftRef={draftRef} liveVoice={liveVoice} />
<MemoryRouter initialEntries={[{ pathname: '/', state: { workingDir: initialWorkingDir } }]}>
<Hub setView={setView} draftRef={draftRef} liveVoice={liveVoice} />
</MemoryRouter>
</IntlTestWrapper>
);
}
@@ -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' };
+9 -4
View File
@@ -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;
+1 -1
View File
@@ -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');
},
})
);
@@ -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 () => {
+2 -2
View File
@@ -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<string> => {
const initial = getInitialWorkingDir();
export const getEffectiveWorkingDir = async (inheritedWorkingDir?: string): Promise<string> => {
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) {