bep40 commited on
Commit
b669390
·
verified ·
1 Parent(s): 9cf3a95

V6: Fix variable name bug + use correct references

Browse files
Files changed (1) hide show
  1. patch_auto_continue_v6.py +243 -0
patch_auto_continue_v6.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """V6: FIXED - Auto-continue with pause button for free models."""
2
+
3
+ import os
4
+ import re
5
+
6
+ EVENTS_FILE = "/source/frontend/src/types/events.ts"
7
+ SSE_TRANSPORT = "/source/frontend/src/lib/sse-chat-transport.ts"
8
+ HOOK_FILE = "/source/frontend/src/hooks/useAgentChat.ts"
9
+ CHAT_INPUT = "/source/frontend/src/components/Chat/ChatInput.tsx"
10
+ SESSION_CHAT = "/source/frontend/src/components/SessionChat.tsx"
11
+ AGENT_LOOP = "/app/agent/core/agent_loop.py"
12
+
13
+
14
+ def fix_events():
15
+ with open(EVENTS_FILE, "r") as f:
16
+ content = f.read()
17
+ if "'task_incomplete'" not in content:
18
+ content = content.replace(" | 'plan_update';", " | 'plan_update'\n | 'task_incomplete';")
19
+ with open(EVENTS_FILE, "w") as f:
20
+ f.write(content)
21
+ print("OK: events.ts")
22
+
23
+
24
+ def fix_sse():
25
+ with open(SSE_TRANSPORT, "r") as f:
26
+ content = f.read()
27
+
28
+ # Add onTaskIncomplete to interface
29
+ if "onTaskIncomplete:" not in content and "onInterrupted: () => void;" in content:
30
+ content = content.replace(
31
+ " onInterrupted: () => void;",
32
+ " onInterrupted: () => void;\n onTaskIncomplete: (incompletePlan: Array<{ id: string; content: string; status: string }>) => void;"
33
+ )
34
+
35
+ # Add case handler
36
+ if "case 'task_incomplete'" not in content:
37
+ case_code = """ case 'task_incomplete' as const:
38
+ sideChannel.onTaskIncomplete(
39
+ (event.data?.incomplete_plan as Array<{ id: string; content: string; status: string }>) || [],
40
+ );
41
+ break;
42
+ """
43
+ content = content.replace("case 'turn_complete':", case_code + "\n case 'turn_complete':")
44
+
45
+ with open(SSE_TRANSPORT, "w") as f:
46
+ f.write(content)
47
+ print("OK: sse-chat-transport.ts")
48
+
49
+
50
+ def fix_hook():
51
+ with open(HOOK_FILE, "r") as f:
52
+ content = f.read()
53
+
54
+ # 1. Import useState
55
+ if "useState" not in content:
56
+ content = content.replace(
57
+ "import { useCallback, useEffect, useMemo, useRef } from 'react';",
58
+ "import { useCallback, useEffect, useMemo, useRef, useState } from 'react';"
59
+ )
60
+
61
+ # 2. Add state after callbacksRef block
62
+ state_block = """
63
+ // Auto-continue for free models
64
+ const _acTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
65
+ const [_showAc, _setShowAc] = useState(false);
66
+ const _acCancel = useCallback(() => {
67
+ _setShowAc(false);
68
+ if (_acTimer.current) { clearTimeout(_acTimer.current); _acTimer.current = null; }
69
+ }, []);"""
70
+
71
+ if "_acTimer" not in content:
72
+ content = content.replace(
73
+ "callbacksRef.current = { onReady, onError, onSessionDead };",
74
+ "callbacksRef.current = { onReady, onError, onSessionDead };" + state_block
75
+ )
76
+
77
+ # 3. Add onTaskIncomplete to interface
78
+ if "onTaskIncomplete:" not in content and "onInterrupted: () => void;" in content:
79
+ content = content.replace(
80
+ " onInterrupted: () => void;",
81
+ " onInterrupted: () => void;\n onTaskIncomplete: (incompletePlan: Array<{ id: string; content: string; status: string }>) => void;"
82
+ )
83
+
84
+ # 4. Add handler in sideChannel - uses chatActionsRef to avoid hoisting issues
85
+ handler_code = """ onTaskIncomplete: (incompletePlan: Array<{ id: string; content: string; status: string }>) => {
86
+ _setShowAc(true);
87
+ if (_acTimer.current) clearTimeout(_acTimer.current);
88
+ _acTimer.current = setTimeout(() => {
89
+ _setShowAc(false);
90
+ const planStr = incompletePlan.map(i => `- ${i.content}`).join('\\\\n');
91
+ const msg = { text: `[TIẾP TỤC] Task chưa hoàn thành:\\\\n${planStr}`, metadata: { createdAt: new Date().toISOString() } };
92
+ const setMsgs = chatActionsRef.current.setMessages;
93
+ if (setMsgs) {
94
+ chatActionsRef.current.messages = [...chatActionsRef.current.messages, { id: 'ac-continue', role: 'user', parts: [{ type: 'text', text: msg.text }], content: msg.text }];
95
+ }
96
+ }, 10000);
97
+ },
98
+ onInterrupted: () => { /* no-op - handled by stop() */ },"""
99
+
100
+ if "onTaskIncomplete: (incompletePlan" not in content:
101
+ old_handler = ' onInterrupted: () => { /* no-op \u2014 handled by stop() caller */ },'
102
+ if old_handler in content:
103
+ content = content.replace(old_handler, handler_code)
104
+ else:
105
+ old_handler2 = ' onInterrupted: () => { /* no-op */ },'
106
+ content = content.replace(old_handler2, handler_code)
107
+
108
+ # 5. Return values
109
+ if "_showAc" not in content:
110
+ # The _showAc and _acCancel need to be in the return
111
+ return_marker = "refreshMessages,\n };"
112
+ if return_marker in content:
113
+ content = content.replace(
114
+ return_marker,
115
+ "refreshMessages,\n _showAc,\n _acCancel,\n };"
116
+ )
117
+
118
+ with open(HOOK_FILE, "w") as f:
119
+ f.write(content)
120
+ print("OK: useAgentChat.ts")
121
+
122
+
123
+ def fix_chat_input():
124
+ with open(CHAT_INPUT, "r") as f:
125
+ content = f.read()
126
+
127
+ # Fix DatasetUploadResponse
128
+ wrong_import = "import type { DatasetUploadResponse } from '@/types/agent';"
129
+ if wrong_import in content:
130
+ content = content.replace(wrong_import, "")
131
+ content = content.replace(
132
+ "import { apiFetch } from '@/utils/api';",
133
+ "import { apiFetch } from '@/utils/api';\ntype DatasetUploadResponse = { url: string; repo_id: string; filename: string; size: number; };"
134
+ )
135
+
136
+ # Add Button import
137
+ if "Button" not in content:
138
+ content = content.replace(
139
+ "import { Box, IconButton, Stack, Tooltip } from '@mui/material';",
140
+ "import { Box, IconButton, Stack, Tooltip, Button } from '@mui/material';"
141
+ )
142
+
143
+ # Fix interface
144
+ if "_showAc" not in content:
145
+ iface_match = re.search(r'interface ChatInputProps\s*\{[^}]*\}', content, re.DOTALL)
146
+ if iface_match:
147
+ new_iface = """interface ChatInputProps {
148
+ sessionId: string;
149
+ initialModelPath: string | null | undefined;
150
+ onSend: (text: string) => Promise<void>;
151
+ onStop: () => void;
152
+ onDatasetUploaded: () => Promise<boolean>;
153
+ isProcessing: boolean;
154
+ disabled: boolean;
155
+ placeholder?: string;
156
+ _showAc?: boolean;
157
+ _acCancel?: () => void;
158
+ }"""
159
+ content = content.replace(iface_match.group(0), new_iface)
160
+
161
+ # Add pause button
162
+ btn_code = """
163
+ {/* Auto-continue pause for free models */}
164
+ {_showAc && _acCancel && (
165
+ <Stack direction="row" spacing={1} sx={{ mb: 1, px: 1 }}>
166
+ <Button
167
+ variant="outlined"
168
+ color="secondary"
169
+ size="small"
170
+ onClick={_acCancel}
171
+ sx={{ textTransform: 'none', fontSize: '0.7rem', opacity: 0.8 }}
172
+ >
173
+ T\u1ea1m d\u1eebng t\u1ef1 \u0111\u1ed9ng ti\u1ebfp t\u1ee5c (10s)
174
+ </Button>
175
+ </Stack>
176
+ )}"""
177
+
178
+ if "T\u1ea1m d\u1eebng" not in content and "free models" not in content:
179
+ content = content.replace("<Box sx={{ flex: 1 ", btn_code + "\n <Box sx={{ flex: 1 ")
180
+
181
+ with open(CHAT_INPUT, "w") as f:
182
+ f.write(content)
183
+ print("OK: ChatInput.tsx")
184
+
185
+
186
+ def fix_session_chat():
187
+ with open(SESSION_CHAT, "r") as f:
188
+ content = f.read()
189
+
190
+ # Add props to ChatInput
191
+ if "_showAc" not in content:
192
+ content = content.replace(
193
+ "<ChatInput ",
194
+ "<ChatInput _showAc={_showAc} _acCancel={_acCancel} "
195
+ )
196
+
197
+ with open(SESSION_CHAT, "w") as f:
198
+ f.write(content)
199
+ print("OK: SessionChat.tsx")
200
+
201
+
202
+ def fix_agent_loop():
203
+ if not os.path.exists(AGENT_LOOP):
204
+ print(f"SKIP: {AGENT_LOOP}")
205
+ return
206
+ with open(AGENT_LOOP, "r") as f:
207
+ content = f.read()
208
+
209
+ if "_unfinished_plan" not in content:
210
+ fn_block = '''
211
+
212
+ def _unfinished_plan(s: Session) -> list[dict[str, str]]:
213
+ p = getattr(s, "current_plan", None) or []
214
+ return [it for it in p if it.get("status") in ("pending", "in_progress")]
215
+
216
+ '''
217
+ content = content.replace("class Handlers:", fn_block + "\n\nclass Handlers:")
218
+
219
+ if "task_incomplete" not in content:
220
+ check_block = '''
221
+ # Auto-continue detect
222
+ if not llm_result.tool_calls_acc and llm_result.content:
223
+ unfinished = _unfinished_plan(session)
224
+ if unfinished:
225
+ await session.send_event(Event(event_type="task_incomplete", data={"incomplete_plan": unfinished}))
226
+ '''
227
+ marker = " # -- End of turn --"
228
+ if marker in content:
229
+ content = content.replace(marker, check_block + "\n" + marker)
230
+
231
+ with open(AGENT_LOOP, "w") as f:
232
+ f.write(content)
233
+ print("OK: agent_loop.py")
234
+
235
+
236
+ if __name__ == "__main__":
237
+ fix_events()
238
+ fix_sse()
239
+ fix_hook()
240
+ fix_chat_input()
241
+ fix_session_chat()
242
+ fix_agent_loop()
243
+ print("\nDONE: V6 - all fixed")