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

V5: SIMPLE - just show pause button, no auto-send

Browse files
Files changed (1) hide show
  1. patch_auto_continue_v5.py +252 -0
patch_auto_continue_v5.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """V5: SIMPLEST approach - just show pause button with 10s auto-continue.
2
+
3
+ Architecture:
4
+ 1. Agent loop detects model stopped mid-task → sends 'task_incomplete' event
5
+ 2. SSE transport receives it → calls sideChannel.onTaskIncomplete()
6
+ 3. useAgentChat: onTaskIncomplete sets _showAutoContinue=true, sends continue msg
7
+ 4. ChatInput shows "Tạm dừng" button if _showAutoContinue
8
+ """
9
+
10
+ import os, re
11
+
12
+ EVENTS = "/source/frontend/src/types/events.ts"
13
+ SSE = "/source/frontend/src/lib/sse-chat-transport.ts"
14
+ USE_AGENT_CHAT = "/source/frontend/src/hooks/useAgentChat.ts"
15
+ CHAT_INPUT = "/source/frontend/src/components/Chat/ChatInput.tsx"
16
+ AGENT_LOOP = "/app/agent/core/agent_loop.py"
17
+
18
+
19
+ def patch_events():
20
+ with open(EVENTS, "r") as f:
21
+ c = f.read()
22
+ if "'task_incomplete'" not in c:
23
+ c = c.replace(" | 'plan_update';", " | 'plan_update'\n | 'task_incomplete';")
24
+ with open(EVENTS, "w") as f:
25
+ f.write(c)
26
+ print("OK: events.ts")
27
+
28
+
29
+ def patch_sse():
30
+ with open(SSE, "r") as f:
31
+ c = f.read()
32
+
33
+ if "onTaskIncomplete:" not in c:
34
+ c = c.replace(
35
+ " onInterrupted: () => void;",
36
+ " onInterrupted: () => void;\n onTaskIncomplete: (incompletePlan: Array<{ id: string; content: string; status: string }>) => void;"
37
+ )
38
+
39
+ if "case 'task_incomplete'" not in c:
40
+ case_block = """ case 'task_incomplete' as const:
41
+ sideChannel.onTaskIncomplete(
42
+ (event.data?.incomplete_plan as Array<{ id: string; content: string; status: string }>) || [],
43
+ );
44
+ break;
45
+ """
46
+ c = c.replace("case 'turn_complete':", case_block + "\n case 'turn_complete':")
47
+
48
+ with open(SSE, "w") as f:
49
+ f.write(c)
50
+ print("OK: sse.ts")
51
+
52
+
53
+ def patch_use_agent():
54
+ with open(USE_AGENT_CHAT, "r") as f:
55
+ c = f.read()
56
+
57
+ # 1. Import useState
58
+ if "useState" not in c:
59
+ c = c.replace(
60
+ "import { useCallback, useEffect, useMemo, useRef } from 'react';",
61
+ "import { useCallback, useEffect, useMemo, useRef, useState } from 'react';"
62
+ )
63
+
64
+ # 2. State (prefixed with _ = TS allows unused)
65
+ state = '''
66
+ // Auto-continue state for free models
67
+ const _acTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
68
+ const [_showAc, _setShowAc] = useState(false);'''
69
+ if "_acTimer" not in c:
70
+ c = c.replace(
71
+ "callbacksRef.current = { onReady, onError, onSessionDead };",
72
+ "callbacksRef.current = { onReady, onError, onSessionDead };" + state
73
+ )
74
+
75
+ # 3. Add onTaskIncomplete to interface
76
+ if "onTaskIncomplete:" not in c:
77
+ c = c.replace(
78
+ " onInterrupted: () => void;",
79
+ " onInterrupted: () => void;\n onTaskIncomplete: (incompletePlan: Array<{ id: string; content: string; status: string }>) => void;"
80
+ )
81
+
82
+ # 4. Add onTaskIncomplete handler - uses chatActionsRef ref instead of chat directly
83
+ handler = ''' onTaskIncomplete: (incompletePlan: Array<{ id: string; content: string; status: string }>) => {
84
+ _setShowAc(true);
85
+ if (_acTimer.current) clearTimeout(_acTimer.current);
86
+ _acTimer.current = setTimeout(() => {
87
+ _setShowAc(false);
88
+ // Auto-continue after 10s via chatActionsRef
89
+ const chatRef = chatActionsRef.current;
90
+ const sendMsg = (chatRef as any)?.sendMessage;
91
+ if (sendMsg) {
92
+ const planStr = incompletePlan.map(i => `- ${i.content}`).join('\\\\n');
93
+ sendMsg({ text: `[TIẾP TỤC] Tiếp tục task chưa hoàn thành:\\\\n${planStr}`, metadata: { createdAt: new Date().toISOString() } });
94
+ }
95
+ }, 10000);
96
+ },
97
+ onInterrupted: () => { /* no-op */ },'''
98
+
99
+ if "onTaskIncomplete: (incompletePlan" not in c:
100
+ old = ' onInterrupted: () => { /* no-op — handled by stop() caller */ },'
101
+ if old in c:
102
+ c = c.replace(old, handler)
103
+ else:
104
+ old2 = ' onInterrupted: () => { /* no-op */ },'
105
+ c = c.replace(old2, handler)
106
+
107
+ # 5. Cancel ref + return values
108
+ if "_showAc" not in content:
109
+ # Insert cancel before return
110
+ cancel = '''
111
+ // Expose auto-continue state
112
+ const _acCancel = useCallback(() => {
113
+ _setShowAc(false);
114
+ if (_acTimer.current) { clearTimeout(_acTimer.current); _acTimer.current = null; }
115
+ }, []);
116
+ '''
117
+ if "_acCancel" not in c:
118
+ c = c.replace('\n return {\n messages: chat.messages,', cancel + '\n return {\n messages: chat.messages,')
119
+
120
+ if "_showAc," not in c:
121
+ c = c.replace(
122
+ "refreshMessages,\n };",
123
+ "refreshMessages,\n _showAc,\n _acCancel,\n };"
124
+ )
125
+
126
+ with open(USE_AGENT_CHAT, "w") as f:
127
+ f.write(c)
128
+ print("OK: useAgentChat.ts")
129
+
130
+
131
+ def patch_chat_input():
132
+ with open(CHAT_INPUT, "r") as f:
133
+ c = f.read()
134
+
135
+ # DatasetUploadResponse fix
136
+ if "DatasetUploadResponse" in c and "type DatasetUploadResponse" not in c:
137
+ wrong = "import type { DatasetUploadResponse } from '@/types/agent';"
138
+ if wrong in c:
139
+ c = c.replace(wrong, "")
140
+ c = c.replace(
141
+ "import { apiFetch } from '@/utils/api';",
142
+ "import { apiFetch } from '@/utils/api';\ntype DatasetUploadResponse = { url: string; repo_id: string; filename: string; size: number; };"
143
+ )
144
+
145
+ # Add Button
146
+ if "Button" not in c:
147
+ c = c.replace(
148
+ "import { Box, IconButton, Stack, Tooltip } from '@mui/material';",
149
+ "import { Box, IconButton, Stack, Tooltip, Button } from '@mui/material';"
150
+ )
151
+
152
+ # Update interface
153
+ if "_showAc" not in c:
154
+ m = re.search(r'interface ChatInputProps\s*\{[^}]*\}', c, re.DOTALL)
155
+ if m:
156
+ iface = """interface ChatInputProps {
157
+ sessionId: string;
158
+ initialModelPath: string | null | undefined;
159
+ onSend: (text: string) => Promise<void>;
160
+ onStop: () => void;
161
+ onDatasetUploaded: () => Promise<boolean>;
162
+ isProcessing: boolean;
163
+ disabled: boolean;
164
+ placeholder?: string;
165
+ _showAc?: boolean;
166
+ _acCancel?: () => void;
167
+ }"""
168
+ c = c.replace(m.group(0), iface)
169
+
170
+ # Add button
171
+ btn = """
172
+ {/* Auto-continue pause button for free models */}
173
+ {_showAc && _acCancel && (
174
+ <Stack direction="row" spacing={1} sx={{ mb: 1, px: 1 }}>
175
+ <Button
176
+ variant="outlined"
177
+ color="secondary"
178
+ size="small"
179
+ onClick={_acCancel}
180
+ sx={{ textTransform: 'none', fontSize: '0.7rem' }}
181
+ >
182
+ Tạm dừng tự động tiếp tục (10s)
183
+ </Button>
184
+ </Stack>
185
+ )}
186
+ """
187
+ if "Tạm dừng" not in c:
188
+ c = c.replace("<Box sx={{ flex: 1 ", btn + "\n <Box sx={{ flex: 1 ")
189
+
190
+ with open(CHAT_INPUT, "w") as f:
191
+ f.write(c)
192
+ print("OK: ChatInput.tsx")
193
+
194
+
195
+ def patch_session_chat():
196
+ sess = "/source/frontend/src/components/SessionChat.tsx"
197
+ if not os.path.exists(sess):
198
+ print(f"SKIP: {sess}")
199
+ return
200
+ with open(sess, "r") as f:
201
+ c = f.read()
202
+ if "_showAc" not in c:
203
+ c = c.replace("<ChatInput ", "<ChatInput _showAc={_showAc} _acCancel={_acCancel} ")
204
+ with open(sess, "w") as f:
205
+ f.write(c)
206
+ print("OK: SessionChat.tsx")
207
+
208
+
209
+ def patch_agent_loop():
210
+ if not os.path.exists(AGENT_LOOP):
211
+ print(f"SKIP: {AGENT_LOOP}")
212
+ return
213
+ with open(AGENT_LOOP, "r") as f:
214
+ c = f.read()
215
+
216
+ if "_unfinished_plan" not in c:
217
+ fn = '''
218
+
219
+ def _unfinished_plan(session: Session) -> list[dict[str, str]]:
220
+ plan = getattr(session, "current_plan", None) or []
221
+ return [item for item in plan if item.get("status") in ("pending", "in_progress")]
222
+
223
+ '''
224
+ c = c.replace("class Handlers:", fn + "\n\nclass Handlers:")
225
+
226
+ if "task_incomplete" not in c:
227
+ check = '''
228
+ # === Auto-continue detection ===
229
+ if not llm_result.tool_calls_acc and llm_result.content:
230
+ unfinished = _unfinished_plan(session)
231
+ if unfinished:
232
+ await session.send_event(
233
+ Event(event_type="task_incomplete", data={"incomplete_plan": unfinished})
234
+ )
235
+ '''
236
+ marker = " # -- End of turn --"
237
+ if marker in c:
238
+ c = c.replace(marker, check + "\n" + marker)
239
+
240
+ with open(AGENT_LOOP, "w") as f:
241
+ f.write(c)
242
+ print("OK: agent_loop.py")
243
+
244
+
245
+ if __name__ == "__main__":
246
+ patch_events()
247
+ patch_sse()
248
+ patch_use_agent()
249
+ patch_chat_input()
250
+ patch_session_chat()
251
+ patch_agent_loop()
252
+ print("\nDONE: V5 - simple approach applied")