fix: 修复 AI 设计会话失效后的伪登录

问题:Main 刷新令牌返回 401 后已清空会话,但 Renderer 仍保留用户信息,AI 设计持续返回 AUTH_REQUIRED。

实现:认证初始化等待 Main 同步完成;同步或刷新失败清理登录态;Workspace 识别结构化认证错误并在重新登录后恢复加载;路由守卫响应登录状态变化。

验证:49 个聚焦测试通过,TypeScript、聚焦 Lint 与 Vite 生产构建通过。
This commit is contained in:
2026-08-01 09:37:23 +08:00
parent 1e23028b4b
commit 592bdfbc70
8 changed files with 328 additions and 62 deletions

View File

@@ -123,7 +123,7 @@ function ProtectedLayout({
setupReady: boolean; setupReady: boolean;
}) { }) {
const location = useLocation(); const location = useLocation();
const isAuthenticated = useAuthStore((state) => state.isAuthenticated); const authenticated = useAuthStore((state) => state.isAuthenticated());
const allowsAnonymousImageWorkspace = imageWorkspaceLocalDevelopment const allowsAnonymousImageWorkspace = imageWorkspaceLocalDevelopment
&& (location.pathname === '/' && (location.pathname === '/'
|| location.pathname === '/image-canvas' || location.pathname === '/image-canvas'
@@ -137,7 +137,7 @@ function ProtectedLayout({
return <StartupScreen />; return <StartupScreen />;
} }
if (authRequired && !allowsAnonymousImageWorkspace && !isAuthenticated()) { if (authRequired && !allowsAnonymousImageWorkspace && !authenticated) {
return ( return (
<Navigate <Navigate
to="/login" to="/login"
@@ -161,7 +161,7 @@ function ProtectedModuleSelection({
imageWorkspaceLocalDevelopment: boolean; imageWorkspaceLocalDevelopment: boolean;
setupReady: boolean; setupReady: boolean;
}) { }) {
const isAuthenticated = useAuthStore((state) => state.isAuthenticated); const authenticated = useAuthStore((state) => state.isAuthenticated());
if (!setupReady) { if (!setupReady) {
return <StartupScreen />; return <StartupScreen />;
@@ -171,7 +171,7 @@ function ProtectedModuleSelection({
return <StartupScreen />; return <StartupScreen />;
} }
if (authRequired && !imageWorkspaceLocalDevelopment && !isAuthenticated()) { if (authRequired && !imageWorkspaceLocalDevelopment && !authenticated) {
return <Navigate to="/login" replace state={{ from: AI_MODULE_SELECTION_PATH }} />; return <Navigate to="/login" replace state={{ from: AI_MODULE_SELECTION_PATH }} />;
} }
@@ -242,14 +242,14 @@ function App() {
const initProviders = useProviderStore((state) => state.init); const initProviders = useProviderStore((state) => state.init);
const initAuth = useAuthStore((state) => state.init); const initAuth = useAuthStore((state) => state.init);
const authInitialized = useAuthStore((state) => state.initialized); const authInitialized = useAuthStore((state) => state.initialized);
const isAuthenticated = useAuthStore((state) => state.isAuthenticated); const authenticated = useAuthStore((state) => state.isAuthenticated());
const bootstrapUserSync = useUserSyncStore((state) => state.bootstrap); const bootstrapUserSync = useUserSyncStore((state) => state.bootstrap);
const setupReady = setupComplete || skipSetupForE2E || rendererOnlyPreview; const setupReady = setupComplete || skipSetupForE2E || rendererOnlyPreview;
const authRequired = !skipSetupForE2E && !rendererOnlyPreview; const authRequired = !skipSetupForE2E && !rendererOnlyPreview;
const imageWorkspaceLocalDevelopment = window.electron?.imageWorkspaceLocalDevelopment === true; const imageWorkspaceLocalDevelopment = window.electron?.imageWorkspaceLocalDevelopment === true;
useEffect(() => { useEffect(() => {
initAuth(); void initAuth();
}, [initAuth]); }, [initAuth]);
useEffect(() => { useEffect(() => {
@@ -274,9 +274,9 @@ function App() {
if (rendererOnlyPreview) return; if (rendererOnlyPreview) return;
if (!setupReady) return; if (!setupReady) return;
if (!authInitialized) return; if (!authInitialized) return;
if (!isAuthenticated()) return; if (!authenticated) return;
void bootstrapUserSync(); void bootstrapUserSync();
}, [authInitialized, bootstrapUserSync, isAuthenticated, rendererOnlyPreview, setupReady]); }, [authenticated, authInitialized, bootstrapUserSync, rendererOnlyPreview, setupReady]);
// Redirect to setup wizard if not complete // Redirect to setup wizard if not complete
useEffect(() => { useEffect(() => {

View File

@@ -19,6 +19,7 @@ import {
import { IMAGE_WORKSPACE_CREATE_PROJECT_EVENT } from '@/lib/image-workspace'; import { IMAGE_WORKSPACE_CREATE_PROJECT_EVENT } from '@/lib/image-workspace';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { useImageWorkspaceStore } from '@/stores/image-workspace'; import { useImageWorkspaceStore } from '@/stores/image-workspace';
import { useAuthStore } from '@/stores/auth';
import type { DesignWorkspaceSummary } from '../../../shared/image-workspace'; import type { DesignWorkspaceSummary } from '../../../shared/image-workspace';
type ImageWorkspaceSidebarProps = { type ImageWorkspaceSidebarProps = {
@@ -30,6 +31,7 @@ type ProjectDialogState =
| { mode: 'rename'; project: DesignWorkspaceSummary }; | { mode: 'rename'; project: DesignWorkspaceSummary };
export function ImageWorkspaceSidebar({ sidebarCollapsed }: ImageWorkspaceSidebarProps) { export function ImageWorkspaceSidebar({ sidebarCollapsed }: ImageWorkspaceSidebarProps) {
const authenticated = useAuthStore((state) => state.isAuthenticated());
const navigate = useNavigate(); const navigate = useNavigate();
const status = useImageWorkspaceStore((state) => state.status); const status = useImageWorkspaceStore((state) => state.status);
const bootstrap = useImageWorkspaceStore((state) => state.bootstrap); const bootstrap = useImageWorkspaceStore((state) => state.bootstrap);
@@ -46,8 +48,8 @@ export function ImageWorkspaceSidebar({ sidebarCollapsed }: ImageWorkspaceSideba
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
useEffect(() => { useEffect(() => {
if (status === 'idle') void load(); if (status === 'idle' || (status === 'auth-required' && authenticated)) void load();
}, [load, status]); }, [authenticated, load, status]);
useEffect(() => { useEffect(() => {
const openCreateDialog = () => { const openCreateDialog = () => {
@@ -154,7 +156,7 @@ export function ImageWorkspaceSidebar({ sidebarCollapsed }: ImageWorkspaceSideba
</div> </div>
) : null} ) : null}
{status === 'unavailable' || status === 'error' ? ( {status === 'unavailable' || status === 'error' || status === 'auth-required' ? (
<div <div
data-testid="sidebar-image-workspace-unavailable" data-testid="sidebar-image-workspace-unavailable"
className="rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-3 text-xs font-medium text-muted-foreground" className="rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-3 text-xs font-medium text-muted-foreground"

View File

@@ -27,6 +27,7 @@ import {
} from '@/lib/image-workspace'; } from '@/lib/image-workspace';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { useImageWorkspaceStore } from '@/stores/image-workspace'; import { useImageWorkspaceStore } from '@/stores/image-workspace';
import { useAuthStore } from '@/stores/auth';
import type { import type {
DesignAsset, DesignAsset,
DesignGenerationQuote, DesignGenerationQuote,
@@ -184,6 +185,7 @@ function QuoteCard({
} }
export function ImageCanvas() { export function ImageCanvas() {
const authenticated = useAuthStore((state) => state.isAuthenticated());
const status = useImageWorkspaceStore((state) => state.status); const status = useImageWorkspaceStore((state) => state.status);
const bootstrap = useImageWorkspaceStore((state) => state.bootstrap); const bootstrap = useImageWorkspaceStore((state) => state.bootstrap);
const workspace = useImageWorkspaceStore((state) => state.workspace); const workspace = useImageWorkspaceStore((state) => state.workspace);
@@ -207,8 +209,8 @@ export function ImageCanvas() {
const hasActiveTasks = tasks.some((task) => ACTIVE_TASK_STATUSES.has(task.status)); const hasActiveTasks = tasks.some((task) => ACTIVE_TASK_STATUSES.has(task.status));
useEffect(() => { useEffect(() => {
if (status === 'idle') void load(); if (status === 'idle' || (status === 'auth-required' && authenticated)) void load();
}, [load, status]); }, [authenticated, load, status]);
useEffect(() => { useEffect(() => {
if (!hasActiveTasks || !workspace) return; if (!hasActiveTasks || !workspace) return;

View File

@@ -46,10 +46,11 @@ type AuthState = {
tokenType: string | null; tokenType: string | null;
expiresAt: number | null; expiresAt: number | null;
user: AuthUser | null; user: AuthUser | null;
init: () => void; init: () => Promise<void>;
loginWithBrowser: () => Promise<void>; loginWithBrowser: () => Promise<void>;
refreshSession: () => Promise<string | null>; refreshSession: () => Promise<string | null>;
getValidAccessToken: () => Promise<string | null>; getValidAccessToken: () => Promise<string | null>;
invalidateSession: (message?: string) => void;
logout: () => Promise<void>; logout: () => Promise<void>;
isAuthenticated: () => boolean; isAuthenticated: () => boolean;
}; };
@@ -120,10 +121,10 @@ async function syncMainSession(session: {
refreshToken: string | null; refreshToken: string | null;
tokenType: string | null; tokenType: string | null;
expiresAt: number | null; expiresAt: number | null;
}): Promise<void> { }): Promise<boolean> {
if (!session.accessToken) return; if (!session.accessToken) return false;
try { try {
await hostApiFetch<AuthActionResponse>('/api/auth/session/sync', { const response = await hostApiFetch<AuthActionResponse>('/api/auth/session/sync', {
method: 'POST', method: 'POST',
body: JSON.stringify({ body: JSON.stringify({
accessToken: session.accessToken, accessToken: session.accessToken,
@@ -132,8 +133,9 @@ async function syncMainSession(session: {
expiresAt: session.expiresAt, expiresAt: session.expiresAt,
}), }),
}); });
return response.success;
} catch { } catch {
// The renderer session remains authoritative for UI; Main can resync later. return false;
} }
} }
@@ -147,8 +149,9 @@ export const useAuthStore = create<AuthState>()(
clientId: DEFAULT_CLIENT_ID, clientId: DEFAULT_CLIENT_ID,
...getClearedSession(), ...getClearedSession(),
init: () => { init: async () => {
const state = get(); const state = get();
if (state.loading && !state.initialized) return;
const authBaseChanged = Boolean( const authBaseChanged = Boolean(
state.authBase state.authBase
&& trimTrailingSlash(state.authBase) !== trimTrailingSlash(DEFAULT_AUTH_BASE), && trimTrailingSlash(state.authBase) !== trimTrailingSlash(DEFAULT_AUTH_BASE),
@@ -159,21 +162,36 @@ export const useAuthStore = create<AuthState>()(
&& state.expiresAt <= Date.now() + TOKEN_EXPIRY_SKEW_MS, && state.expiresAt <= Date.now() + TOKEN_EXPIRY_SKEW_MS,
); );
set({ set({
initialized: true, initialized: false,
loading: false, loading: false,
error: null, error: null,
authBase: DEFAULT_AUTH_BASE, authBase: DEFAULT_AUTH_BASE,
clientId: DEFAULT_CLIENT_ID, clientId: DEFAULT_CLIENT_ID,
...(expired || authBaseChanged ? getClearedSession() : {}), ...(expired || authBaseChanged ? getClearedSession() : {}),
}); });
if (!expired && !authBaseChanged && state.accessToken) {
void syncMainSession({ if (expired || authBaseChanged || !state.accessToken) {
set({ initialized: true });
return;
}
set({ loading: true });
const synchronized = await syncMainSession({
accessToken: state.accessToken, accessToken: state.accessToken,
refreshToken: state.refreshToken, refreshToken: state.refreshToken,
tokenType: state.tokenType, tokenType: state.tokenType,
expiresAt: state.expiresAt, expiresAt: state.expiresAt,
}); });
if (!synchronized) {
set({
initialized: true,
loading: false,
error: '登录状态恢复失败,请重新登录。',
...getClearedSession(),
});
return;
} }
set({ initialized: true, loading: false });
}, },
loginWithBrowser: async () => { loginWithBrowser: async () => {
@@ -199,7 +217,9 @@ export const useAuthStore = create<AuthState>()(
clientId, clientId,
...session, ...session,
}); });
await syncMainSession(session); if (!await syncMainSession(session)) {
throw new Error('Failed to synchronize the signed-in session');
}
} catch (error) { } catch (error) {
const message = error instanceof Error ? error.message : String(error); const message = error instanceof Error ? error.message : String(error);
set({ loading: false, error: message, ...getClearedSession() }); set({ loading: false, error: message, ...getClearedSession() });
@@ -228,11 +248,18 @@ export const useAuthStore = create<AuthState>()(
error: null, error: null,
...session, ...session,
}); });
await syncMainSession(session); if (!await syncMainSession(session)) {
throw new Error('Failed to synchronize the refreshed session');
}
return session.accessToken; return session.accessToken;
} catch (error) { } catch (error) {
const message = error instanceof Error ? error.message : String(error); const message = error instanceof Error ? error.message : String(error);
set({ loading: false, error: message }); set({
initialized: true,
loading: false,
error: message,
...getClearedSession(),
});
return null; return null;
} }
}, },
@@ -252,6 +279,15 @@ export const useAuthStore = create<AuthState>()(
return accessToken; return accessToken;
}, },
invalidateSession: (message = '登录已过期,请重新登录。') => {
set({
initialized: true,
loading: false,
error: message,
...getClearedSession(),
});
},
logout: async () => { logout: async () => {
const { accessToken } = get(); const { accessToken } = get();
try { try {

View File

@@ -9,6 +9,7 @@ import {
renameImageWorkspaceProject, renameImageWorkspaceProject,
sendImageWorkspaceMessage, sendImageWorkspaceMessage,
} from '@/lib/image-workspace'; } from '@/lib/image-workspace';
import { useAuthStore } from '@/stores/auth';
import { import {
IMAGE_WORKSPACE_UNAVAILABLE_CODE, IMAGE_WORKSPACE_UNAVAILABLE_CODE,
type DesignGenerationTask, type DesignGenerationTask,
@@ -17,7 +18,13 @@ import {
type DesignWorkspaceSummary, type DesignWorkspaceSummary,
} from '../../shared/image-workspace'; } from '../../shared/image-workspace';
export type ImageWorkspaceLoadStatus = 'idle' | 'loading' | 'ready' | 'unavailable' | 'error'; export type ImageWorkspaceLoadStatus =
| 'idle'
| 'loading'
| 'ready'
| 'unavailable'
| 'error'
| 'auth-required';
type ImageWorkspaceState = { type ImageWorkspaceState = {
status: ImageWorkspaceLoadStatus; status: ImageWorkspaceLoadStatus;
@@ -44,6 +51,10 @@ function unavailable(error: unknown): boolean {
&& (error.status === 501 || error.code === IMAGE_WORKSPACE_UNAVAILABLE_CODE); && (error.status === 501 || error.code === IMAGE_WORKSPACE_UNAVAILABLE_CODE);
} }
function authenticationRequired(error: unknown): boolean {
return error instanceof ImageWorkspaceApiError && error.code === 'AUTH_REQUIRED';
}
function messageOf(error: unknown): string { function messageOf(error: unknown): string {
return error instanceof Error ? error.message : String(error); return error instanceof Error ? error.message : String(error);
} }
@@ -69,6 +80,22 @@ function upsertSummary(
} }
export const useImageWorkspaceStore = create<ImageWorkspaceState>((set, get) => { export const useImageWorkspaceStore = create<ImageWorkspaceState>((set, get) => {
const handleRequestError = (error: unknown): string => {
const message = messageOf(error);
if (authenticationRequired(error)) {
useAuthStore.getState().invalidateSession();
set({
status: 'auth-required',
bootstrap: null,
activeWorkspaceId: null,
workspace: null,
tasks: [],
error: message,
});
}
return message;
};
const applyWorkspace = (workspace: DesignWorkspace): DesignWorkspace => { const applyWorkspace = (workspace: DesignWorkspace): DesignWorkspace => {
set((state) => ({ set((state) => ({
status: 'ready', status: 'ready',
@@ -139,14 +166,17 @@ export const useImageWorkspaceStore = create<ImageWorkspaceState>((set, get) =>
if (activeWorkspaceId) await loadWorkspace(activeWorkspaceId); if (activeWorkspaceId) await loadWorkspace(activeWorkspaceId);
return bootstrap; return bootstrap;
} catch (error) { } catch (error) {
const message = handleRequestError(error);
if (!authenticationRequired(error)) {
set({ set({
status: unavailable(error) ? 'unavailable' : 'error', status: unavailable(error) ? 'unavailable' : 'error',
bootstrap: null, bootstrap: null,
activeWorkspaceId: null, activeWorkspaceId: null,
workspace: null, workspace: null,
tasks: [], tasks: [],
error: messageOf(error), error: message,
}); });
}
return null; return null;
} finally { } finally {
inFlightLoad = null; inFlightLoad = null;
@@ -161,7 +191,7 @@ export const useImageWorkspaceStore = create<ImageWorkspaceState>((set, get) =>
set({ tasks: [] }); set({ tasks: [] });
return workspace; return workspace;
} catch (error) { } catch (error) {
set({ error: messageOf(error) }); set({ error: handleRequestError(error) });
throw error; throw error;
} }
}, },
@@ -170,7 +200,7 @@ export const useImageWorkspaceStore = create<ImageWorkspaceState>((set, get) =>
try { try {
return applyWorkspace(await renameImageWorkspaceProject(workspaceId, title)); return applyWorkspace(await renameImageWorkspaceProject(workspaceId, title));
} catch (error) { } catch (error) {
set({ error: messageOf(error) }); set({ error: handleRequestError(error) });
throw error; throw error;
} }
}, },
@@ -186,7 +216,7 @@ export const useImageWorkspaceStore = create<ImageWorkspaceState>((set, get) =>
try { try {
await loadWorkspace(workspaceId); await loadWorkspace(workspaceId);
} catch (error) { } catch (error) {
set({ error: messageOf(error) }); set({ error: handleRequestError(error) });
} }
}, },
@@ -196,7 +226,7 @@ export const useImageWorkspaceStore = create<ImageWorkspaceState>((set, get) =>
try { try {
return applyWorkspace(await fetchImageWorkspaceProject(workspaceId)); return applyWorkspace(await fetchImageWorkspaceProject(workspaceId));
} catch (error) { } catch (error) {
set({ error: messageOf(error) }); set({ error: handleRequestError(error) });
throw error; throw error;
} }
}, },
@@ -212,7 +242,7 @@ export const useImageWorkspaceStore = create<ImageWorkspaceState>((set, get) =>
set({ tasks }); set({ tasks });
return tasks; return tasks;
} catch (error) { } catch (error) {
set({ error: messageOf(error) }); set({ error: handleRequestError(error) });
throw error; throw error;
} }
}, },
@@ -227,7 +257,7 @@ export const useImageWorkspaceStore = create<ImageWorkspaceState>((set, get) =>
message, message,
)); ));
} catch (error) { } catch (error) {
set({ error: messageOf(error) }); set({ error: handleRequestError(error) });
return await recoverRevisionConflict(error); return await recoverRevisionConflict(error);
} }
}, },
@@ -244,7 +274,7 @@ export const useImageWorkspaceStore = create<ImageWorkspaceState>((set, get) =>
await get().refreshTasks().catch(() => []); await get().refreshTasks().catch(() => []);
return updated; return updated;
} catch (error) { } catch (error) {
set({ error: messageOf(error) }); set({ error: handleRequestError(error) });
return await recoverRevisionConflict(error); return await recoverRevisionConflict(error);
} }
}, },

View File

@@ -36,7 +36,8 @@ describe('auth store', () => {
}); });
it('starts browser authorization through the host api and stores the session', async () => { it('starts browser authorization through the host api and stores the session', async () => {
hostApiFetchMock.mockResolvedValueOnce({ hostApiFetchMock
.mockResolvedValueOnce({
success: true, success: true,
token: { token: {
access_token: 'access-token', access_token: 'access-token',
@@ -50,7 +51,8 @@ describe('auth store', () => {
authorities: ['ROLE_USER'], authorities: ['ROLE_USER'],
client_id: 'app', client_id: 'app',
}, },
}); })
.mockResolvedValueOnce({ success: true });
await useAuthStore.getState().loginWithBrowser(); await useAuthStore.getState().loginWithBrowser();
@@ -152,6 +154,72 @@ describe('auth store', () => {
}); });
}); });
it('waits for Main session sync before marking persisted auth initialized', async () => {
let resolveSync!: (value: { success: boolean }) => void;
hostApiFetchMock.mockImplementationOnce(() => new Promise((resolve) => {
resolveSync = resolve;
}));
useAuthStore.setState({
initialized: false,
loading: false,
error: null,
authBase: 'https://biz.nianxx.cn/auth/',
clientId: 'app',
accessToken: 'persisted-access-token',
refreshToken: 'persisted-refresh-token',
tokenType: 'Bearer',
expiresAt: Date.now() + 60_000,
user: {
username: 'zhangsan',
userId: '1',
tenantId: 7,
deptId: 9,
authorities: ['ROLE_USER'],
},
});
const initialization = useAuthStore.getState().init();
expect(useAuthStore.getState().initialized).toBe(false);
resolveSync({ success: true });
await initialization;
expect(useAuthStore.getState().initialized).toBe(true);
});
it('clears persisted renderer auth when Main session sync fails', async () => {
hostApiFetchMock.mockRejectedValueOnce(new Error('Host API unavailable'));
useAuthStore.setState({
initialized: false,
loading: false,
error: null,
authBase: 'https://biz.nianxx.cn/auth/',
clientId: 'app',
accessToken: 'persisted-access-token',
refreshToken: 'persisted-refresh-token',
tokenType: 'Bearer',
expiresAt: Date.now() + 60_000,
user: {
username: 'zhangsan',
userId: '1',
tenantId: 7,
deptId: 9,
authorities: ['ROLE_USER'],
},
});
await useAuthStore.getState().init();
expect(useAuthStore.getState()).toMatchObject({
initialized: true,
accessToken: null,
refreshToken: null,
user: null,
error: '登录状态恢复失败,请重新登录。',
});
});
it('syncs a refreshed session to Main', async () => { it('syncs a refreshed session to Main', async () => {
hostApiFetchMock hostApiFetchMock
.mockResolvedValueOnce({ .mockResolvedValueOnce({
@@ -200,6 +268,36 @@ describe('auth store', () => {
}); });
}); });
it('clears stale renderer auth when refresh fails', async () => {
hostApiFetchMock.mockRejectedValueOnce(new Error('Invalid refresh token'));
useAuthStore.setState({
initialized: true,
loading: false,
error: null,
authBase: 'https://biz.nianxx.cn/auth/',
clientId: 'app',
accessToken: 'expired-access-token',
refreshToken: 'invalid-refresh-token',
tokenType: 'Bearer',
expiresAt: Date.now() - 1,
user: {
username: 'zhangsan',
userId: '1',
tenantId: 7,
deptId: 9,
authorities: ['ROLE_USER'],
},
});
await expect(useAuthStore.getState().refreshSession()).resolves.toBeNull();
expect(useAuthStore.getState()).toMatchObject({
accessToken: null,
refreshToken: null,
user: null,
});
});
it('logs out remotely and clears the local session', async () => { it('logs out remotely and clears the local session', async () => {
hostApiFetchMock.mockResolvedValueOnce({ success: true }); hostApiFetchMock.mockResolvedValueOnce({ success: true });
useAuthStore.setState({ useAuthStore.setState({

View File

@@ -3,6 +3,7 @@ import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ImageWorkspaceApiError } from '@/lib/image-workspace'; import { ImageWorkspaceApiError } from '@/lib/image-workspace';
import { ImageCanvas } from '@/pages/ImageCanvas'; import { ImageCanvas } from '@/pages/ImageCanvas';
import { useAuthStore } from '@/stores/auth';
import { useImageWorkspaceStore } from '@/stores/image-workspace'; import { useImageWorkspaceStore } from '@/stores/image-workspace';
import type { import type {
DesignGenerationTask, DesignGenerationTask,
@@ -152,6 +153,57 @@ describe('ImageCanvas Workspace-first design experience', () => {
expect(screen.getByText(/暂时无法连接设计服务/)).toBeInTheDocument(); expect(screen.getByText(/暂时无法连接设计服务/)).toBeInTheDocument();
}); });
it('clears stale renderer auth when Main requires authentication', async () => {
useAuthStore.setState({
initialized: true,
loading: false,
error: null,
accessToken: 'expired-access-token',
refreshToken: 'invalid-refresh-token',
tokenType: 'Bearer',
expiresAt: Date.now() - 1,
user: {
username: 'brother7',
userId: '1',
tenantId: null,
deptId: null,
authorities: [],
},
});
fetchImageWorkspaceMock.mockRejectedValueOnce(new ImageWorkspaceApiError(
401,
'AUTH_REQUIRED',
'请先登录后再使用 AI 设计',
));
render(<MemoryRouter><ImageCanvas /></MemoryRouter>);
await screen.findByTestId('image-workspace-unavailable');
expect(useAuthStore.getState()).toMatchObject({
accessToken: null,
refreshToken: null,
user: null,
});
expect(useImageWorkspaceStore.getState().status).toBe('auth-required');
useAuthStore.setState({
accessToken: 'fresh-access-token',
refreshToken: 'fresh-refresh-token',
tokenType: 'Bearer',
expiresAt: Date.now() + 60_000,
user: {
username: 'brother7',
userId: '1',
tenantId: null,
deptId: null,
authorities: [],
},
});
await waitFor(() => expect(fetchImageWorkspaceMock).toHaveBeenCalledTimes(2));
await waitFor(() => expect(useImageWorkspaceStore.getState().status).toBe('ready'));
});
it('renders one fixed design Agent, a Quote, and the unified image/video task list', async () => { it('renders one fixed design Agent, a Quote, and the unified image/video task list', async () => {
render(<MemoryRouter><ImageCanvas /></MemoryRouter>); render(<MemoryRouter><ImageCanvas /></MemoryRouter>);

View File

@@ -1,4 +1,4 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
import { MemoryRouter, Route, Routes } from 'react-router-dom'; import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { Login } from '@/pages/Login'; import { Login } from '@/pages/Login';
@@ -66,6 +66,52 @@ describe('Login page', () => {
expect(await screen.findByRole('button', { name: 'Continue in browser' })).toBeInTheDocument(); expect(await screen.findByRole('button', { name: 'Continue in browser' })).toBeInTheDocument();
}); });
it('redirects an open protected route when the current auth session is invalidated', async () => {
useSettingsStore.setState({ setupComplete: true });
useAuthStore.setState({
initialized: true,
loading: false,
error: null,
authBase: 'https://biz.nianxx.cn/auth/',
clientId: 'app',
accessToken: 'access-token',
refreshToken: 'refresh-token',
tokenType: 'Bearer',
expiresAt: Date.now() + 60_000,
user: {
username: 'brother7',
userId: '1',
tenantId: null,
deptId: null,
authorities: [],
},
});
hostApiFetchMock.mockResolvedValue({ success: true });
render(
<MemoryRouter initialEntries={['/makelore-home']}>
<App />
</MemoryRouter>,
);
await waitFor(() => expect(hostApiFetchMock).toHaveBeenCalledWith(
'/api/auth/session/sync',
expect.any(Object),
));
act(() => {
useAuthStore.setState({
accessToken: null,
refreshToken: null,
tokenType: null,
expiresAt: null,
user: null,
});
});
expect(await screen.findByRole('button', { name: 'Continue in browser' })).toBeInTheDocument();
});
it('opens only the local image workspace anonymously when the explicit development mode is active', async () => { it('opens only the local image workspace anonymously when the explicit development mode is active', async () => {
useSettingsStore.setState({ setupComplete: true }); useSettingsStore.setState({ setupComplete: true });
window.electron.imageWorkspaceLocalDevelopment = true; window.electron.imageWorkspaceLocalDevelopment = true;