bep40 commited on
Commit
68e54e0
·
verified ·
1 Parent(s): b669390

V7: Precise patches with exact source matching

Browse files
Files changed (1) hide show
  1. patch_auto_continue_v7.py +255 -0
patch_auto_continue_v7.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """V7: PRECISE patch - exact string matching with source code.
2
+
3
+ Adds auto-continue pause button for free models. All patches use exact
4
+ string content from the original source files for reliable replacement.
5
+ """
6
+
7
+ import os, sys
8
+
9
+ # ========== PATCH 1: events.ts - add 'task_incomplete' to EventType ==========
10
+ events_ts = "/source/frontend/src/types/events.ts"
11
+ def patch_events():
12
+ with open(events_ts) as f:
13
+ c = f.read()
14
+ if "'task_incomplete'" not in c:
15
+ c = c.replace(
16
+ " | 'interrupted'",
17
+ " | 'interrupted'\n | 'task_incomplete'"
18
+ )
19
+ with open(events_ts, 'w') as f: f.write(c)
20
+ print("OK: events.ts")
21
+
22
+ # ========== PATCH 2: SSE transport - add onTaskIncomplete to interface + handler ==========
23
+ sse_ts = "/source/frontend/src/lib/sse-chat-transport.ts"
24
+ def patch_sse():
25
+ with open(sse_ts) as f:
26
+ c = f.read()
27
+
28
+ # Add to interface
29
+ if "onTaskIncomplete:" not in c:
30
+ c = c.replace(
31
+ " onInterrupted: () => void;",
32
+ " onInterrupted: () => void;\n onTaskIncomplete: (incompletePlan: Array<{ id: string; content: string; status: string }>) => void;"
33
+ )
34
+
35
+ # Add case handler before default
36
+ if "case 'task_incomplete'" not in c:
37
+ case_handler = """ case 'task_incomplete':
38
+ sideChannel.onTaskIncomplete(
39
+ (event.data?.incomplete_plan as Array<{ id: string; content: string; status: string }>) || [],
40
+ );
41
+ break;
42
+
43
+ default:"""
44
+ c = c.replace("\n default:", "\n" + case_handler)
45
+
46
+ with open(sse_ts, 'w') as f: f.write(c)
47
+ print("OK: sse-chat-transport.ts")
48
+
49
+ # ========== PATCH 3: useAgentChat.ts - add state + handler + return ==========
50
+ hook_ts = "/source/frontend/src/hooks/useAgentChat.ts"
51
+ def patch_hook():
52
+ with open(hook_ts) as f:
53
+ c = f.read()
54
+
55
+ # 1. Add useState to imports
56
+ if "useState" not in c:
57
+ c = c.replace(
58
+ "import { useCallback, useEffect, useMemo, useRef } from 'react';",
59
+ "import { useCallback, useEffect, useMemo, useRef, useState } from 'react';"
60
+ )
61
+
62
+ # 2. Add state variables after callbacksRef
63
+ state_block = """
64
+ // Auto-continue state for free models
65
+ const _acTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
66
+ const [_showAc, _setShowAc] = useState(false);"""
67
+ if "_acTimerRef" not in c:
68
+ c = c.replace(
69
+ "callbacksRef.current = { onReady, onError, onSessionDead };",
70
+ "callbacksRef.current = { onReady, onError, onSessionDead };" + state_block
71
+ )
72
+
73
+ # 3. Add onTaskIncomplete to interface
74
+ if "onTaskIncomplete:" not in c:
75
+ c = c.replace(
76
+ " onInterrupted: () => void;",
77
+ " onInterrupted: () => void;\n onTaskIncomplete: (incompletePlan: Array<{ id: string; content: string; status: string }>) => void;"
78
+ )
79
+
80
+ # 4. Add onTaskIncomplete handler in sideChannel object
81
+ # This inserts BEFORE the existing onInterrupted handler
82
+ handler = """ onTaskIncomplete: (incompletePlan: Array<{ id: string; content: string; status: string }>) => {
83
+ _setShowAc(true);
84
+ if (_acTimerRef.current) clearTimeout(_acTimerRef.current);
85
+ _acTimerRef.current = setTimeout(() => {
86
+ _setShowAc(false);
87
+ const planStr = incompletePlan.map(i => `- ${i.content}`).join('\\\\n');
88
+ const setMsgs = chatActionsRef.current.setMessages;
89
+ if (setMsgs) {
90
+ const msgs = chatActionsRef.current.messages;
91
+ setMsgs([...msgs, { id: 'ac-'+Date.now(), role: 'user' as const, parts: [{ type: 'text' as const, text: `[TIẾP TỤC] Task chưa hoàn thành:\\\\n${planStr}` }], content: '' }]);
92
+ }
93
+ }, 10000);
94
+ },
95
+ onInterrupted: () => { /* no-op */ },"""
96
+
97
+ if "onTaskIncomplete: (incompletePlan" not in c:
98
+ old_interrupted = ' onInterrupted: () => { /* no-op \u2014 handled by stop() caller */ },'
99
+ if old_interrupted in c:
100
+ c = c.replace(old_interrupted, handler)
101
+ else:
102
+ # Try simpler version
103
+ old2 = ' onInterrupted: () => { /* no-op */ },'
104
+ c = c.replace(old2, handler)
105
+
106
+ # 5. Add _acCancel function + return values
107
+ cancel_func = """
108
+ const _acCancel = useCallback(() => {
109
+ _setShowAc(false);
110
+ if (_acTimerRef.current) { clearTimeout(_acTimerRef.current); _acTimerRef.current = null; }
111
+ }, []);"""
112
+ if "_acCancel" not in c:
113
+ c = c.replace("\n return {\n messages: chat.messages,", cancel_func + "\n return {\n messages: chat.messages,")
114
+
115
+ # 6. Return values
116
+ if "_showAc," not in c:
117
+ c = c.replace(
118
+ "refreshMessages,\n };",
119
+ "refreshMessages,\n _showAc,\n _acCancel,\n };"
120
+ )
121
+
122
+ with open(hook_ts, 'w') as f: f.write(c)
123
+ print("OK: useAgentChat.ts")
124
+
125
+ # ========== PATCH 4: ChatInput.tsx - add pause button ==========
126
+ input_tsx = "/source/frontend/src/components/Chat/ChatInput.tsx"
127
+ def patch_chat_input():
128
+ with open(input_tsx) as f:
129
+ c = f.read()
130
+
131
+ # 1. Add Button import (it's missing from the original imports)
132
+ if "Button" not in c:
133
+ c = c.replace(
134
+ " Tooltip,",
135
+ " Tooltip,\n Button,"
136
+ )
137
+
138
+ # 2. Add props to interface
139
+ if "_showAc" not in c:
140
+ old_interface_end = """interface ChatInputProps {
141
+ sessionId?: string;
142
+ initialModelPath?: string | null;
143
+ onSend: (text: string) => void;
144
+ onStop?: () => void;
145
+ onDatasetUploaded?: () => Promise<boolean> | boolean;
146
+ isProcessing?: boolean;
147
+ disabled?: boolean;
148
+ placeholder?: string;
149
+ }"""
150
+ new_interface = """interface ChatInputProps {
151
+ sessionId?: string;
152
+ initialModelPath?: string | null;
153
+ onSend: (text: string) => void;
154
+ onStop?: () => void;
155
+ onDatasetUploaded?: () => Promise<boolean> | boolean;
156
+ isProcessing?: boolean;
157
+ disabled?: boolean;
158
+ placeholder?: string;
159
+ _showAc?: boolean;
160
+ _acCancel?: () => void;
161
+ }"""
162
+ c = c.replace(old_interface_end, new_interface)
163
+
164
+ # 3. Add destructured props in function signature
165
+ if "_showAc" not in c:
166
+ old_props = "placeholder = 'Ask anything...' }: ChatInputProps) {"
167
+ new_props = "placeholder = 'Ask anything...', _showAc = false, _acCancel }: ChatInputProps) {"
168
+ if old_props not in c:
169
+ old_props2 = "placeholder = 'Ask anything...' }: ChatInputProps) {"
170
+ new_props2 = "placeholder = 'Ask anything...', _showAc = false, _acCancel }: ChatInputProps) {"
171
+ c = c.replace(old_props2, new_props2)
172
+ else:
173
+ c = c.replace(old_props, new_props)
174
+
175
+ # 4. Add pause button after the model badge area, before <JobsUpgradeDialog>
176
+ if "T\u1ea1m d\u1eebng" not in c:
177
+ btn = """
178
+ {/* Auto-continue pause for free models */}
179
+ {_showAc && _acCancel && (
180
+ <Box sx={{ display: 'flex', justifyContent: 'center', mt: 1 }}>
181
+ <Button
182
+ variant="outlined"
183
+ size="small"
184
+ onClick={_acCancel}
185
+ sx={{ textTransform: 'none', fontSize: '0.7rem', opacity: 0.7, '&:hover': { opacity: 1 } }}
186
+ >
187
+ T\u1ea1m d\u1eebng t\u1ef1 \u0111\u1ed9ng ti\u1ebfp t\u1ee5c (10s)
188
+ </Button>
189
+ </Box>
190
+ )}
191
+ """
192
+ if "<JobsUpgradeDialog" in c:
193
+ c = c.replace("<JobsUpgradeDialog", btn + "\n <JobsUpgradeDialog")
194
+
195
+ with open(input_tsx, 'w') as f: f.write(c)
196
+ print("OK: ChatInput.tsx")
197
+
198
+ # ========== PATCH 5: SessionChat.tsx - pass props down ==========
199
+ session_tsx = "/source/frontend/src/components/SessionChat.tsx"
200
+ def patch_session():
201
+ if not os.path.exists(session_tsx):
202
+ print(f"SKIP: {session_tsx}")
203
+ return
204
+ with open(session_tsx) as f:
205
+ c = f.read()
206
+ if "_showAc" not in c:
207
+ old = "<ChatInput "
208
+ new = "<ChatInput _showAc={_showAc} _acCancel={_acCancel} "
209
+ c = c.replace(old, new)
210
+ with open(session_tsx, 'w') as f: f.write(c)
211
+ print("OK: SessionChat.tsx")
212
+
213
+ # ========== PATCH 6: agent_loop.py - detection ==========
214
+ agent_py = "/app/agent/core/agent_loop.py"
215
+ def patch_agent():
216
+ if not os.path.exists(agent_py):
217
+ print(f"SKIP: {agent_py}")
218
+ return
219
+ with open(agent_py) as f:
220
+ c = f.read()
221
+
222
+ # Add helper function
223
+ if "_unfinished_plan" not in c:
224
+ fn = """
225
+ def _unfinished_plan(s: Session) -> list[dict[str, str]]:
226
+ p = getattr(s, "current_plan", None) or []
227
+ return [it for it in p if it.get("status") in ("pending", "in_progress")]
228
+
229
+ """
230
+ c = c.replace("class Handlers:", fn + "\n\nclass Handlers:")
231
+
232
+ # Add detection
233
+ if "task_incomplete" not in c:
234
+ check = """
235
+ # Auto-continue detection
236
+ if not llm_result.tool_calls_acc and llm_result.content:
237
+ unfinished = _unfinished_plan(session)
238
+ if unfinished:
239
+ await session.send_event(Event(event_type="task_incomplete", data={"incomplete_plan": unfinished}))
240
+ """
241
+ marker = " # -- End of turn --"
242
+ if marker in c:
243
+ c = c.replace(marker, check + "\n" + marker)
244
+
245
+ with open(agent_py, 'w') as f: f.write(c)
246
+ print("OK: agent_loop.py")
247
+
248
+ if __name__ == "__main__":
249
+ patch_events()
250
+ patch_sse()
251
+ patch_hook()
252
+ patch_chat_input()
253
+ patch_session()
254
+ patch_agent()
255
+ print("\nDONE: V7 - precise patches applied")