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

View File

@@ -19,6 +19,7 @@ import {
import { IMAGE_WORKSPACE_CREATE_PROJECT_EVENT } from '@/lib/image-workspace';
import { cn } from '@/lib/utils';
import { useImageWorkspaceStore } from '@/stores/image-workspace';
import { useAuthStore } from '@/stores/auth';
import type { DesignWorkspaceSummary } from '../../../shared/image-workspace';
type ImageWorkspaceSidebarProps = {
@@ -30,6 +31,7 @@ type ProjectDialogState =
| { mode: 'rename'; project: DesignWorkspaceSummary };
export function ImageWorkspaceSidebar({ sidebarCollapsed }: ImageWorkspaceSidebarProps) {
const authenticated = useAuthStore((state) => state.isAuthenticated());
const navigate = useNavigate();
const status = useImageWorkspaceStore((state) => state.status);
const bootstrap = useImageWorkspaceStore((state) => state.bootstrap);
@@ -46,8 +48,8 @@ export function ImageWorkspaceSidebar({ sidebarCollapsed }: ImageWorkspaceSideba
const [saving, setSaving] = useState(false);
useEffect(() => {
if (status === 'idle') void load();
}, [load, status]);
if (status === 'idle' || (status === 'auth-required' && authenticated)) void load();
}, [authenticated, load, status]);
useEffect(() => {
const openCreateDialog = () => {
@@ -154,7 +156,7 @@ export function ImageWorkspaceSidebar({ sidebarCollapsed }: ImageWorkspaceSideba
</div>
) : null}
{status === 'unavailable' || status === 'error' ? (
{status === 'unavailable' || status === 'error' || status === 'auth-required' ? (
<div
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"

View File

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

View File

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

View File

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