import { ref, onUnmounted } from 'vue' export function useWebSocket(taskId) { const logs = ref([]) const connected = ref(false) let ws = null const connect = () => { const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:' ws = new WebSocket(`${protocol}//${location.host}/ws/tasks/${taskId}`) ws.onopen = () => { connected.value = true } ws.onmessage = (event) => { const msg = JSON.parse(event.data) if (msg.level !== 'heartbeat') { logs.value.push(msg) } } ws.onclose = () => { connected.value = false } ws.onerror = () => { connected.value = false } } const disconnect = () => { if (ws) { ws.close() ws = null } } onUnmounted(disconnect) return { logs, connected, connect, disconnect } }