File size: 2,605 Bytes
3c88a0f | 1 2 3 4 5 | {"type": "session", "harness": "opencode", "id": "appdev-0045", "name": "chat app"}
{"type": "message", "message": {"role": "system", "content": "You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies."}}
{"type": "message", "message": {"role": "user", "content": "Walk me through building a chat app: key concepts, concrete details and common pitfalls. Include a runnable code example with its expected output."}}
{"type": "message", "message": {"role": "assistant", "content": "**WebSocket Chat App:**\n\n```python\nfrom fastapi import FastAPI, WebSocket, WebSocketDisconnect\nfrom fastapi.responses import HTMLResponse\nimport json\n\napp = FastAPI()\n\nclass ConnectionManager:\n def __init__(self):\n self.active: list[WebSocket] = []\n\n async def connect(self, ws: WebSocket):\n await ws.accept()\n self.active.append(ws)\n\n def disconnect(self, ws: WebSocket):\n self.active.remove(ws)\n\n async def broadcast(self, message: str, sender: WebSocket):\n for conn in self.active:\n if conn != sender:\n await conn.send_text(message)\n\nmanager = ConnectionManager()\n\n@app.websocket('/ws/{username}')\nasync def websocket_endpoint(websocket: WebSocket, username: str):\n await manager.connect(websocket)\n await manager.broadcast(f'{username} joined!', websocket)\n try:\n while True:\n data = await websocket.receive_text()\n await manager.broadcast(f'{username}: {data}', websocket)\n except WebSocketDisconnect:\n manager.disconnect(websocket)\n await manager.broadcast(f'{username} left.', websocket)\n\nHTML = '''\n<h1>Chat</h1>\n<input id=\"msg\" type=\"text\" placeholder=\"Type message...\">\n<button onclick=\"send()\">Send</button>\n<div id=\"log\"></div>\n<script>\nconst ws = new WebSocket(`ws://localhost:8000/ws/${prompt('Username:')}`);\nws.onmessage = (e) => {\n document.getElementById('log').innerHTML += `<p>${e.data}</p>`;\n};\nfunction send() {\n const msg = document.getElementById('msg');\n ws.send(msg.value); msg.value = '';\n}\n</script>'''\n\n@app.get('/')\nasync def get():\n return HTMLResponse(HTML)\n```\n\n**Run:** `uvicorn main:app --reload`\n**Test:** Open multiple browser tabs to `http://localhost:8000`"}}
|