bep40 commited on
Commit
3b5cf7d
·
verified ·
1 Parent(s): 020776c

V2: Fix all TS errors for auto-continue

Browse files
Files changed (1) hide show
  1. patch_auto_continue_v2.py +307 -0
patch_auto_continue_v2.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """V2: Fix all TypeScript errors for auto-continue feature.
2
+
3
+ Errors fixed:
4
+ 1. 'startAutoContinue' used before declaration → use refs
5
+ 2. 'showAutoContinue'/'taskIncompleteInfo' never read → they're in return
6
+ 3. 'incompletePlan' implicit any → add type
7
+ 4. EventType missing 'task_incomplete' → add to events.ts
8
+ 5. DatasetUploadResponse not found → fix import path
9
+ 6. onTaskIncomplete not on SideChannelCallbacks → fix in SSE transport
10
+ """
11
+
12
+ import os
13
+ import re
14
+
15
+ # =====================================================================
16
+ # PATCH 1: events.ts - Add 'task_incomplete' to EventType
17
+ # =====================================================================
18
+ EVENTS_FILE = "/source/frontend/src/types/events.ts"
19
+
20
+ def patch_events():
21
+ if not os.path.exists(EVENTS_FILE):
22
+ print(f"SKIP: {EVENTS_FILE} not found")
23
+ return
24
+ with open(EVENTS_FILE, "r") as f:
25
+ content = f.read()
26
+ if "'task_incomplete'" not in content:
27
+ content = content.replace(
28
+ " | 'plan_update';",
29
+ " | 'plan_update'\n | 'task_incomplete';"
30
+ )
31
+ with open(EVENTS_FILE, "w") as f:
32
+ f.write(content)
33
+ print("OK: Added 'task_incomplete' to EventType")
34
+ else:
35
+ print("OK: EventType already has 'task_incomplete'")
36
+
37
+ # =====================================================================
38
+ # PATCH 2: useAgentChat.ts - Fix hoisting + type issues
39
+ # =====================================================================
40
+ USE_AGENT_CHAT = "/source/frontend/src/hooks/useAgentChat.ts"
41
+
42
+ def patch_use_agent_chat():
43
+ if not os.path.exists(USE_AGENT_CHAT):
44
+ print(f"SKIP: {USE_AGENT_CHAT} not found")
45
+ return
46
+
47
+ with open(USE_AGENT_CHAT, "r") as f:
48
+ content = f.read()
49
+
50
+ # 1. Add useState to imports
51
+ if "useState" not in content:
52
+ content = content.replace(
53
+ "import { useCallback, useEffect, useMemo, useRef } from 'react';",
54
+ "import { useCallback, useEffect, useMemo, useRef, useState } from 'react';"
55
+ )
56
+
57
+ # 2. Add state + refs after callbacksRef
58
+ state_code = '''
59
+ // Auto-continue state for free models when task incomplete
60
+ const autoContinueTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
61
+ const [showAutoContinue, setShowAutoContinue] = useState(false);
62
+ const [taskIncompleteInfo, setTaskIncompleteInfo] = useState<{
63
+ incompletePlan: Array<{ id: string; content: string; status: string }>;
64
+ } | null>(null);
65
+ const startAutoContinueRef = useRef<() => void>(() => {});
66
+ const cancelAutoContinueRef = useRef<() => void>(() => {});
67
+ '''
68
+ if "autoContinueTimerRef" not in content:
69
+ content = content.replace(
70
+ "callbacksRef.current = { onReady, onError, onSessionDead };",
71
+ "callbacksRef.current = { onReady, onError, onSessionDead };" + state_code
72
+ )
73
+
74
+ # 3. Add onTaskIncomplete to SideChannelCallbacks interface
75
+ if "onTaskIncomplete:" not in content and "onInterrupted:" in content:
76
+ content = content.replace(
77
+ " onInterrupted: () => void;",
78
+ " onInterrupted: () => void;\n onTaskIncomplete: (incompletePlan: Array<{ id: string; content: string; status: string }>) => void;"
79
+ )
80
+
81
+ # 4. Replace onTaskIncomplete handler to use refs
82
+ old_handler = "onTaskIncomplete: (incompletePlan) => {"
83
+ new_handler = "onTaskIncomplete: (incompletePlan: Array<{ id: string; content: string; status: string }>) => {"
84
+ if old_handler in content:
85
+ content = content.replace(old_handler, new_handler)
86
+
87
+ # Fix the timer callback to use ref instead of direct call
88
+ old_timer = "autoContinueTimerRef.current = setTimeout(() => {\n startAutoContinue();\n }, 10000);"
89
+ new_timer = "autoContinueTimerRef.current = setTimeout(() => {\n startAutoContinueRef.current();\n }, 10000);"
90
+ if old_timer in content:
91
+ content = content.replace(old_timer, new_timer)
92
+
93
+ # 5. Add auto-continue functions BEFORE return (but using refs pattern)
94
+ # Remove old startAutoContinue/cancelAutoContinue if they exist
95
+ old_funcs_start = "const startAutoContinue = useCallback"
96
+ if old_funcs_start in content:
97
+ # Find and remove the old function blocks
98
+ start_idx = content.find("const startAutoContinue = useCallback")
99
+ cancel_idx = content.find("const cancelAutoContinue = useCallback")
100
+ cleanup_idx = content.find("// Cleanup timer on unmount")
101
+
102
+ # Remove from startAutoContinue to end of cleanup
103
+ if start_idx > 0 and cleanup_idx > start_idx:
104
+ # Find the end of cleanup effect
105
+ end_cleanup = content.find("\n", cleanup_idx)
106
+ # Find the closing of the useEffect
107
+ close_idx = content.find("}, []);", end_cleanup)
108
+ if close_idx > 0:
109
+ close_idx += len("}, []);")
110
+ content = content[:start_idx] + content[close_idx:]
111
+
112
+ # 5b. Add new functions using ref pattern, before return
113
+ new_funcs = '''
114
+ // -- Auto-continue for free models when task incomplete -----------------
115
+ const startAutoContinue = useCallback(() => {
116
+ setShowAutoContinue(false);
117
+ setTaskIncompleteInfo(null);
118
+ if (autoContinueTimerRef.current) {
119
+ clearTimeout(autoContinueTimerRef.current);
120
+ autoContinueTimerRef.current = null;
121
+ }
122
+ const incompleteItems = taskIncompleteInfo?.incompletePlan || [];
123
+ const continuationText = incompleteItems.length > 0
124
+ ? `Tiếp tục từ các task chưa hoàn thành:\\n${incompleteItems.map(i => `- ${i.content}`).join('\\n')}`
125
+ : 'Tiếp tục nhiệm vụ.';
126
+ chat.sendMessage({
127
+ text: `[TỰ ĐỘNG TIẾP TỤC] ${continuationText}`,
128
+ metadata: { createdAt: new Date().toISOString() },
129
+ });
130
+ }, [taskIncompleteInfo, chat]);
131
+
132
+ const cancelAutoContinue = useCallback(() => {
133
+ setShowAutoContinue(false);
134
+ setTaskIncompleteInfo(null);
135
+ if (autoContinueTimerRef.current) {
136
+ clearTimeout(autoContinueTimerRef.current);
137
+ autoContinueTimerRef.current = null;
138
+ }
139
+ }, []);
140
+
141
+ // Keep refs in sync
142
+ startAutoContinueRef.current = startAutoContinue;
143
+ cancelAutoContinueRef.current = cancelAutoContinue;
144
+
145
+ // Cleanup timer on unmount
146
+ useEffect(() => {
147
+ return () => {
148
+ if (autoContinueTimerRef.current) {
149
+ clearTimeout(autoContinueTimerRef.current);
150
+ }
151
+ };
152
+ }, []);
153
+ '''
154
+
155
+ if "startAutoContinueRef.current" not in content:
156
+ content = content.replace(
157
+ '\n return {\n messages: chat.messages,',
158
+ new_funcs + '\n return {\n messages: chat.messages,'
159
+ )
160
+
161
+ # 6. Update return to include new values
162
+ if "showAutoContinue," not in content:
163
+ content = content.replace(
164
+ "refreshMessages,\n };",
165
+ "refreshMessages,\n showAutoContinue,\n taskIncompleteInfo,\n startAutoContinue,\n cancelAutoContinue,\n };"
166
+ )
167
+
168
+ with open(USE_AGENT_CHAT, "w") as f:
169
+ f.write(content)
170
+ print(f"OK: Patched {USE_AGENT_CHAT}")
171
+
172
+ # =====================================================================
173
+ # PATCH 3: ChatInput.tsx - Fix DatasetUploadResponse import
174
+ # =====================================================================
175
+ CHAT_INPUT = "/source/frontend/src/components/Chat/ChatInput.tsx"
176
+
177
+ def patch_chat_input():
178
+ if not os.path.exists(CHAT_INPUT):
179
+ print(f"SKIP: {CHAT_INPUT} not found")
180
+ return
181
+
182
+ with open(CHAT_INPUT, "r") as f:
183
+ content = f.read()
184
+
185
+ # Fix DatasetUploadResponse import - try correct path
186
+ if "DatasetUploadResponse" in content:
187
+ # Check if it's imported from agent.ts
188
+ wrong_import = "import type { DatasetUploadResponse } from '@/types/agent';"
189
+ if wrong_import in content:
190
+ # Try to find the correct import - it's probably in the same file or from backend
191
+ # Replace with inline type or remove
192
+ content = content.replace(wrong_import, "")
193
+ # Add inline type
194
+ content = content.replace(
195
+ "import { apiFetch } from '@/utils/api';",
196
+ "import { apiFetch } from '@/utils/api';\n\ntype DatasetUploadResponse = { url: string; repo_id: string; filename: string; size: number; };"
197
+ )
198
+ print("OK: Fixed DatasetUploadResponse import")
199
+
200
+ # Add Button to MUI imports
201
+ if "Button" not in content:
202
+ content = content.replace(
203
+ "import { Box, IconButton, Stack, Tooltip } from '@mui/material';",
204
+ "import { Box, IconButton, Stack, Tooltip, Button } from '@mui/material';"
205
+ )
206
+
207
+ # Check if interface already has our props (from previous patch)
208
+ if "showAutoContinue" not in content:
209
+ # Find interface and replace with complete version
210
+ interface_match = re.search(r'interface ChatInputProps\s*\{[^}]*\}', content, re.DOTALL)
211
+ if interface_match:
212
+ props_code = '''
213
+ interface ChatInputProps {
214
+ sessionId: string;
215
+ initialModelPath: string | null | undefined;
216
+ onSend: (text: string) => Promise<void>;
217
+ onStop: () => void;
218
+ onDatasetUploaded: () => Promise<boolean>;
219
+ isProcessing: boolean;
220
+ disabled: boolean;
221
+ placeholder?: string;
222
+ showAutoContinue?: boolean;
223
+ taskIncompleteInfo?: { incompletePlan: Array<{ id: string; content: string; status: string }> } | null;
224
+ startAutoContinue?: () => void;
225
+ cancelAutoContinue?: () => void;
226
+ }
227
+ '''
228
+ content = content.replace(interface_match.group(0), props_code)
229
+ print("OK: Updated ChatInputProps interface")
230
+
231
+ # Add auto-continue buttons
232
+ buttons_code = '''
233
+ {/* Auto-continue controls for free models */}
234
+ {showAutoContinue && taskIncompleteInfo && (
235
+ <Stack direction="row" spacing={1} sx={{ mb: 1, px: 1 }}>
236
+ <Button
237
+ variant="contained"
238
+ color="primary"
239
+ size="small"
240
+ onClick={startAutoContinue}
241
+ sx={{ textTransform: 'none', fontSize: '0.75rem' }}
242
+ >
243
+ Tự động tiếp tục (10s)
244
+ </Button>
245
+ <Button
246
+ variant="outlined"
247
+ color="secondary"
248
+ size="small"
249
+ onClick={cancelAutoContinue}
250
+ sx={{ textTransform: 'none', fontSize: '0.75rem' }}
251
+ >
252
+ Tạm dừng
253
+ </Button>
254
+ </Stack>
255
+ )}
256
+ '''
257
+
258
+ if "Tự động tiếp tục" not in content:
259
+ content = content.replace(
260
+ "<Box sx={{ flex: 1 ",
261
+ buttons_code + " <Box sx={{ flex: 1 "
262
+ )
263
+ print("OK: Added auto-continue buttons")
264
+
265
+ with open(CHAT_INPUT, "w") as f:
266
+ f.write(content)
267
+ print(f"OK: Patched {CHAT_INPUT}")
268
+
269
+ # =====================================================================
270
+ # PATCH 4: sse-chat-transport.ts - Fix onTaskIncomplete reference
271
+ # =====================================================================
272
+ SSE_TRANSPORT = "/source/frontend/src/lib/sse-chat-transport.ts"
273
+
274
+ def patch_sse_transport():
275
+ if not os.path.exists(SSE_TRANSPORT):
276
+ print(f"SKIP: {SSE_TRANSPORT} not found")
277
+ return
278
+
279
+ with open(SSE_TRANSPORT, "r") as f:
280
+ content = f.read()
281
+
282
+ # Add onTaskIncomplete to SideChannelCallbacks interface
283
+ if "onTaskIncomplete:" not in content and "onInterrupted:" in content:
284
+ content = content.replace(
285
+ " onInterrupted: () => void;",
286
+ " onInterrupted: () => void;\n onTaskIncomplete: (incompletePlan: Array<{ id: string; content: string; status: string }>) => void;"
287
+ )
288
+
289
+ # Use @ts-ignore for the case since EventType union doesn't include 'task_incomplete'
290
+ # Or better: add the case with a type assertion
291
+ if "case 'task_incomplete'" in content:
292
+ # Already added, make sure it compiles
293
+ old_case = "case 'task_incomplete':\n sideChannel.onTaskIncomplete("
294
+ new_case = "case 'task_incomplete' as const:\n sideChannel.onTaskIncomplete("
295
+ content = content.replace(old_case, new_case)
296
+
297
+ with open(SSE_TRANSPORT, "w") as f:
298
+ f.write(content)
299
+ print(f"OK: Patched {SSE_TRANSPORT}")
300
+
301
+
302
+ if __name__ == "__main__":
303
+ patch_events()
304
+ patch_use_agent_chat()
305
+ patch_chat_input()
306
+ patch_sse_transport()
307
+ print("\nDONE: All V2 patches applied")