Spaces:
Running
Running
File size: 8,507 Bytes
fefda99 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | """V8: Safe auto-continue via useEffect pattern (no hoisting issues)."""
import os
events_ts = "/source/frontend/src/types/events.ts"
sse_ts = "/source/frontend/src/lib/sse-chat-transport.ts"
hook_ts = "/source/frontend/src/hooks/useAgentChat.ts"
input_tsx = "/source/frontend/src/components/Chat/ChatInput.tsx"
session_tsx = "/source/frontend/src/components/SessionChat.tsx"
agent_py = "/app/agent/core/agent_loop.py"
def patch_events():
with open(events_ts) as f:
c = f.read()
if "'task_incomplete'" not in c:
c = c.replace(
" | 'interrupted'",
" | 'interrupted'\n | 'task_incomplete'"
)
with open(events_ts, 'w') as f: f.write(c)
print("OK: events.ts")
def patch_sse():
with open(sse_ts) as f:
c = f.read()
if "onTaskIncomplete:" not in c:
c = c.replace(
" onInterrupted: () => void;",
" onInterrupted: () => void;\n onTaskIncomplete: (incompletePlan: Array<{ id: string; content: string; status: string }>) => void;"
)
if "case 'task_incomplete'" not in c:
case_handler = """ case 'task_incomplete':
sideChannel.onTaskIncomplete(
(event.data?.incomplete_plan as Array<{ id: string; content: string; status: string }>) || [],
);
break;
default:"""
c = c.replace("\n default:", "\n" + case_handler)
with open(sse_ts, 'w') as f: f.write(c)
print("OK: sse.ts")
def patch_hook():
with open(hook_ts) as f:
c = f.read()
# 1. Import useState
if "useState" not in c:
c = c.replace(
"import { useCallback, useEffect, useMemo, useRef } from 'react';",
"import { useCallback, useEffect, useMemo, useRef, useState } from 'react';"
)
# 2. State after callbacksRef
state = """
// Auto-continue state for free models
const [_showAc, _setShowAc] = useState(false);
const _acPlanRef = useRef<Array<{ id: string; content: string; status: string }>>([]);"""
if "_showAc" not in c:
c = c.replace(
"callbacksRef.current = { onReady, onError, onSessionDead };",
"callbacksRef.current = { onReady, onError, onSessionDead };" + state
)
# 3. onTaskIncomplete in interface
if "onTaskIncomplete:" not in c:
c = c.replace(
" onInterrupted: () => void;",
" onInterrupted: () => void;\n onTaskIncomplete: (incompletePlan: Array<{ id: string; content: string; status: string }>) => void;"
)
# 4. Handler in sideChannel (only set state + ref, no chat.sendMessage)
handler = """ onTaskIncomplete: (incompletePlan: Array<{ id: string; content: string; status: string }>) => {
_acPlanRef.current = incompletePlan;
_setShowAc(true);
},
onInterrupted: () => { /* no-op */ },"""
if "onTaskIncomplete: (incompletePlan" not in c:
old = ' onInterrupted: () => { /* no-op \u2014 handled by stop() caller */ },'
if old in c:
c = c.replace(old, handler)
else:
c = c.replace(' onInterrupted: () => { /* no-op */ },', handler)
# 5. useEffect to watch _showAc - runs timer, calls chat.sendMessage via chatActionsRef
effect = """
// Auto-continue effect: when _showAc becomes true, start 10s timer
useEffect(() => {
if (!_showAc) return;
const timer = setTimeout(() => {
const plan = _acPlanRef.current;
const setMsgs = chatActionsRef.current.setMessages;
const msgs = chatActionsRef.current.messages;
if (setMsgs && plan.length > 0) {
const planStr = plan.map(i => `- ${i.content}`).join('\\\\n');
const newMsg = { 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: '' };
setMsgs([...msgs, newMsg]);
}
_setShowAc(false);
}, 10000);
return () => clearTimeout(timer);
}, [_showAc]);
"""
if "Auto-continue effect" not in c:
# Insert before return
c = c.replace("\n return {\n messages: chat.messages,", effect + "\n return {\n messages: chat.messages,")
# 6. Cancel + return
cancel = """
const _acCancel = useCallback(() => { _setShowAc(false); }, []);"""
if "_acCancel" not in c:
c = c.replace("\n return {\n messages: chat.messages,", cancel + "\n return {\n messages: chat.messages,")
if "_showAc," not in c:
c = c.replace(
"refreshMessages,\n };",
"refreshMessages,\n _showAc,\n _acCancel,\n };"
)
with open(hook_ts, 'w') as f: f.write(c)
print("OK: useAgentChat.ts")
def patch_chat_input():
with open(input_tsx) as f:
c = f.read()
if "Button" not in c:
c = c.replace(" Tooltip,", " Tooltip,\n Button,")
if "_showAc" not in c:
old_iface = """interface ChatInputProps {
sessionId?: string;
initialModelPath?: string | null;
onSend: (text: string) => void;
onStop?: () => void;
onDatasetUploaded?: () => Promise<boolean> | boolean;
isProcessing?: boolean;
disabled?: boolean;
placeholder?: string;
}"""
new_iface = """interface ChatInputProps {
sessionId?: string;
initialModelPath?: string | null;
onSend: (text: string) => void;
onStop?: () => void;
onDatasetUploaded?: () => Promise<boolean> | boolean;
isProcessing?: boolean;
disabled?: boolean;
placeholder?: string;
_showAc?: boolean;
_acCancel?: () => void;
}"""
c = c.replace(old_iface, new_iface)
old_props = "placeholder = 'Ask anything...' }: ChatInputProps) {"
new_props = "placeholder = 'Ask anything...', _showAc = false, _acCancel }: ChatInputProps) {"
if old_props not in c:
old_props2 = "placeholder = 'Ask anything...' }: ChatInputProps) {"
new_props2 = "placeholder = 'Ask anything...', _showAc = false, _acCancel }: ChatInputProps) {"
c = c.replace(old_props2, new_props2)
else:
c = c.replace(old_props, new_props)
if "T\u1ea1m d\u1eebng" not in c:
btn = """
{_showAc && _acCancel && (
<Box sx={{ display: 'flex', justifyContent: 'center', mt: 1 }}>
<Button variant="outlined" size="small" onClick={_acCancel}
sx={{ textTransform: 'none', fontSize: '0.7rem', opacity: 0.7, '&:hover': { opacity: 1 } }}>
T\u1ea1m d\u1eebng t\u1ef1 \u0111\u1ed9ng ti\u1ebfp t\u1ee5c (10s)
</Button>
</Box>
)}
"""
if "<JobsUpgradeDialog" in c:
c = c.replace("<JobsUpgradeDialog", btn + "\n <JobsUpgradeDialog")
with open(input_tsx, 'w') as f: f.write(c)
print("OK: ChatInput.tsx")
def patch_session():
if not os.path.exists(session_tsx):
print(f"SKIP: {session_tsx}")
return
with open(session_tsx) as f:
c = f.read()
if "_showAc" not in c:
c = c.replace("<ChatInput ", "<ChatInput _showAc={_showAc} _acCancel={_acCancel} ")
with open(session_tsx, 'w') as f: f.write(c)
print("OK: SessionChat.tsx")
def patch_agent():
if not os.path.exists(agent_py):
print(f"SKIP: {agent_py}")
return
with open(agent_py) as f:
c = f.read()
if "_unfinished_plan" not in c:
fn = """
def _unfinished_plan(s: Session) -> list[dict[str, str]]:
p = getattr(s, "current_plan", None) or []
return [it for it in p if it.get("status") in ("pending", "in_progress")]
"""
c = c.replace("class Handlers:", fn + "\n\nclass Handlers:")
if "task_incomplete" not in c:
check = """
# Auto-continue detection
if not llm_result.tool_calls_acc and llm_result.content:
unfinished = _unfinished_plan(session)
if unfinished:
await session.send_event(Event(event_type="task_incomplete", data={"incomplete_plan": unfinished}))
"""
marker = " # -- End of turn --"
if marker in c:
c = c.replace(marker, check + "\n" + marker)
with open(agent_py, 'w') as f: f.write(c)
print("OK: agent_loop.py")
if __name__ == "__main__":
patch_events()
patch_sse()
patch_hook()
patch_chat_input()
patch_session()
patch_agent()
print("\nDONE: V8 - safe useEffect pattern") |