Refactor: decouple task queues, add JS injection support, and simplify stapp rendering
This commit is contained in:
38
stapp.py
38
stapp.py
@@ -23,12 +23,6 @@ agent = init()
|
||||
|
||||
st.title("🖥️ Cowork")
|
||||
|
||||
if "idle_buf" not in st.session_state: st.session_state.idle_buf = ""
|
||||
if "messages" not in st.session_state: st.session_state.messages = []
|
||||
|
||||
for msg in st.session_state.messages:
|
||||
with st.chat_message(msg["role"]): st.markdown(msg["content"])
|
||||
|
||||
@st.fragment
|
||||
def render_llm_switcher():
|
||||
current_idx = agent.llm_no
|
||||
@@ -44,36 +38,22 @@ def render_llm_switcher():
|
||||
st.toast("下次将重新注入System Prompt")
|
||||
with st.sidebar: render_llm_switcher()
|
||||
|
||||
@st.fragment(run_every="1s")
|
||||
def global_queue_listener():
|
||||
if agent.current_source == 'auto':
|
||||
while not agent.display_queue.empty():
|
||||
item = agent.display_queue.get()
|
||||
if item.get('source') == 'auto':
|
||||
if 'next' in item: st.session_state.idle_buf = item['next']
|
||||
if 'done' in item:
|
||||
st.session_state.messages.append({"role": "assistant", "content": f"🤖 {item['done']}"})
|
||||
st.session_state.idle_buf = ""; st.rerun()
|
||||
if st.session_state.get("idle_buf"):
|
||||
with st.chat_message("assistant"):
|
||||
st.write(st.session_state.idle_buf + "▌")
|
||||
else:
|
||||
st.caption("🟢 Agent Listener Active", help=f"Last sync: {int(time.time())}")
|
||||
st.session_state.idle_buf = ""
|
||||
|
||||
global_queue_listener()
|
||||
|
||||
def agent_backend_stream(prompt):
|
||||
agent.put_task(prompt, source="user")
|
||||
display_queue = agent.put_task(prompt, source="user")
|
||||
try:
|
||||
while True:
|
||||
item = agent.display_queue.get()
|
||||
item = display_queue.get()
|
||||
if 'next' in item: yield item['next']
|
||||
if 'done' in item:
|
||||
yield item['done']; break
|
||||
finally:
|
||||
agent.abort()
|
||||
|
||||
if "messages" not in st.session_state: st.session_state.messages = []
|
||||
for msg in st.session_state.messages:
|
||||
with st.chat_message(msg["role"]): st.markdown(msg["content"])
|
||||
|
||||
if prompt := st.chat_input("请输入指令"):
|
||||
st.session_state.messages.append({"role": "user", "content": prompt})
|
||||
with st.chat_message("user"): st.markdown(prompt)
|
||||
@@ -84,4 +64,8 @@ if prompt := st.chat_input("请输入指令"):
|
||||
for response in agent_backend_stream(prompt):
|
||||
message_placeholder.markdown(response + "▌")
|
||||
message_placeholder.markdown(response)
|
||||
st.session_state.messages.append({"role": "assistant", "content": response})
|
||||
st.session_state.messages.append({"role": "assistant", "content": response})
|
||||
st.session_state.last_reply_time = int(time.time())
|
||||
|
||||
st.markdown(f"""<div id="last-reply-time" style="display:none">{st.session_state.get('last_reply_time', int(time.time()))}</div>""", unsafe_allow_html=True)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user