Skip to content

Commit d3f95a2

Browse files
re-fcursoragent
andcommitted
fix: keep history slice pure and ignore stale diff responses
Seed history from the URL in store preloadedState, skip AbortError logs, and apply the same request-id guard to content, outline, and diff fetches. Co-authored-by: Cursor <[email protected]>
1 parent 0023844 commit d3f95a2

19 files changed

Lines changed: 395 additions & 58 deletions

File tree

‎packages/frontend/src/api.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ export const fetchData = async <T>(
44
signal?: AbortSignal,
55
): Promise<T | null> => {
66
try {
7-
const response = signal ? await fetch(url, { signal }) : await fetch(url);
7+
const response = await fetch(url, { signal });
88
if (!response.ok) {
99
throw new Error(`HTTP error! status: ${response.status}`);
1010
}
@@ -14,6 +14,9 @@ export const fetchData = async <T>(
1414
return await response.text() as T;
1515
}
1616
} catch (error) {
17+
if (error instanceof DOMException && error.name === 'AbortError') {
18+
throw error;
19+
}
1720
console.error(`Error fetching from ${url}:`, error);
1821
throw error;
1922
}

‎packages/frontend/src/components/Content/MarkdownContent/MarkdownContent.tsx‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,20 +35,28 @@ const MarkdownContent: React.FC<MarkdownContentProps> = ({ scrollToId, onDirecto
3535
useEffect(() => {
3636
const request = dispatch(fetchContent(currentPath));
3737
return () => {
38-
request?.abort?.();
38+
request.abort();
3939
};
4040
}, [dispatch, currentPath]);
4141

4242
useEffect(() => {
43-
if (isGitRepository) {
44-
dispatch(fetchDiff(currentPath));
43+
if (!isGitRepository) {
44+
return;
4545
}
46+
const request = dispatch(fetchDiff(currentPath));
47+
return () => {
48+
request.abort();
49+
};
4650
}, [dispatch, currentPath, isGitRepository]);
4751

4852
useEffect(() => {
49-
if (viewMode === 'diff-prev') {
50-
dispatch(fetchDiffPrev(currentPath));
53+
if (viewMode !== 'diff-prev') {
54+
return;
5155
}
56+
const request = dispatch(fetchDiffPrev(currentPath));
57+
return () => {
58+
request.abort();
59+
};
5260
}, [dispatch, currentPath, viewMode]);
5361

5462
useEffect(() => {

‎packages/frontend/src/components/RightPane/Outline.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ const Outline: React.FC<OutlineProps> = ({ filePath, onItemClick, isOpen, onTogg
2323
useEffect(() => {
2424
const request = dispatch(fetchOutline(filePath));
2525
return () => {
26-
request?.abort?.();
26+
request.abort();
2727
};
2828
}, [dispatch, filePath]);
2929

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export const isStaleRequest = (
2+
state: { latestRequestId: string | null },
3+
action: { meta: { requestId: string; aborted?: boolean } },
4+
): boolean => (
5+
state.latestRequestId !== action.meta.requestId || Boolean(action.meta.aborted)
6+
);

‎packages/frontend/src/store/slices/contentSlice.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
21
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
32
import { fetchData } from '../../api';
3+
import { isStaleRequest } from '../isStaleRequest';
44

55
interface ContentState {
66
content: string;
@@ -21,7 +21,7 @@ const initialState: ContentState = {
2121
const encodePath = (path: string): string =>
2222
path.split('/').map(encodeURIComponent).join('/');
2323

24-
export const markdownApiUrl = (path: string | null): string => (
24+
const markdownApiUrl = (path: string | null): string => (
2525
path
2626
? `/api/markdown/${encodePath(path)}`
2727
: '/api/markdown/mdts-welcome-markdown.md'
@@ -53,14 +53,14 @@ const contentSlice = createSlice({
5353
state.error = null;
5454
})
5555
.addCase(fetchContent.fulfilled, (state, action) => {
56-
if (state.latestRequestId !== action.meta.requestId) {
56+
if (isStaleRequest(state, action)) {
5757
return;
5858
}
5959
state.loading = false;
6060
state.content = action.payload;
6161
})
6262
.addCase(fetchContent.rejected, (state, action) => {
63-
if (state.latestRequestId !== action.meta.requestId || action.meta.aborted) {
63+
if (isStaleRequest(state, action)) {
6464
return;
6565
}
6666
state.loading = false;

‎packages/frontend/src/store/slices/diffSlice.ts‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
22
import { fetchData } from '../../api';
3+
import { isStaleRequest } from '../isStaleRequest';
34

45
interface DiffState {
56
diff: string;
@@ -8,6 +9,8 @@ interface DiffState {
89
diffPrevLoading: boolean;
910
diffError: string | null;
1011
diffPrevError: string | null;
12+
latestDiffRequestId: string | null;
13+
latestDiffPrevRequestId: string | null;
1114
}
1215

1316
const initialState: DiffState = {
@@ -17,25 +20,27 @@ const initialState: DiffState = {
1720
diffPrevLoading: false,
1821
diffError: null,
1922
diffPrevError: null,
23+
latestDiffRequestId: null,
24+
latestDiffPrevRequestId: null,
2025
};
2126

2227
const encodePath = (path: string): string =>
2328
path.split('/').map(encodeURIComponent).join('/');
2429

2530
export const fetchDiff = createAsyncThunk(
2631
'diff/fetchDiff',
27-
async (path: string | null) => {
32+
async (path: string | null, { signal }) => {
2833
if (!path) return '';
29-
const data = await fetchData<string>(`/api/diff/${encodePath(path)}`, 'text');
34+
const data = await fetchData<string>(`/api/diff/${encodePath(path)}`, 'text', signal);
3035
return data || '';
3136
}
3237
);
3338

3439
export const fetchDiffPrev = createAsyncThunk(
3540
'diff/fetchDiffPrev',
36-
async (path: string | null) => {
41+
async (path: string | null, { signal }) => {
3742
if (!path) return '';
38-
const data = await fetchData<string>(`/api/diff-prev/${encodePath(path)}`, 'text');
43+
const data = await fetchData<string>(`/api/diff-prev/${encodePath(path)}`, 'text', signal);
3944
return data || '';
4045
}
4146
);
@@ -46,28 +51,42 @@ const diffSlice = createSlice({
4651
reducers: {},
4752
extraReducers: (builder) => {
4853
builder
49-
.addCase(fetchDiff.pending, (state) => {
54+
.addCase(fetchDiff.pending, (state, action) => {
55+
state.latestDiffRequestId = action.meta.requestId;
5056
state.diffLoading = true;
5157
state.diffError = null;
5258
})
5359
.addCase(fetchDiff.fulfilled, (state, action) => {
60+
if (isStaleRequest({ latestRequestId: state.latestDiffRequestId }, action)) {
61+
return;
62+
}
5463
state.diffLoading = false;
5564
state.diff = action.payload;
5665
})
5766
.addCase(fetchDiff.rejected, (state, action) => {
67+
if (isStaleRequest({ latestRequestId: state.latestDiffRequestId }, action)) {
68+
return;
69+
}
5870
state.diffLoading = false;
5971
state.diff = '';
6072
state.diffError = action.error.message || 'Failed to fetch diff';
6173
})
62-
.addCase(fetchDiffPrev.pending, (state) => {
74+
.addCase(fetchDiffPrev.pending, (state, action) => {
75+
state.latestDiffPrevRequestId = action.meta.requestId;
6376
state.diffPrevLoading = true;
6477
state.diffPrevError = null;
6578
})
6679
.addCase(fetchDiffPrev.fulfilled, (state, action) => {
80+
if (isStaleRequest({ latestRequestId: state.latestDiffPrevRequestId }, action)) {
81+
return;
82+
}
6783
state.diffPrevLoading = false;
6884
state.diffPrev = action.payload;
6985
})
7086
.addCase(fetchDiffPrev.rejected, (state, action) => {
87+
if (isStaleRequest({ latestRequestId: state.latestDiffPrevRequestId }, action)) {
88+
return;
89+
}
7190
state.diffPrevLoading = false;
7291
state.diffPrev = '';
7392
state.diffPrevError = action.error.message || 'Failed to fetch previous diff';

‎packages/frontend/src/store/slices/historySlice.ts‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,36 @@
11
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
2-
import { AppDispatch } from '../store';
2+
import type { AppDispatch } from '../store';
33

44
interface HistoryState {
55
currentPath: string | null;
66
isDirectory: boolean;
77
}
88

9+
const decodePath = (path: string): string => {
10+
try {
11+
return decodeURIComponent(path);
12+
} catch {
13+
return path;
14+
}
15+
};
16+
917
export const parseHistoryFromPathname = (pathname: string): HistoryState => {
10-
const path = pathname.substring(1);
11-
if (path === '') {
18+
const rawPath = pathname.substring(1);
19+
if (rawPath === '') {
1220
return { currentPath: null, isDirectory: false };
1321
}
1422

23+
const path = decodePath(rawPath);
1524
const fileExtensions = ['.md', '.markdown'];
1625
const isFile = fileExtensions.some((ext) => path.toLowerCase().endsWith(ext));
1726

18-
return { currentPath: decodeURIComponent(path), isDirectory: !isFile };
27+
return { currentPath: path, isDirectory: !isFile };
1928
};
2029

21-
const initialState: HistoryState = typeof window === 'undefined'
22-
? { currentPath: null, isDirectory: false }
23-
: parseHistoryFromPathname(window.location.pathname);
30+
const initialState: HistoryState = {
31+
currentPath: null,
32+
isDirectory: false,
33+
};
2434

2535
const historySlice = createSlice({
2636
name: 'history',

‎packages/frontend/src/store/slices/outlineSlice.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
22
import { fetchData } from '../../api';
3+
import { isStaleRequest } from '../isStaleRequest';
34

45
export type OutlineItem = {
56
id: string;
@@ -44,14 +45,14 @@ const outlineSlice = createSlice({
4445
state.error = null;
4546
})
4647
.addCase(fetchOutline.fulfilled, (state, action) => {
47-
if (state.latestRequestId !== action.meta.requestId) {
48+
if (isStaleRequest(state, action)) {
4849
return;
4950
}
5051
state.loading = false;
5152
state.outline = action.payload;
5253
})
5354
.addCase(fetchOutline.rejected, (state, action) => {
54-
if (state.latestRequestId !== action.meta.requestId || action.meta.aborted) {
55+
if (isStaleRequest(state, action)) {
5556
return;
5657
}
5758
state.loading = false;

‎packages/frontend/src/store/store.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import diffReducer from './slices/diffSlice';
44
import fileTreeReducer from './slices/fileTreeSlice';
55
import outlineReducer from './slices/outlineSlice';
66
import appSettingReducer, { saveAppSetting } from './slices/appSettingSlice';
7-
import historyReducer from './slices/historySlice';
7+
import historyReducer, { parseHistoryFromPathname } from './slices/historySlice';
88
import configReducer from './slices/configSlice';
99
import plantUMLReducer from './slices/plantUMLSlice';
1010

@@ -60,7 +60,10 @@ export const store = configureStore({
6060
config: configReducer,
6161
plantUML: plantUMLReducer,
6262
},
63-
preloadedState: loadState(),
63+
preloadedState: {
64+
...loadState(),
65+
history: parseHistoryFromPathname(window.location.pathname),
66+
},
6467
middleware: (getDefaultMiddleware) =>
6568
getDefaultMiddleware().prepend(listenerMiddleware.middleware),
6669
});

‎packages/frontend/test/unit/api.test.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ describe('fetchData', () => {
2929
mockFetch.mockResolvedValueOnce(createResponse({ json: payload }));
3030

3131
await expect(fetchData<typeof payload>('/api/config', 'json')).resolves.toEqual(payload);
32-
expect(mockFetch).toHaveBeenCalledWith('/api/config');
32+
expect(mockFetch).toHaveBeenCalledWith('/api/config', { signal: undefined });
3333
});
3434

3535
it('returns text when responseType is text', async () => {
@@ -59,4 +59,14 @@ describe('fetchData', () => {
5959
await expect(fetchData('/api/config', 'json')).rejects.toThrow(error);
6060
expect(consoleErrorSpy).toHaveBeenCalledWith('Error fetching from /api/config:', error);
6161
});
62+
63+
it('rethrows abort errors without logging', async () => {
64+
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
65+
const abortError = new DOMException('Aborted', 'AbortError');
66+
67+
mockFetch.mockRejectedValueOnce(abortError);
68+
69+
await expect(fetchData('/api/config', 'json')).rejects.toBe(abortError);
70+
expect(consoleErrorSpy).not.toHaveBeenCalled();
71+
});
6272
});

0 commit comments

Comments
 (0)