[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7DA2Z7CA8BK8YRPY677EPT5":3,"skill-same:01M7DA2Z7CA8BK8YRPY677EPT5":81},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":59,"commitSha":60,"skillDirectory":61,"forksCount":14,"repositoryHtmlUrl":62,"repositoryHomepageUrl":6,"ownerHtmlUrl":63,"ownerBlogUrl":64,"ownerDescription":65,"updatedAt":66,"install":67,"resources":80},"01M7DA2Z7CA8BK8YRPY677EPT5","WebSocket Bug Finder",null,"Test WebSocket connections for reliability including reconnection logic, message ordering, heartbeat mechanisms, and connection state management under adverse conditions","GrupoANDevelopment-m\u002Falberto-ai","GrupoANDevelopment-m","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F257455179?v=4","01M7D69X2N2KEVN0SJF6WGM6SH","Antônio  Ndombe","01M7D69X3P5JTT8H8S904N3888",0,"MIT","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fskills\u002Fqa\u002Fwebsocket-bug-finder\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: WebSocket Bug Finder\ndescription: Test WebSocket connections for reliability including reconnection logic, message ordering, heartbeat mechanisms, and connection state management under adverse conditions\nversion: 1.0.0\nauthor: Pramod\nlicense: MIT\ntags: [websocket, real-time, connection-testing, reconnection, message-ordering, heartbeat, socket-testing, ws]\ntestingTypes: [integration, e2e]\nframeworks: [playwright]\nlanguages: [typescript, javascript]\ndomains: [web, api]\nagents: [claude-code, cursor, github-copilot, windsurf, codex, aider, continue, cline, zed, bolt, gemini-cli, amp]\n---\n\n# WebSocket Bug Finder Skill\n\nYou are an expert QA automation engineer specializing in WebSocket and real-time communication testing. When the user asks you to write, review, or debug WebSocket tests, follow these detailed instructions to validate connection lifecycle management, reconnection reliability, message ordering guarantees, heartbeat mechanisms, and connection behavior under adverse network conditions.\n\n## Core Principles\n\n1. **Connections are ephemeral** -- WebSocket connections will drop unexpectedly due to network changes, server restarts, load balancer timeouts, and mobile device sleep. Every WebSocket client must handle disconnection gracefully and reconnect automatically.\n2. **Message ordering is not guaranteed without explicit sequencing** -- While TCP guarantees in-order delivery within a single connection, reconnection creates a new TCP stream. Messages sent during reconnection may arrive out of order. Test that applications handle sequence gaps correctly.\n3. **Heartbeats are a contract** -- Both client and server must participate in keep-alive mechanisms. Test that heartbeats are sent at the correct interval, that missed heartbeats trigger reconnection, and that heartbeat failures do not cause silent connection death.\n4. **Test the transitions, not just the states** -- The critical bugs live in state transitions: connecting to open, open to closing, closing to closed, closed to reconnecting. Test every transition path, especially the error paths.\n5. **Simulate real network conditions** -- Lab environments with perfect connectivity will never expose reconnection bugs. Use network throttling, packet loss simulation, and connection interruption to test under realistic conditions.\n6. **Binary and text frames have different semantics** -- WebSocket supports both text frames (UTF-8 encoded) and binary frames (ArrayBuffer). Test that the application correctly handles both frame types and does not confuse them.\n7. **Concurrency limits matter** -- Browsers limit WebSocket connections per domain (typically 6-30). Test that the application functions correctly near these limits and handles connection pool exhaustion gracefully.\n\n## Project Structure\n\nOrganize WebSocket testing projects with this structure:\n\n```\ntests\u002F\n  websocket\u002F\n    connection\u002F\n      lifecycle.spec.ts\n      reconnection.spec.ts\n      authentication.spec.ts\n      concurrent-connections.spec.ts\n    messaging\u002F\n      ordering.spec.ts\n      delivery-guarantee.spec.ts\n      binary-messages.spec.ts\n      large-payloads.spec.ts\n    heartbeat\u002F\n      ping-pong.spec.ts\n      timeout-detection.spec.ts\n      keep-alive.spec.ts\n    resilience\u002F\n      network-disruption.spec.ts\n      server-restart.spec.ts\n      backpressure.spec.ts\n    e2e\u002F\n      real-time-updates.spec.ts\n      collaborative-editing.spec.ts\n      chat-messaging.spec.ts\n  helpers\u002F\n    ws-test-client.ts\n    ws-message-recorder.ts\n    network-simulator.ts\n    ws-server-mock.ts\n  fixtures\u002F\n    websocket.fixture.ts\n  config\u002F\n    ws-test-config.ts\nplaywright.config.ts\n```\n\n## WebSocket Connection Lifecycle Testing\n\n### Test Client Helper\n\n```typescript\n\u002F\u002F helpers\u002Fws-test-client.ts\nimport WebSocket from 'ws';\nimport { EventEmitter } from 'events';\n\ninterface WSMessage {\n  data: string | Buffer;\n  timestamp: number;\n  type: 'text' | 'binary';\n  sequence?: number;\n}\n\ninterface ConnectionEvent {\n  type: 'open' | 'close' | 'error' | 'message' | 'reconnect';\n  timestamp: number;\n  details?: unknown;\n}\n\nexport class WSTestClient extends EventEmitter {\n  private ws: WebSocket | null = null;\n  private url: string;\n  private messages: WSMessage[] = [];\n  private events: ConnectionEvent[] = [];\n  private reconnectAttempts = 0;\n  private maxReconnectAttempts = 5;\n  private reconnectDelay = 1000;\n  private shouldReconnect = true;\n  private heartbeatInterval: NodeJS.Timeout | null = null;\n  private heartbeatTimeout: NodeJS.Timeout | null = null;\n  private headers: Record\u003Cstring, string>;\n\n  constructor(\n    url: string,\n    options: {\n      headers?: Record\u003Cstring, string>;\n      maxReconnectAttempts?: number;\n      reconnectDelay?: number;\n    } = {}\n  ) {\n    super();\n    this.url = url;\n    this.headers = options.headers || {};\n    this.maxReconnectAttempts = options.maxReconnectAttempts ?? 5;\n    this.reconnectDelay = options.reconnectDelay ?? 1000;\n  }\n\n  connect(): Promise\u003Cvoid> {\n    return new Promise((resolve, reject) => {\n      this.ws = new WebSocket(this.url, { headers: this.headers });\n\n      this.ws.on('open', () => {\n        this.reconnectAttempts = 0;\n        this.recordEvent('open');\n        this.emit('open');\n        resolve();\n      });\n\n      this.ws.on('message', (data: WebSocket.Data) => {\n        const message: WSMessage = {\n          data: data instanceof Buffer ? data : data.toString(),\n          timestamp: Date.now(),\n          type: data instanceof Buffer ? 'binary' : 'text',\n        };\n\n        \u002F\u002F Extract sequence number if present\n        if (typeof message.data === 'string') {\n          try {\n            const parsed = JSON.parse(message.data);\n            if (parsed.seq !== undefined) {\n              message.sequence = parsed.seq;\n            }\n          } catch {\n            \u002F\u002F Not JSON, that is fine\n          }\n        }\n\n        this.messages.push(message);\n        this.recordEvent('message', message);\n        this.emit('message', message);\n      });\n\n      this.ws.on('close', (code, reason) => {\n        this.recordEvent('close', { code, reason: reason.toString() });\n        this.emit('close', code, reason);\n        this.stopHeartbeat();\n\n        if (this.shouldReconnect && this.reconnectAttempts \u003C this.maxReconnectAttempts) {\n          this.attemptReconnect();\n        }\n      });\n\n      this.ws.on('error', (error) => {\n        this.recordEvent('error', { message: error.message });\n        this.emit('error', error);\n        reject(error);\n      });\n    });\n  }\n\n  private async attemptReconnect(): Promise\u003Cvoid> {\n    this.reconnectAttempts++;\n    const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);\n    this.recordEvent('reconnect', { attempt: this.reconnectAttempts, delay });\n\n    await new Promise((resolve) => setTimeout(resolve, delay));\n\n    try {\n      await this.connect();\n    } catch {\n      \u002F\u002F Reconnect failed, will retry if under max attempts\n    }\n  }\n\n  send(data: string | Buffer): void {\n    if (this.ws?.readyState !== WebSocket.OPEN) {\n      throw new Error(`Cannot send: WebSocket is ${this.getStateName()}`);\n    }\n    this.ws.send(data);\n  }\n\n  startHeartbeat(intervalMs: number = 30000, timeoutMs: number = 5000): void {\n    this.heartbeatInterval = setInterval(() => {\n      if (this.ws?.readyState === WebSocket.OPEN) {\n        this.ws.ping();\n\n        this.heartbeatTimeout = setTimeout(() => {\n          \u002F\u002F No pong received within timeout\n          this.emit('heartbeat-timeout');\n          this.ws?.terminate();\n        }, timeoutMs);\n      }\n    }, intervalMs);\n\n    this.ws?.on('pong', () => {\n      if (this.heartbeatTimeout) {\n        clearTimeout(this.heartbeatTimeout);\n        this.heartbeatTimeout = null;\n      }\n      this.emit('pong');\n    });\n  }\n\n  stopHeartbeat(): void {\n    if (this.heartbeatInterval) {\n      clearInterval(this.heartbeatInterval);\n      this.heartbeatInterval = null;\n    }\n    if (this.heartbeatTimeout) {\n      clearTimeout(this.heartbeatTimeout);\n      this.heartbeatTimeout = null;\n    }\n  }\n\n  close(code: number = 1000, reason: string = 'Test complete'): void {\n    this.shouldReconnect = false;\n    this.stopHeartbeat();\n    this.ws?.close(code, reason);\n  }\n\n  getMessages(): WSMessage[] {\n    return [...this.messages];\n  }\n\n  getEvents(): ConnectionEvent[] {\n    return [...this.events];\n  }\n\n  getState(): number {\n    return this.ws?.readyState ?? WebSocket.CLOSED;\n  }\n\n  getStateName(): string {\n    const states: Record\u003Cnumber, string> = {\n      [WebSocket.CONNECTING]: 'CONNECTING',\n      [WebSocket.OPEN]: 'OPEN',\n      [WebSocket.CLOSING]: 'CLOSING',\n      [WebSocket.CLOSED]: 'CLOSED',\n    };\n    return states[this.getState()] || 'UNKNOWN';\n  }\n\n  getReconnectAttempts(): number {\n    return this.reconnectAttempts;\n  }\n\n  clearMessages(): void {\n    this.messages = [];\n  }\n\n  private recordEvent(type: ConnectionEvent['type'], details?: unknown): void {\n    this.events.push({ type, timestamp: Date.now(), details });\n  }\n}\n```\n\n### Connection Lifecycle Tests\n\n```typescript\n\u002F\u002F tests\u002Fwebsocket\u002Fconnection\u002Flifecycle.spec.ts\nimport { describe, test, expect, beforeAll, afterAll, afterEach } from 'vitest';\nimport { WSTestClient } from '..\u002F..\u002Fhelpers\u002Fws-test-client';\nimport { WebSocketServer, WebSocket } from 'ws';\n\nlet wss: WebSocketServer;\nconst PORT = 8765;\nconst WS_URL = `ws:\u002F\u002Flocalhost:${PORT}`;\n\nbeforeAll(() => {\n  wss = new WebSocketServer({ port: PORT });\n  wss.on('connection', (ws) => {\n    ws.on('message', (data) => {\n      \u002F\u002F Echo messages back\n      ws.send(data);\n    });\n  });\n});\n\nafterAll(() => {\n  wss.close();\n});\n\ndescribe('WebSocket Connection Lifecycle', () => {\n  let client: WSTestClient;\n\n  afterEach(() => {\n    client?.close();\n  });\n\n  test('should establish connection and reach OPEN state', async () => {\n    client = new WSTestClient(WS_URL);\n    await client.connect();\n\n    expect(client.getState()).toBe(WebSocket.OPEN);\n    expect(client.getStateName()).toBe('OPEN');\n\n    const events = client.getEvents();\n    expect(events[0].type).toBe('open');\n  });\n\n  test('should perform clean close with code 1000', async () => {\n    client = new WSTestClient(WS_URL);\n    await client.connect();\n\n    const closePromise = new Promise\u003C{ code: number; reason: Buffer }>((resolve) => {\n      client.on('close', (code, reason) => resolve({ code, reason }));\n    });\n\n    client.close(1000, 'Normal closure');\n    const result = await closePromise;\n\n    expect(result.code).toBe(1000);\n    expect(client.getState()).toBe(WebSocket.CLOSED);\n  });\n\n  test('should record all lifecycle events in order', async () => {\n    client = new WSTestClient(WS_URL);\n    await client.connect();\n\n    client.send('test message');\n\n    \u002F\u002F Wait for echo\n    await new Promise\u003Cvoid>((resolve) => {\n      client.on('message', () => resolve());\n    });\n\n    client.close();\n\n    await new Promise\u003Cvoid>((resolve) => {\n      client.on('close', () => resolve());\n    });\n\n    const events = client.getEvents();\n    const eventTypes = events.map((e) => e.type);\n\n    expect(eventTypes[0]).toBe('open');\n    expect(eventTypes).toContain('message');\n    expect(eventTypes[eventTypes.length - 1]).toBe('close');\n\n    \u002F\u002F Events should be in chronological order\n    for (let i = 1; i \u003C events.length; i++) {\n      expect(events[i].timestamp).toBeGreaterThanOrEqual(events[i - 1].timestamp);\n    }\n  });\n\n  test('should handle server-initiated close', async () => {\n    client = new WSTestClient(WS_URL, { maxReconnectAttempts: 0 });\n    await client.connect();\n\n    const closePromise = new Promise\u003Cnumber>((resolve) => {\n      client.on('close', (code) => resolve(code));\n    });\n\n    \u002F\u002F Close from server side\n    wss.clients.forEach((ws) => {\n      ws.close(1001, 'Server going away');\n    });\n\n    const code = await closePromise;\n    expect(code).toBe(1001);\n  });\n\n  test('should reject connection to invalid URL', async () => {\n    client = new WSTestClient('ws:\u002F\u002Flocalhost:9999', { maxReconnectAttempts: 0 });\n\n    await expect(client.connect()).rejects.toThrow();\n    expect(client.getState()).toBe(WebSocket.CLOSED);\n  });\n});\n```\n\n## Reconnection Logic Verification\n\n```typescript\n\u002F\u002F tests\u002Fwebsocket\u002Fconnection\u002Freconnection.spec.ts\nimport { describe, test, expect, afterEach } from 'vitest';\nimport { WSTestClient } from '..\u002F..\u002Fhelpers\u002Fws-test-client';\nimport { WebSocketServer, WebSocket } from 'ws';\n\ndescribe('WebSocket Reconnection', () => {\n  let wss: WebSocketServer;\n  let client: WSTestClient;\n  const PORT = 8766;\n\n  afterEach(() => {\n    client?.close();\n    wss?.close();\n  });\n\n  test('should automatically reconnect after server disconnect', async () => {\n    wss = new WebSocketServer({ port: PORT });\n\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n      maxReconnectAttempts: 3,\n      reconnectDelay: 100,\n    });\n\n    await client.connect();\n    expect(client.getState()).toBe(WebSocket.OPEN);\n\n    \u002F\u002F Track reconnection\n    const reconnectPromise = new Promise\u003Cvoid>((resolve) => {\n      client.on('open', () => resolve());\n    });\n\n    \u002F\u002F Force disconnect from server side\n    wss.clients.forEach((ws) => ws.terminate());\n\n    \u002F\u002F Wait for reconnection\n    await reconnectPromise;\n    expect(client.getState()).toBe(WebSocket.OPEN);\n    expect(client.getReconnectAttempts()).toBeGreaterThanOrEqual(1);\n  });\n\n  test('should use exponential backoff for reconnection attempts', async () => {\n    \u002F\u002F Start server, connect, then stop server to force reconnect failures\n    wss = new WebSocketServer({ port: PORT });\n\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n      maxReconnectAttempts: 4,\n      reconnectDelay: 100,\n    });\n\n    await client.connect();\n\n    \u002F\u002F Close server to prevent reconnection\n    wss.close();\n\n    \u002F\u002F Force disconnect\n    client['ws']?.terminate();\n\n    \u002F\u002F Wait for all reconnection attempts to fail\n    await new Promise((resolve) => setTimeout(resolve, 5000));\n\n    const events = client.getEvents().filter((e) => e.type === 'reconnect');\n\n    \u002F\u002F Verify exponential backoff pattern\n    for (let i = 1; i \u003C events.length; i++) {\n      const prevDelay = (events[i - 1].details as { delay: number }).delay;\n      const currDelay = (events[i].details as { delay: number }).delay;\n      expect(currDelay).toBeGreaterThanOrEqual(prevDelay);\n    }\n  });\n\n  test('should stop reconnecting after max attempts', async () => {\n    const maxAttempts = 3;\n\n    wss = new WebSocketServer({ port: PORT });\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n      maxReconnectAttempts: maxAttempts,\n      reconnectDelay: 50,\n    });\n\n    await client.connect();\n    wss.close();\n    client['ws']?.terminate();\n\n    \u002F\u002F Wait for all attempts to exhaust\n    await new Promise((resolve) => setTimeout(resolve, 3000));\n\n    const reconnectEvents = client.getEvents().filter((e) => e.type === 'reconnect');\n    expect(reconnectEvents.length).toBeLessThanOrEqual(maxAttempts);\n  });\n\n  test('should reset reconnect counter after successful connection', async () => {\n    wss = new WebSocketServer({ port: PORT });\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n      maxReconnectAttempts: 5,\n      reconnectDelay: 100,\n    });\n\n    await client.connect();\n\n    \u002F\u002F First disconnect and reconnect\n    const firstReconnect = new Promise\u003Cvoid>((resolve) => {\n      client.once('open', () => resolve());\n    });\n    wss.clients.forEach((ws) => ws.terminate());\n    await firstReconnect;\n\n    \u002F\u002F After successful reconnect, counter should reset\n    expect(client.getReconnectAttempts()).toBe(0);\n\n    \u002F\u002F Second disconnect and reconnect should also work\n    const secondReconnect = new Promise\u003Cvoid>((resolve) => {\n      client.once('open', () => resolve());\n    });\n    wss.clients.forEach((ws) => ws.terminate());\n    await secondReconnect;\n\n    expect(client.getState()).toBe(WebSocket.OPEN);\n  });\n});\n```\n\n## Message Ordering and Delivery Guarantees\n\n```typescript\n\u002F\u002F tests\u002Fwebsocket\u002Fmessaging\u002Fordering.spec.ts\nimport { describe, test, expect, beforeAll, afterAll, afterEach } from 'vitest';\nimport { WSTestClient } from '..\u002F..\u002Fhelpers\u002Fws-test-client';\nimport { WebSocketServer } from 'ws';\n\ndescribe('Message Ordering', () => {\n  let wss: WebSocketServer;\n  let client: WSTestClient;\n  const PORT = 8767;\n\n  beforeAll(() => {\n    wss = new WebSocketServer({ port: PORT });\n    wss.on('connection', (ws) => {\n      ws.on('message', (data) => {\n        \u002F\u002F Echo with server timestamp\n        const msg = JSON.parse(data.toString());\n        ws.send(\n          JSON.stringify({\n            ...msg,\n            serverTimestamp: Date.now(),\n          })\n        );\n      });\n    });\n  });\n\n  afterAll(() => wss.close());\n  afterEach(() => client?.close());\n\n  test('messages should arrive in order within a single connection', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`);\n    await client.connect();\n\n    const messageCount = 100;\n    const receivedPromise = new Promise\u003Cvoid>((resolve) => {\n      let count = 0;\n      client.on('message', () => {\n        count++;\n        if (count === messageCount) resolve();\n      });\n    });\n\n    \u002F\u002F Send 100 messages with sequence numbers\n    for (let i = 0; i \u003C messageCount; i++) {\n      client.send(JSON.stringify({ seq: i, data: `message-${i}` }));\n    }\n\n    await receivedPromise;\n\n    const messages = client.getMessages();\n    expect(messages).toHaveLength(messageCount);\n\n    \u002F\u002F Verify ordering\n    for (let i = 0; i \u003C messages.length; i++) {\n      const parsed = JSON.parse(messages[i].data as string);\n      expect(parsed.seq).toBe(i);\n    }\n  });\n\n  test('should detect out-of-order messages', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`);\n    await client.connect();\n\n    \u002F\u002F Create a server that deliberately reorders messages\n    const reorderWss = new WebSocketServer({ port: PORT + 1 });\n    const reorderClient = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT + 1}`);\n\n    reorderWss.on('connection', (ws) => {\n      const buffer: string[] = [];\n      ws.on('message', (data) => {\n        buffer.push(data.toString());\n        \u002F\u002F Every 3 messages, send them in reverse order\n        if (buffer.length === 3) {\n          buffer.reverse().forEach((msg) => ws.send(msg));\n          buffer.length = 0;\n        }\n      });\n    });\n\n    await reorderClient.connect();\n\n    const receivedPromise = new Promise\u003Cvoid>((resolve) => {\n      let count = 0;\n      reorderClient.on('message', () => {\n        count++;\n        if (count === 9) resolve();\n      });\n    });\n\n    for (let i = 0; i \u003C 9; i++) {\n      reorderClient.send(JSON.stringify({ seq: i }));\n    }\n\n    await receivedPromise;\n\n    const messages = reorderClient.getMessages();\n    const sequences = messages.map((m) => JSON.parse(m.data as string).seq);\n\n    \u002F\u002F Detect ordering violations\n    let outOfOrderCount = 0;\n    for (let i = 1; i \u003C sequences.length; i++) {\n      if (sequences[i] \u003C sequences[i - 1]) {\n        outOfOrderCount++;\n      }\n    }\n\n    expect(outOfOrderCount).toBeGreaterThan(0); \u002F\u002F Confirms reordering occurred\n\n    reorderClient.close();\n    reorderWss.close();\n  });\n\n  test('should handle duplicate message detection', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`);\n    await client.connect();\n\n    \u002F\u002F Server that sends duplicates\n    const dupWss = new WebSocketServer({ port: PORT + 2 });\n    const dupClient = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT + 2}`);\n\n    dupWss.on('connection', (ws) => {\n      ws.on('message', (data) => {\n        \u002F\u002F Send each message twice to simulate duplicates\n        ws.send(data);\n        ws.send(data);\n      });\n    });\n\n    await dupClient.connect();\n\n    const receivedPromise = new Promise\u003Cvoid>((resolve) => {\n      let count = 0;\n      dupClient.on('message', () => {\n        count++;\n        if (count === 6) resolve(); \u002F\u002F 3 messages x 2 duplicates\n      });\n    });\n\n    for (let i = 0; i \u003C 3; i++) {\n      dupClient.send(JSON.stringify({ id: `msg-${i}`, seq: i }));\n    }\n\n    await receivedPromise;\n\n    const messages = dupClient.getMessages();\n    const uniqueIds = new Set(messages.map((m) => JSON.parse(m.data as string).id));\n\n    \u002F\u002F Should detect duplicates\n    expect(messages.length).toBe(6); \u002F\u002F All messages received\n    expect(uniqueIds.size).toBe(3);  \u002F\u002F But only 3 unique\n\n    dupClient.close();\n    dupWss.close();\n  });\n});\n```\n\n## Heartbeat and Ping-Pong Testing\n\n```typescript\n\u002F\u002F tests\u002Fwebsocket\u002Fheartbeat\u002Fping-pong.spec.ts\nimport { describe, test, expect, beforeAll, afterAll, afterEach } from 'vitest';\nimport { WSTestClient } from '..\u002F..\u002Fhelpers\u002Fws-test-client';\nimport { WebSocketServer } from 'ws';\n\ndescribe('Heartbeat \u002F Ping-Pong', () => {\n  let wss: WebSocketServer;\n  let client: WSTestClient;\n  const PORT = 8768;\n\n  beforeAll(() => {\n    wss = new WebSocketServer({ port: PORT });\n    wss.on('connection', (ws) => {\n      \u002F\u002F Server responds to pings automatically (ws library default behavior)\n      ws.on('message', (data) => ws.send(data));\n    });\n  });\n\n  afterAll(() => wss.close());\n  afterEach(() => client?.close());\n\n  test('client should send periodic heartbeat pings', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`);\n    await client.connect();\n\n    let pongCount = 0;\n    client.on('pong', () => pongCount++);\n\n    \u002F\u002F Start heartbeat with 200ms interval for fast testing\n    client.startHeartbeat(200, 100);\n\n    \u002F\u002F Wait for several heartbeat cycles\n    await new Promise((resolve) => setTimeout(resolve, 1000));\n\n    \u002F\u002F Should have received multiple pong responses\n    expect(pongCount).toBeGreaterThanOrEqual(3);\n  });\n\n  test('should detect heartbeat timeout when server stops responding', async () => {\n    \u002F\u002F Create a server that does not respond to pings\n    const silentWss = new WebSocketServer({ port: PORT + 1 });\n    silentWss.on('connection', (ws) => {\n      \u002F\u002F Override the automatic pong response\n      ws.on('ping', () => {\n        \u002F\u002F Deliberately do not send pong\n      });\n    });\n\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT + 1}`, {\n      maxReconnectAttempts: 0,\n    });\n    await client.connect();\n\n    const timeoutPromise = new Promise\u003Cvoid>((resolve) => {\n      client.on('heartbeat-timeout', () => resolve());\n    });\n\n    client.startHeartbeat(200, 100);\n\n    \u002F\u002F Should detect timeout\n    await timeoutPromise;\n\n    \u002F\u002F Connection should be terminated\n    await new Promise((resolve) => setTimeout(resolve, 200));\n    expect(client.getState()).not.toBe(1); \u002F\u002F Not OPEN\n\n    silentWss.close();\n  });\n\n  test('heartbeat should reset timeout on each successful pong', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`);\n    await client.connect();\n\n    let timeoutOccurred = false;\n    client.on('heartbeat-timeout', () => {\n      timeoutOccurred = true;\n    });\n\n    \u002F\u002F Start heartbeat\n    client.startHeartbeat(100, 500);\n\n    \u002F\u002F Let it run for multiple cycles\n    await new Promise((resolve) => setTimeout(resolve, 2000));\n\n    \u002F\u002F No timeout should occur because server responds to pings\n    expect(timeoutOccurred).toBe(false);\n    expect(client.getState()).toBe(1); \u002F\u002F Still OPEN\n  });\n});\n```\n\n## Connection Drop Simulation\n\n### Simulating Network Disruptions in E2E Tests\n\n```typescript\n\u002F\u002F tests\u002Fwebsocket\u002Fresilience\u002Fnetwork-disruption.spec.ts\nimport { test, expect, Page } from '@playwright\u002Ftest';\n\ntest.describe('WebSocket Network Disruption', () => {\n  test('should reconnect after network interruption', async ({ page, context }) => {\n    await page.goto('\u002Fchat');\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Verify WebSocket is connected\n    await expect(page.locator('[data-testid=\"connection-status\"]')).toHaveText('Connected');\n\n    \u002F\u002F Send a message to confirm connectivity\n    await page.fill('[data-testid=\"message-input\"]', 'Hello before disconnect');\n    await page.click('[data-testid=\"send-button\"]');\n    await expect(page.locator('[data-testid=\"messages\"] >> text=Hello before disconnect')).toBeVisible();\n\n    \u002F\u002F Simulate network going offline\n    await context.setOffline(true);\n\n    \u002F\u002F Wait for the connection to be detected as lost\n    await expect(page.locator('[data-testid=\"connection-status\"]')).toHaveText(\n      \u002Fdisconnected|reconnecting\u002Fi,\n      { timeout: 10000 }\n    );\n\n    \u002F\u002F Restore network\n    await context.setOffline(false);\n\n    \u002F\u002F Should auto-reconnect\n    await expect(page.locator('[data-testid=\"connection-status\"]')).toHaveText(\n      'Connected',\n      { timeout: 15000 }\n    );\n\n    \u002F\u002F Verify messaging works after reconnection\n    await page.fill('[data-testid=\"message-input\"]', 'Hello after reconnect');\n    await page.click('[data-testid=\"send-button\"]');\n    await expect(\n      page.locator('[data-testid=\"messages\"] >> text=Hello after reconnect')\n    ).toBeVisible();\n  });\n\n  test('should queue messages sent during disconnection', async ({ page, context }) => {\n    await page.goto('\u002Fchat');\n    await page.waitForLoadState('networkidle');\n    await expect(page.locator('[data-testid=\"connection-status\"]')).toHaveText('Connected');\n\n    \u002F\u002F Go offline\n    await context.setOffline(true);\n    await expect(page.locator('[data-testid=\"connection-status\"]')).toHaveText(\n      \u002Fdisconnected|reconnecting\u002Fi,\n      { timeout: 10000 }\n    );\n\n    \u002F\u002F Try to send messages while disconnected\n    await page.fill('[data-testid=\"message-input\"]', 'Queued message 1');\n    await page.click('[data-testid=\"send-button\"]');\n    await page.fill('[data-testid=\"message-input\"]', 'Queued message 2');\n    await page.click('[data-testid=\"send-button\"]');\n\n    \u002F\u002F Messages should show as pending\n    await expect(page.locator('[data-testid=\"pending-indicator\"]').first()).toBeVisible();\n\n    \u002F\u002F Restore network\n    await context.setOffline(false);\n    await expect(page.locator('[data-testid=\"connection-status\"]')).toHaveText(\n      'Connected',\n      { timeout: 15000 }\n    );\n\n    \u002F\u002F Queued messages should be delivered\n    await expect(page.locator('[data-testid=\"pending-indicator\"]')).toHaveCount(0, {\n      timeout: 10000,\n    });\n    await expect(page.locator('text=Queued message 1')).toBeVisible();\n    await expect(page.locator('text=Queued message 2')).toBeVisible();\n  });\n\n  test('should handle slow network gracefully', async ({ page }) => {\n    \u002F\u002F Throttle the network to simulate a poor connection\n    const cdpSession = await page.context().newCDPSession(page);\n    await cdpSession.send('Network.emulateNetworkConditions', {\n      offline: false,\n      downloadThroughput: 5000,   \u002F\u002F 5 KB\u002Fs\n      uploadThroughput: 5000,     \u002F\u002F 5 KB\u002Fs\n      latency: 2000,              \u002F\u002F 2 seconds\n    });\n\n    await page.goto('\u002Fchat');\n\n    \u002F\u002F Connection should eventually establish even under slow conditions\n    await expect(page.locator('[data-testid=\"connection-status\"]')).toHaveText(\n      'Connected',\n      { timeout: 30000 }\n    );\n\n    \u002F\u002F Messages should still work (possibly with delay)\n    await page.fill('[data-testid=\"message-input\"]', 'Slow network message');\n    await page.click('[data-testid=\"send-button\"]');\n\n    await expect(page.locator('text=Slow network message')).toBeVisible({\n      timeout: 15000,\n    });\n\n    \u002F\u002F Reset network conditions\n    await cdpSession.send('Network.emulateNetworkConditions', {\n      offline: false,\n      downloadThroughput: -1,\n      uploadThroughput: -1,\n      latency: 0,\n    });\n  });\n});\n```\n\n## Authentication Token Refresh During WebSocket Sessions\n\n```typescript\n\u002F\u002F tests\u002Fwebsocket\u002Fconnection\u002Fauthentication.spec.ts\nimport { describe, test, expect, beforeAll, afterAll, afterEach } from 'vitest';\nimport { WSTestClient } from '..\u002F..\u002Fhelpers\u002Fws-test-client';\nimport { WebSocketServer, WebSocket } from 'ws';\nimport { IncomingMessage } from 'http';\n\ndescribe('WebSocket Authentication', () => {\n  let wss: WebSocketServer;\n  let client: WSTestClient;\n  const PORT = 8769;\n\n  beforeAll(() => {\n    wss = new WebSocketServer({\n      port: PORT,\n      verifyClient: (info: { req: IncomingMessage }) => {\n        const token = info.req.headers['authorization'];\n        \u002F\u002F Accept connections with valid tokens\n        return token === 'Bearer valid-token' || token === 'Bearer refreshed-token';\n      },\n    });\n\n    wss.on('connection', (ws) => {\n      ws.send(JSON.stringify({ type: 'auth_success' }));\n      ws.on('message', (data) => ws.send(data));\n    });\n  });\n\n  afterAll(() => wss.close());\n  afterEach(() => client?.close());\n\n  test('should connect with valid authentication token', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n      headers: { Authorization: 'Bearer valid-token' },\n    });\n\n    await client.connect();\n    expect(client.getState()).toBe(WebSocket.OPEN);\n\n    \u002F\u002F Wait for auth success message\n    await new Promise\u003Cvoid>((resolve) => {\n      client.on('message', (msg) => {\n        const parsed = JSON.parse(msg.data as string);\n        if (parsed.type === 'auth_success') resolve();\n      });\n    });\n  });\n\n  test('should reject connection with invalid token', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n      headers: { Authorization: 'Bearer invalid-token' },\n      maxReconnectAttempts: 0,\n    });\n\n    await expect(client.connect()).rejects.toThrow();\n  });\n\n  test('should reconnect with refreshed token after auth expiry', async () => {\n    let connectionCount = 0;\n\n    const authWss = new WebSocketServer({\n      port: PORT + 1,\n      verifyClient: (info: { req: IncomingMessage }) => {\n        connectionCount++;\n        if (connectionCount === 1) return true;  \u002F\u002F First connection succeeds\n        if (connectionCount === 2) return false;  \u002F\u002F Simulate token expiry\n        return true;  \u002F\u002F Third attempt with refreshed token succeeds\n      },\n    });\n\n    authWss.on('connection', (ws) => {\n      ws.on('message', (data) => ws.send(data));\n    });\n\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT + 1}`, {\n      maxReconnectAttempts: 3,\n      reconnectDelay: 100,\n    });\n\n    await client.connect();\n    expect(client.getState()).toBe(WebSocket.OPEN);\n\n    \u002F\u002F Simulate server-side token expiry by closing connection\n    authWss.clients.forEach((ws) => ws.close(4001, 'Token expired'));\n\n    \u002F\u002F Wait for reconnection attempts\n    await new Promise((resolve) => setTimeout(resolve, 2000));\n\n    \u002F\u002F Client should have attempted to reconnect\n    expect(connectionCount).toBeGreaterThanOrEqual(2);\n\n    authWss.close();\n  });\n});\n```\n\n## Backpressure Testing\n\n```typescript\n\u002F\u002F tests\u002Fwebsocket\u002Fresilience\u002Fbackpressure.spec.ts\nimport { describe, test, expect, beforeAll, afterAll, afterEach } from 'vitest';\nimport { WSTestClient } from '..\u002F..\u002Fhelpers\u002Fws-test-client';\nimport { WebSocketServer, WebSocket } from 'ws';\n\ndescribe('WebSocket Backpressure', () => {\n  let wss: WebSocketServer;\n  let client: WSTestClient;\n  const PORT = 8770;\n\n  beforeAll(() => {\n    wss = new WebSocketServer({ port: PORT });\n    wss.on('connection', (ws) => {\n      ws.on('message', (data) => {\n        \u002F\u002F Simulate slow processing\n        setTimeout(() => ws.send(data), 10);\n      });\n    });\n  });\n\n  afterAll(() => wss.close());\n  afterEach(() => client?.close());\n\n  test('should handle burst of messages without dropping', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`);\n    await client.connect();\n\n    const messageCount = 500;\n    let received = 0;\n\n    const allReceived = new Promise\u003Cvoid>((resolve) => {\n      client.on('message', () => {\n        received++;\n        if (received === messageCount) resolve();\n      });\n    });\n\n    \u002F\u002F Send burst of messages\n    for (let i = 0; i \u003C messageCount; i++) {\n      client.send(JSON.stringify({ seq: i, data: 'x'.repeat(100) }));\n    }\n\n    await allReceived;\n\n    expect(received).toBe(messageCount);\n\n    \u002F\u002F Verify no messages were dropped\n    const messages = client.getMessages();\n    const sequences = messages.map((m) => JSON.parse(m.data as string).seq);\n    const uniqueSequences = new Set(sequences);\n    expect(uniqueSequences.size).toBe(messageCount);\n  });\n\n  test('should handle large payloads', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`);\n    await client.connect();\n\n    \u002F\u002F Send increasingly large messages\n    const sizes = [1024, 10240, 102400, 1048576]; \u002F\u002F 1KB, 10KB, 100KB, 1MB\n\n    for (const size of sizes) {\n      const payload = JSON.stringify({\n        size,\n        data: 'x'.repeat(size),\n      });\n\n      const responsePromise = new Promise\u003Cvoid>((resolve) => {\n        client.once('message', () => resolve());\n      });\n\n      client.send(payload);\n      await responsePromise;\n\n      const lastMessage = client.getMessages().at(-1);\n      expect(lastMessage).toBeDefined();\n\n      const parsed = JSON.parse(lastMessage!.data as string);\n      expect(parsed.data.length).toBe(size);\n    }\n  });\n});\n```\n\n## Concurrent Connection Limits\n\n```typescript\n\u002F\u002F tests\u002Fwebsocket\u002Fconnection\u002Fconcurrent-connections.spec.ts\nimport { describe, test, expect, beforeAll, afterAll } from 'vitest';\nimport { WSTestClient } from '..\u002F..\u002Fhelpers\u002Fws-test-client';\nimport { WebSocketServer } from 'ws';\n\ndescribe('Concurrent WebSocket Connections', () => {\n  let wss: WebSocketServer;\n  const PORT = 8771;\n  const MAX_CONNECTIONS = 10;\n\n  beforeAll(() => {\n    wss = new WebSocketServer({ port: PORT });\n    let connectionCount = 0;\n\n    wss.on('connection', (ws) => {\n      connectionCount++;\n\n      if (connectionCount > MAX_CONNECTIONS) {\n        ws.close(4029, 'Too many connections');\n        return;\n      }\n\n      ws.on('message', (data) => ws.send(data));\n      ws.on('close', () => connectionCount--);\n    });\n  });\n\n  afterAll(() => wss.close());\n\n  test('should handle multiple concurrent connections', async () => {\n    const clients: WSTestClient[] = [];\n    const count = 5;\n\n    for (let i = 0; i \u003C count; i++) {\n      const client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n        maxReconnectAttempts: 0,\n      });\n      await client.connect();\n      clients.push(client);\n    }\n\n    \u002F\u002F All clients should be connected\n    for (const client of clients) {\n      expect(client.getStateName()).toBe('OPEN');\n    }\n\n    \u002F\u002F All clients should be able to send and receive\n    for (let i = 0; i \u003C clients.length; i++) {\n      const responsePromise = new Promise\u003Cvoid>((resolve) => {\n        clients[i].once('message', () => resolve());\n      });\n      clients[i].send(JSON.stringify({ client: i }));\n      await responsePromise;\n    }\n\n    \u002F\u002F Clean up\n    clients.forEach((c) => c.close());\n  });\n\n  test('should reject connections beyond the limit', async () => {\n    const clients: WSTestClient[] = [];\n\n    \u002F\u002F Fill up to the limit\n    for (let i = 0; i \u003C MAX_CONNECTIONS; i++) {\n      const client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n        maxReconnectAttempts: 0,\n      });\n      await client.connect();\n      clients.push(client);\n    }\n\n    \u002F\u002F The next connection should be rejected\n    const extraClient = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n      maxReconnectAttempts: 0,\n    });\n\n    await extraClient.connect();\n\n    \u002F\u002F Should receive a close frame with the rejection code\n    const closePromise = new Promise\u003Cnumber>((resolve) => {\n      extraClient.on('close', (code) => resolve(code));\n    });\n\n    const code = await closePromise;\n    expect(code).toBe(4029);\n\n    \u002F\u002F Clean up\n    clients.forEach((c) => c.close());\n    extraClient.close();\n  });\n});\n```\n\n## Configuration\n\n### Playwright Configuration for WebSocket E2E Tests\n\n```typescript\n\u002F\u002F playwright.config.ts\nimport { defineConfig, devices } from '@playwright\u002Ftest';\n\nexport default defineConfig({\n  testDir: '.\u002Ftests\u002Fwebsocket\u002Fe2e',\n  fullyParallel: false, \u002F\u002F WebSocket tests may share server state\n  retries: 2,\n  timeout: 30000,\n  reporter: [\n    ['html', { open: 'never' }],\n    ['json', { outputFile: 'ws-test-results.json' }],\n  ],\n  use: {\n    baseURL: process.env.BASE_URL || 'http:\u002F\u002Flocalhost:3000',\n    trace: 'on-first-retry',\n    screenshot: 'only-on-failure',\n    video: 'retain-on-failure',\n  },\n  projects: [\n    {\n      name: 'ws-chrome',\n      use: { ...devices['Desktop Chrome'] },\n    },\n    {\n      name: 'ws-firefox',\n      use: { ...devices['Desktop Firefox'] },\n    },\n    {\n      name: 'ws-mobile',\n      use: { ...devices['iPhone 14'] },\n    },\n  ],\n});\n```\n\n### WebSocket Test Configuration\n\n```typescript\n\u002F\u002F config\u002Fws-test-config.ts\nexport const WS_TEST_CONFIG = {\n  \u002F\u002F Server configuration\n  serverUrl: process.env.WS_SERVER_URL || 'ws:\u002F\u002Flocalhost:8080',\n  serverPort: parseInt(process.env.WS_TEST_PORT || '8080', 10),\n\n  \u002F\u002F Connection settings\n  connectTimeout: 5000,\n  maxReconnectAttempts: 5,\n  reconnectBaseDelay: 1000,\n  reconnectMaxDelay: 30000,\n\n  \u002F\u002F Heartbeat settings\n  heartbeatInterval: 30000,\n  heartbeatTimeout: 5000,\n\n  \u002F\u002F Message settings\n  maxMessageSize: 1048576,  \u002F\u002F 1MB\n  messageTimeout: 10000,\n\n  \u002F\u002F Test data\n  burstMessageCount: 500,\n  concurrentClientCount: 10,\n  largePayloadSizes: [1024, 10240, 102400, 1048576],\n};\n```\n\n## Best Practices\n\n1. **Always implement exponential backoff with jitter for reconnection** -- A fixed reconnect interval causes all disconnected clients to reconnect simultaneously, creating a \"thundering herd\" that can overwhelm the server. Add random jitter to spread reconnection attempts.\n\n2. **Use connection state machines** -- Model the WebSocket lifecycle as a state machine with explicit states (DISCONNECTED, CONNECTING, CONNECTED, RECONNECTING) and valid transitions. This prevents impossible state combinations like sending messages while disconnected.\n\n3. **Implement message acknowledgment for critical operations** -- For messages that must not be lost (e.g., financial transactions, chat messages), implement application-level acknowledgments. Do not rely solely on TCP delivery guarantees.\n\n4. **Test with real-world disconnect scenarios** -- Lab-perfect connections hide bugs. Test with WiFi-to-cellular transitions, VPN disconnects, laptop lid close\u002Fopen, and browser tab backgrounding.\n\n5. **Add sequence numbers to messages** -- Every message should include a monotonically increasing sequence number. This enables detection of gaps, duplicates, and reordering on the receiving end.\n\n6. **Handle the \"half-open\" connection state** -- A TCP connection can appear open on one side while closed on the other. Heartbeats detect this condition. Without heartbeats, a client may believe it is connected while the server has already dropped the connection.\n\n7. **Buffer messages during reconnection** -- Messages sent while the WebSocket is reconnecting should be queued and delivered once the connection is re-established, not silently dropped.\n\n8. **Test binary message handling separately from text** -- Binary frames (ArrayBuffer, Blob) and text frames have different serialization paths. Test both frame types to ensure the application handles each correctly.\n\n9. **Implement connection pooling for multiple channels** -- Applications that need multiple logical channels should multiplex over a single WebSocket connection rather than opening separate connections per channel.\n\n10. **Set appropriate close codes** -- Use RFC 6455 close codes correctly: 1000 (normal), 1001 (going away), 1008 (policy violation), 1011 (unexpected condition). Custom codes should be in the 4000-4999 range.\n\n11. **Test WebSocket behavior across browser tabs** -- Browsers may throttle or suspend WebSocket connections in background tabs. Test that reconnection works correctly when a user returns to a backgrounded tab.\n\n12. **Monitor WebSocket connection metrics in production** -- Track connection duration, reconnection frequency, message latency, and error rates. These metrics reveal reliability issues that tests alone cannot catch.\n\n## Anti-Patterns to Avoid\n\n1. **Reconnecting immediately without backoff** -- Instant reconnection creates a retry storm that wastes bandwidth and can trigger rate limiting or server overload. Always use exponential backoff.\n\n2. **Silently dropping messages during disconnection** -- When a user sends a chat message during a brief disconnect and the message disappears, it erodes trust. Queue messages and deliver them after reconnection.\n\n3. **Using WebSocket as the only data channel** -- WebSocket connections are not guaranteed to stay open. Critical operations should have an HTTP fallback. Do not build flows that are impossible to complete without a persistent WebSocket.\n\n4. **Ignoring close frames and codes** -- Different close codes have different meanings. Code 1001 (going away) suggests the server is restarting and reconnection will likely succeed. Code 1008 (policy violation) suggests the client should not reconnect.\n\n5. **Opening a new WebSocket per request** -- WebSocket's advantage is persistent connections. Opening and closing a WebSocket for each message negates the protocol's benefits and adds significant overhead.\n\n6. **Trusting message order across reconnections** -- A new WebSocket connection is a new TCP stream. Messages in transit during reconnection may be lost or arrive on the new connection out of order. Always use sequence numbers.\n\n7. **Not testing concurrent connection limits** -- Browsers enforce per-domain WebSocket limits. Applications that open too many connections will silently fail to connect, causing features to break with no visible error.\n\n## Debugging Tips\n\n1. **Use Chrome DevTools WebSocket inspector** -- The Network tab in Chrome DevTools shows individual WebSocket frames (both sent and received). Filter by \"WS\" to see only WebSocket traffic. Click on a connection to inspect individual frames.\n\n2. **Log connection state transitions** -- Add logging for every state change: CONNECTING, OPEN, CLOSING, CLOSED, and any custom states like RECONNECTING. This trace is invaluable for debugging intermittent connection issues.\n\n3. **Check for load balancer idle timeout** -- Many load balancers (AWS ALB, nginx) close idle WebSocket connections after 60 seconds. If connections drop without heartbeat activity, the load balancer timeout is the likely culprit.\n\n4. **Verify WebSocket upgrade headers** -- Use `curl -i -N -H \"Connection: Upgrade\" -H \"Upgrade: websocket\"` to verify the server responds with a 101 Switching Protocols response. A 200 OK indicates the upgrade failed.\n\n5. **Test with `wscat` for quick manual verification** -- The `wscat` command-line tool (`npx wscat -c ws:\u002F\u002Flocalhost:8080`) provides a simple way to interactively test WebSocket endpoints without building a test client.\n\n6. **Monitor `readyState` before sending** -- Always check `ws.readyState === WebSocket.OPEN` before calling `ws.send()`. Sending on a non-OPEN socket throws an error that may not be caught by error boundaries.\n\n7. **Check for CORS issues on WebSocket upgrade** -- While the WebSocket protocol itself does not enforce CORS, some reverse proxies and CDNs may block WebSocket upgrade requests based on Origin headers. Check server logs for rejected upgrade requests.\n\n8. **Use Wireshark to inspect WebSocket frames at the protocol level** -- When high-level debugging is insufficient, Wireshark can decode WebSocket frames and show the raw binary content, opcode, masking, and frame boundaries.\n\n9. **Verify that ping\u002Fpong frames are not confused with application messages** -- WebSocket control frames (ping, pong, close) are distinct from data frames. Ensure your message handler does not process control frames as application messages.\n\n10. **Test reconnection with server-side logging** -- Log connection and disconnection events on the server with client identifiers. Compare server-side logs with client-side reconnection logs to identify mismatches where the client believes it is connected but the server does not have a matching connection.\n","# WebSocket Bug Finder Skill\n\nYou are an expert QA automation engineer specializing in WebSocket and real-time communication testing. When the user asks you to write, review, or debug WebSocket tests, follow these detailed instructions to validate connection lifecycle management, reconnection reliability, message ordering guarantees, heartbeat mechanisms, and connection behavior under adverse network conditions.\n\n## Core Principles\n\n1. **Connections are ephemeral** -- WebSocket connections will drop unexpectedly due to network changes, server restarts, load balancer timeouts, and mobile device sleep. Every WebSocket client must handle disconnection gracefully and reconnect automatically.\n2. **Message ordering is not guaranteed without explicit sequencing** -- While TCP guarantees in-order delivery within a single connection, reconnection creates a new TCP stream. Messages sent during reconnection may arrive out of order. Test that applications handle sequence gaps correctly.\n3. **Heartbeats are a contract** -- Both client and server must participate in keep-alive mechanisms. Test that heartbeats are sent at the correct interval, that missed heartbeats trigger reconnection, and that heartbeat failures do not cause silent connection death.\n4. **Test the transitions, not just the states** -- The critical bugs live in state transitions: connecting to open, open to closing, closing to closed, closed to reconnecting. Test every transition path, especially the error paths.\n5. **Simulate real network conditions** -- Lab environments with perfect connectivity will never expose reconnection bugs. Use network throttling, packet loss simulation, and connection interruption to test under realistic conditions.\n6. **Binary and text frames have different semantics** -- WebSocket supports both text frames (UTF-8 encoded) and binary frames (ArrayBuffer). Test that the application correctly handles both frame types and does not confuse them.\n7. **Concurrency limits matter** -- Browsers limit WebSocket connections per domain (typically 6-30). Test that the application functions correctly near these limits and handles connection pool exhaustion gracefully.\n\n## Project Structure\n\nOrganize WebSocket testing projects with this structure:\n\n```\ntests\u002F\n  websocket\u002F\n    connection\u002F\n      lifecycle.spec.ts\n      reconnection.spec.ts\n      authentication.spec.ts\n      concurrent-connections.spec.ts\n    messaging\u002F\n      ordering.spec.ts\n      delivery-guarantee.spec.ts\n      binary-messages.spec.ts\n      large-payloads.spec.ts\n    heartbeat\u002F\n      ping-pong.spec.ts\n      timeout-detection.spec.ts\n      keep-alive.spec.ts\n    resilience\u002F\n      network-disruption.spec.ts\n      server-restart.spec.ts\n      backpressure.spec.ts\n    e2e\u002F\n      real-time-updates.spec.ts\n      collaborative-editing.spec.ts\n      chat-messaging.spec.ts\n  helpers\u002F\n    ws-test-client.ts\n    ws-message-recorder.ts\n    network-simulator.ts\n    ws-server-mock.ts\n  fixtures\u002F\n    websocket.fixture.ts\n  config\u002F\n    ws-test-config.ts\nplaywright.config.ts\n```\n\n## WebSocket Connection Lifecycle Testing\n\n### Test Client Helper\n\n```typescript\n\u002F\u002F helpers\u002Fws-test-client.ts\nimport WebSocket from 'ws';\nimport { EventEmitter } from 'events';\n\ninterface WSMessage {\n  data: string | Buffer;\n  timestamp: number;\n  type: 'text' | 'binary';\n  sequence?: number;\n}\n\ninterface ConnectionEvent {\n  type: 'open' | 'close' | 'error' | 'message' | 'reconnect';\n  timestamp: number;\n  details?: unknown;\n}\n\nexport class WSTestClient extends EventEmitter {\n  private ws: WebSocket | null = null;\n  private url: string;\n  private messages: WSMessage[] = [];\n  private events: ConnectionEvent[] = [];\n  private reconnectAttempts = 0;\n  private maxReconnectAttempts = 5;\n  private reconnectDelay = 1000;\n  private shouldReconnect = true;\n  private heartbeatInterval: NodeJS.Timeout | null = null;\n  private heartbeatTimeout: NodeJS.Timeout | null = null;\n  private headers: Record\u003Cstring, string>;\n\n  constructor(\n    url: string,\n    options: {\n      headers?: Record\u003Cstring, string>;\n      maxReconnectAttempts?: number;\n      reconnectDelay?: number;\n    } = {}\n  ) {\n    super();\n    this.url = url;\n    this.headers = options.headers || {};\n    this.maxReconnectAttempts = options.maxReconnectAttempts ?? 5;\n    this.reconnectDelay = options.reconnectDelay ?? 1000;\n  }\n\n  connect(): Promise\u003Cvoid> {\n    return new Promise((resolve, reject) => {\n      this.ws = new WebSocket(this.url, { headers: this.headers });\n\n      this.ws.on('open', () => {\n        this.reconnectAttempts = 0;\n        this.recordEvent('open');\n        this.emit('open');\n        resolve();\n      });\n\n      this.ws.on('message', (data: WebSocket.Data) => {\n        const message: WSMessage = {\n          data: data instanceof Buffer ? data : data.toString(),\n          timestamp: Date.now(),\n          type: data instanceof Buffer ? 'binary' : 'text',\n        };\n\n        \u002F\u002F Extract sequence number if present\n        if (typeof message.data === 'string') {\n          try {\n            const parsed = JSON.parse(message.data);\n            if (parsed.seq !== undefined) {\n              message.sequence = parsed.seq;\n            }\n          } catch {\n            \u002F\u002F Not JSON, that is fine\n          }\n        }\n\n        this.messages.push(message);\n        this.recordEvent('message', message);\n        this.emit('message', message);\n      });\n\n      this.ws.on('close', (code, reason) => {\n        this.recordEvent('close', { code, reason: reason.toString() });\n        this.emit('close', code, reason);\n        this.stopHeartbeat();\n\n        if (this.shouldReconnect && this.reconnectAttempts \u003C this.maxReconnectAttempts) {\n          this.attemptReconnect();\n        }\n      });\n\n      this.ws.on('error', (error) => {\n        this.recordEvent('error', { message: error.message });\n        this.emit('error', error);\n        reject(error);\n      });\n    });\n  }\n\n  private async attemptReconnect(): Promise\u003Cvoid> {\n    this.reconnectAttempts++;\n    const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);\n    this.recordEvent('reconnect', { attempt: this.reconnectAttempts, delay });\n\n    await new Promise((resolve) => setTimeout(resolve, delay));\n\n    try {\n      await this.connect();\n    } catch {\n      \u002F\u002F Reconnect failed, will retry if under max attempts\n    }\n  }\n\n  send(data: string | Buffer): void {\n    if (this.ws?.readyState !== WebSocket.OPEN) {\n      throw new Error(`Cannot send: WebSocket is ${this.getStateName()}`);\n    }\n    this.ws.send(data);\n  }\n\n  startHeartbeat(intervalMs: number = 30000, timeoutMs: number = 5000): void {\n    this.heartbeatInterval = setInterval(() => {\n      if (this.ws?.readyState === WebSocket.OPEN) {\n        this.ws.ping();\n\n        this.heartbeatTimeout = setTimeout(() => {\n          \u002F\u002F No pong received within timeout\n          this.emit('heartbeat-timeout');\n          this.ws?.terminate();\n        }, timeoutMs);\n      }\n    }, intervalMs);\n\n    this.ws?.on('pong', () => {\n      if (this.heartbeatTimeout) {\n        clearTimeout(this.heartbeatTimeout);\n        this.heartbeatTimeout = null;\n      }\n      this.emit('pong');\n    });\n  }\n\n  stopHeartbeat(): void {\n    if (this.heartbeatInterval) {\n      clearInterval(this.heartbeatInterval);\n      this.heartbeatInterval = null;\n    }\n    if (this.heartbeatTimeout) {\n      clearTimeout(this.heartbeatTimeout);\n      this.heartbeatTimeout = null;\n    }\n  }\n\n  close(code: number = 1000, reason: string = 'Test complete'): void {\n    this.shouldReconnect = false;\n    this.stopHeartbeat();\n    this.ws?.close(code, reason);\n  }\n\n  getMessages(): WSMessage[] {\n    return [...this.messages];\n  }\n\n  getEvents(): ConnectionEvent[] {\n    return [...this.events];\n  }\n\n  getState(): number {\n    return this.ws?.readyState ?? WebSocket.CLOSED;\n  }\n\n  getStateName(): string {\n    const states: Record\u003Cnumber, string> = {\n      [WebSocket.CONNECTING]: 'CONNECTING',\n      [WebSocket.OPEN]: 'OPEN',\n      [WebSocket.CLOSING]: 'CLOSING',\n      [WebSocket.CLOSED]: 'CLOSED',\n    };\n    return states[this.getState()] || 'UNKNOWN';\n  }\n\n  getReconnectAttempts(): number {\n    return this.reconnectAttempts;\n  }\n\n  clearMessages(): void {\n    this.messages = [];\n  }\n\n  private recordEvent(type: ConnectionEvent['type'], details?: unknown): void {\n    this.events.push({ type, timestamp: Date.now(), details });\n  }\n}\n```\n\n### Connection Lifecycle Tests\n\n```typescript\n\u002F\u002F tests\u002Fwebsocket\u002Fconnection\u002Flifecycle.spec.ts\nimport { describe, test, expect, beforeAll, afterAll, afterEach } from 'vitest';\nimport { WSTestClient } from '..\u002F..\u002Fhelpers\u002Fws-test-client';\nimport { WebSocketServer, WebSocket } from 'ws';\n\nlet wss: WebSocketServer;\nconst PORT = 8765;\nconst WS_URL = `ws:\u002F\u002Flocalhost:${PORT}`;\n\nbeforeAll(() => {\n  wss = new WebSocketServer({ port: PORT });\n  wss.on('connection', (ws) => {\n    ws.on('message', (data) => {\n      \u002F\u002F Echo messages back\n      ws.send(data);\n    });\n  });\n});\n\nafterAll(() => {\n  wss.close();\n});\n\ndescribe('WebSocket Connection Lifecycle', () => {\n  let client: WSTestClient;\n\n  afterEach(() => {\n    client?.close();\n  });\n\n  test('should establish connection and reach OPEN state', async () => {\n    client = new WSTestClient(WS_URL);\n    await client.connect();\n\n    expect(client.getState()).toBe(WebSocket.OPEN);\n    expect(client.getStateName()).toBe('OPEN');\n\n    const events = client.getEvents();\n    expect(events[0].type).toBe('open');\n  });\n\n  test('should perform clean close with code 1000', async () => {\n    client = new WSTestClient(WS_URL);\n    await client.connect();\n\n    const closePromise = new Promise\u003C{ code: number; reason: Buffer }>((resolve) => {\n      client.on('close', (code, reason) => resolve({ code, reason }));\n    });\n\n    client.close(1000, 'Normal closure');\n    const result = await closePromise;\n\n    expect(result.code).toBe(1000);\n    expect(client.getState()).toBe(WebSocket.CLOSED);\n  });\n\n  test('should record all lifecycle events in order', async () => {\n    client = new WSTestClient(WS_URL);\n    await client.connect();\n\n    client.send('test message');\n\n    \u002F\u002F Wait for echo\n    await new Promise\u003Cvoid>((resolve) => {\n      client.on('message', () => resolve());\n    });\n\n    client.close();\n\n    await new Promise\u003Cvoid>((resolve) => {\n      client.on('close', () => resolve());\n    });\n\n    const events = client.getEvents();\n    const eventTypes = events.map((e) => e.type);\n\n    expect(eventTypes[0]).toBe('open');\n    expect(eventTypes).toContain('message');\n    expect(eventTypes[eventTypes.length - 1]).toBe('close');\n\n    \u002F\u002F Events should be in chronological order\n    for (let i = 1; i \u003C events.length; i++) {\n      expect(events[i].timestamp).toBeGreaterThanOrEqual(events[i - 1].timestamp);\n    }\n  });\n\n  test('should handle server-initiated close', async () => {\n    client = new WSTestClient(WS_URL, { maxReconnectAttempts: 0 });\n    await client.connect();\n\n    const closePromise = new Promise\u003Cnumber>((resolve) => {\n      client.on('close', (code) => resolve(code));\n    });\n\n    \u002F\u002F Close from server side\n    wss.clients.forEach((ws) => {\n      ws.close(1001, 'Server going away');\n    });\n\n    const code = await closePromise;\n    expect(code).toBe(1001);\n  });\n\n  test('should reject connection to invalid URL', async () => {\n    client = new WSTestClient('ws:\u002F\u002Flocalhost:9999', { maxReconnectAttempts: 0 });\n\n    await expect(client.connect()).rejects.toThrow();\n    expect(client.getState()).toBe(WebSocket.CLOSED);\n  });\n});\n```\n\n## Reconnection Logic Verification\n\n```typescript\n\u002F\u002F tests\u002Fwebsocket\u002Fconnection\u002Freconnection.spec.ts\nimport { describe, test, expect, afterEach } from 'vitest';\nimport { WSTestClient } from '..\u002F..\u002Fhelpers\u002Fws-test-client';\nimport { WebSocketServer, WebSocket } from 'ws';\n\ndescribe('WebSocket Reconnection', () => {\n  let wss: WebSocketServer;\n  let client: WSTestClient;\n  const PORT = 8766;\n\n  afterEach(() => {\n    client?.close();\n    wss?.close();\n  });\n\n  test('should automatically reconnect after server disconnect', async () => {\n    wss = new WebSocketServer({ port: PORT });\n\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n      maxReconnectAttempts: 3,\n      reconnectDelay: 100,\n    });\n\n    await client.connect();\n    expect(client.getState()).toBe(WebSocket.OPEN);\n\n    \u002F\u002F Track reconnection\n    const reconnectPromise = new Promise\u003Cvoid>((resolve) => {\n      client.on('open', () => resolve());\n    });\n\n    \u002F\u002F Force disconnect from server side\n    wss.clients.forEach((ws) => ws.terminate());\n\n    \u002F\u002F Wait for reconnection\n    await reconnectPromise;\n    expect(client.getState()).toBe(WebSocket.OPEN);\n    expect(client.getReconnectAttempts()).toBeGreaterThanOrEqual(1);\n  });\n\n  test('should use exponential backoff for reconnection attempts', async () => {\n    \u002F\u002F Start server, connect, then stop server to force reconnect failures\n    wss = new WebSocketServer({ port: PORT });\n\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n      maxReconnectAttempts: 4,\n      reconnectDelay: 100,\n    });\n\n    await client.connect();\n\n    \u002F\u002F Close server to prevent reconnection\n    wss.close();\n\n    \u002F\u002F Force disconnect\n    client['ws']?.terminate();\n\n    \u002F\u002F Wait for all reconnection attempts to fail\n    await new Promise((resolve) => setTimeout(resolve, 5000));\n\n    const events = client.getEvents().filter((e) => e.type === 'reconnect');\n\n    \u002F\u002F Verify exponential backoff pattern\n    for (let i = 1; i \u003C events.length; i++) {\n      const prevDelay = (events[i - 1].details as { delay: number }).delay;\n      const currDelay = (events[i].details as { delay: number }).delay;\n      expect(currDelay).toBeGreaterThanOrEqual(prevDelay);\n    }\n  });\n\n  test('should stop reconnecting after max attempts', async () => {\n    const maxAttempts = 3;\n\n    wss = new WebSocketServer({ port: PORT });\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n      maxReconnectAttempts: maxAttempts,\n      reconnectDelay: 50,\n    });\n\n    await client.connect();\n    wss.close();\n    client['ws']?.terminate();\n\n    \u002F\u002F Wait for all attempts to exhaust\n    await new Promise((resolve) => setTimeout(resolve, 3000));\n\n    const reconnectEvents = client.getEvents().filter((e) => e.type === 'reconnect');\n    expect(reconnectEvents.length).toBeLessThanOrEqual(maxAttempts);\n  });\n\n  test('should reset reconnect counter after successful connection', async () => {\n    wss = new WebSocketServer({ port: PORT });\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n      maxReconnectAttempts: 5,\n      reconnectDelay: 100,\n    });\n\n    await client.connect();\n\n    \u002F\u002F First disconnect and reconnect\n    const firstReconnect = new Promise\u003Cvoid>((resolve) => {\n      client.once('open', () => resolve());\n    });\n    wss.clients.forEach((ws) => ws.terminate());\n    await firstReconnect;\n\n    \u002F\u002F After successful reconnect, counter should reset\n    expect(client.getReconnectAttempts()).toBe(0);\n\n    \u002F\u002F Second disconnect and reconnect should also work\n    const secondReconnect = new Promise\u003Cvoid>((resolve) => {\n      client.once('open', () => resolve());\n    });\n    wss.clients.forEach((ws) => ws.terminate());\n    await secondReconnect;\n\n    expect(client.getState()).toBe(WebSocket.OPEN);\n  });\n});\n```\n\n## Message Ordering and Delivery Guarantees\n\n```typescript\n\u002F\u002F tests\u002Fwebsocket\u002Fmessaging\u002Fordering.spec.ts\nimport { describe, test, expect, beforeAll, afterAll, afterEach } from 'vitest';\nimport { WSTestClient } from '..\u002F..\u002Fhelpers\u002Fws-test-client';\nimport { WebSocketServer } from 'ws';\n\ndescribe('Message Ordering', () => {\n  let wss: WebSocketServer;\n  let client: WSTestClient;\n  const PORT = 8767;\n\n  beforeAll(() => {\n    wss = new WebSocketServer({ port: PORT });\n    wss.on('connection', (ws) => {\n      ws.on('message', (data) => {\n        \u002F\u002F Echo with server timestamp\n        const msg = JSON.parse(data.toString());\n        ws.send(\n          JSON.stringify({\n            ...msg,\n            serverTimestamp: Date.now(),\n          })\n        );\n      });\n    });\n  });\n\n  afterAll(() => wss.close());\n  afterEach(() => client?.close());\n\n  test('messages should arrive in order within a single connection', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`);\n    await client.connect();\n\n    const messageCount = 100;\n    const receivedPromise = new Promise\u003Cvoid>((resolve) => {\n      let count = 0;\n      client.on('message', () => {\n        count++;\n        if (count === messageCount) resolve();\n      });\n    });\n\n    \u002F\u002F Send 100 messages with sequence numbers\n    for (let i = 0; i \u003C messageCount; i++) {\n      client.send(JSON.stringify({ seq: i, data: `message-${i}` }));\n    }\n\n    await receivedPromise;\n\n    const messages = client.getMessages();\n    expect(messages).toHaveLength(messageCount);\n\n    \u002F\u002F Verify ordering\n    for (let i = 0; i \u003C messages.length; i++) {\n      const parsed = JSON.parse(messages[i].data as string);\n      expect(parsed.seq).toBe(i);\n    }\n  });\n\n  test('should detect out-of-order messages', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`);\n    await client.connect();\n\n    \u002F\u002F Create a server that deliberately reorders messages\n    const reorderWss = new WebSocketServer({ port: PORT + 1 });\n    const reorderClient = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT + 1}`);\n\n    reorderWss.on('connection', (ws) => {\n      const buffer: string[] = [];\n      ws.on('message', (data) => {\n        buffer.push(data.toString());\n        \u002F\u002F Every 3 messages, send them in reverse order\n        if (buffer.length === 3) {\n          buffer.reverse().forEach((msg) => ws.send(msg));\n          buffer.length = 0;\n        }\n      });\n    });\n\n    await reorderClient.connect();\n\n    const receivedPromise = new Promise\u003Cvoid>((resolve) => {\n      let count = 0;\n      reorderClient.on('message', () => {\n        count++;\n        if (count === 9) resolve();\n      });\n    });\n\n    for (let i = 0; i \u003C 9; i++) {\n      reorderClient.send(JSON.stringify({ seq: i }));\n    }\n\n    await receivedPromise;\n\n    const messages = reorderClient.getMessages();\n    const sequences = messages.map((m) => JSON.parse(m.data as string).seq);\n\n    \u002F\u002F Detect ordering violations\n    let outOfOrderCount = 0;\n    for (let i = 1; i \u003C sequences.length; i++) {\n      if (sequences[i] \u003C sequences[i - 1]) {\n        outOfOrderCount++;\n      }\n    }\n\n    expect(outOfOrderCount).toBeGreaterThan(0); \u002F\u002F Confirms reordering occurred\n\n    reorderClient.close();\n    reorderWss.close();\n  });\n\n  test('should handle duplicate message detection', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`);\n    await client.connect();\n\n    \u002F\u002F Server that sends duplicates\n    const dupWss = new WebSocketServer({ port: PORT + 2 });\n    const dupClient = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT + 2}`);\n\n    dupWss.on('connection', (ws) => {\n      ws.on('message', (data) => {\n        \u002F\u002F Send each message twice to simulate duplicates\n        ws.send(data);\n        ws.send(data);\n      });\n    });\n\n    await dupClient.connect();\n\n    const receivedPromise = new Promise\u003Cvoid>((resolve) => {\n      let count = 0;\n      dupClient.on('message', () => {\n        count++;\n        if (count === 6) resolve(); \u002F\u002F 3 messages x 2 duplicates\n      });\n    });\n\n    for (let i = 0; i \u003C 3; i++) {\n      dupClient.send(JSON.stringify({ id: `msg-${i}`, seq: i }));\n    }\n\n    await receivedPromise;\n\n    const messages = dupClient.getMessages();\n    const uniqueIds = new Set(messages.map((m) => JSON.parse(m.data as string).id));\n\n    \u002F\u002F Should detect duplicates\n    expect(messages.length).toBe(6); \u002F\u002F All messages received\n    expect(uniqueIds.size).toBe(3);  \u002F\u002F But only 3 unique\n\n    dupClient.close();\n    dupWss.close();\n  });\n});\n```\n\n## Heartbeat and Ping-Pong Testing\n\n```typescript\n\u002F\u002F tests\u002Fwebsocket\u002Fheartbeat\u002Fping-pong.spec.ts\nimport { describe, test, expect, beforeAll, afterAll, afterEach } from 'vitest';\nimport { WSTestClient } from '..\u002F..\u002Fhelpers\u002Fws-test-client';\nimport { WebSocketServer } from 'ws';\n\ndescribe('Heartbeat \u002F Ping-Pong', () => {\n  let wss: WebSocketServer;\n  let client: WSTestClient;\n  const PORT = 8768;\n\n  beforeAll(() => {\n    wss = new WebSocketServer({ port: PORT });\n    wss.on('connection', (ws) => {\n      \u002F\u002F Server responds to pings automatically (ws library default behavior)\n      ws.on('message', (data) => ws.send(data));\n    });\n  });\n\n  afterAll(() => wss.close());\n  afterEach(() => client?.close());\n\n  test('client should send periodic heartbeat pings', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`);\n    await client.connect();\n\n    let pongCount = 0;\n    client.on('pong', () => pongCount++);\n\n    \u002F\u002F Start heartbeat with 200ms interval for fast testing\n    client.startHeartbeat(200, 100);\n\n    \u002F\u002F Wait for several heartbeat cycles\n    await new Promise((resolve) => setTimeout(resolve, 1000));\n\n    \u002F\u002F Should have received multiple pong responses\n    expect(pongCount).toBeGreaterThanOrEqual(3);\n  });\n\n  test('should detect heartbeat timeout when server stops responding', async () => {\n    \u002F\u002F Create a server that does not respond to pings\n    const silentWss = new WebSocketServer({ port: PORT + 1 });\n    silentWss.on('connection', (ws) => {\n      \u002F\u002F Override the automatic pong response\n      ws.on('ping', () => {\n        \u002F\u002F Deliberately do not send pong\n      });\n    });\n\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT + 1}`, {\n      maxReconnectAttempts: 0,\n    });\n    await client.connect();\n\n    const timeoutPromise = new Promise\u003Cvoid>((resolve) => {\n      client.on('heartbeat-timeout', () => resolve());\n    });\n\n    client.startHeartbeat(200, 100);\n\n    \u002F\u002F Should detect timeout\n    await timeoutPromise;\n\n    \u002F\u002F Connection should be terminated\n    await new Promise((resolve) => setTimeout(resolve, 200));\n    expect(client.getState()).not.toBe(1); \u002F\u002F Not OPEN\n\n    silentWss.close();\n  });\n\n  test('heartbeat should reset timeout on each successful pong', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`);\n    await client.connect();\n\n    let timeoutOccurred = false;\n    client.on('heartbeat-timeout', () => {\n      timeoutOccurred = true;\n    });\n\n    \u002F\u002F Start heartbeat\n    client.startHeartbeat(100, 500);\n\n    \u002F\u002F Let it run for multiple cycles\n    await new Promise((resolve) => setTimeout(resolve, 2000));\n\n    \u002F\u002F No timeout should occur because server responds to pings\n    expect(timeoutOccurred).toBe(false);\n    expect(client.getState()).toBe(1); \u002F\u002F Still OPEN\n  });\n});\n```\n\n## Connection Drop Simulation\n\n### Simulating Network Disruptions in E2E Tests\n\n```typescript\n\u002F\u002F tests\u002Fwebsocket\u002Fresilience\u002Fnetwork-disruption.spec.ts\nimport { test, expect, Page } from '@playwright\u002Ftest';\n\ntest.describe('WebSocket Network Disruption', () => {\n  test('should reconnect after network interruption', async ({ page, context }) => {\n    await page.goto('\u002Fchat');\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Verify WebSocket is connected\n    await expect(page.locator('[data-testid=\"connection-status\"]')).toHaveText('Connected');\n\n    \u002F\u002F Send a message to confirm connectivity\n    await page.fill('[data-testid=\"message-input\"]', 'Hello before disconnect');\n    await page.click('[data-testid=\"send-button\"]');\n    await expect(page.locator('[data-testid=\"messages\"] >> text=Hello before disconnect')).toBeVisible();\n\n    \u002F\u002F Simulate network going offline\n    await context.setOffline(true);\n\n    \u002F\u002F Wait for the connection to be detected as lost\n    await expect(page.locator('[data-testid=\"connection-status\"]')).toHaveText(\n      \u002Fdisconnected|reconnecting\u002Fi,\n      { timeout: 10000 }\n    );\n\n    \u002F\u002F Restore network\n    await context.setOffline(false);\n\n    \u002F\u002F Should auto-reconnect\n    await expect(page.locator('[data-testid=\"connection-status\"]')).toHaveText(\n      'Connected',\n      { timeout: 15000 }\n    );\n\n    \u002F\u002F Verify messaging works after reconnection\n    await page.fill('[data-testid=\"message-input\"]', 'Hello after reconnect');\n    await page.click('[data-testid=\"send-button\"]');\n    await expect(\n      page.locator('[data-testid=\"messages\"] >> text=Hello after reconnect')\n    ).toBeVisible();\n  });\n\n  test('should queue messages sent during disconnection', async ({ page, context }) => {\n    await page.goto('\u002Fchat');\n    await page.waitForLoadState('networkidle');\n    await expect(page.locator('[data-testid=\"connection-status\"]')).toHaveText('Connected');\n\n    \u002F\u002F Go offline\n    await context.setOffline(true);\n    await expect(page.locator('[data-testid=\"connection-status\"]')).toHaveText(\n      \u002Fdisconnected|reconnecting\u002Fi,\n      { timeout: 10000 }\n    );\n\n    \u002F\u002F Try to send messages while disconnected\n    await page.fill('[data-testid=\"message-input\"]', 'Queued message 1');\n    await page.click('[data-testid=\"send-button\"]');\n    await page.fill('[data-testid=\"message-input\"]', 'Queued message 2');\n    await page.click('[data-testid=\"send-button\"]');\n\n    \u002F\u002F Messages should show as pending\n    await expect(page.locator('[data-testid=\"pending-indicator\"]').first()).toBeVisible();\n\n    \u002F\u002F Restore network\n    await context.setOffline(false);\n    await expect(page.locator('[data-testid=\"connection-status\"]')).toHaveText(\n      'Connected',\n      { timeout: 15000 }\n    );\n\n    \u002F\u002F Queued messages should be delivered\n    await expect(page.locator('[data-testid=\"pending-indicator\"]')).toHaveCount(0, {\n      timeout: 10000,\n    });\n    await expect(page.locator('text=Queued message 1')).toBeVisible();\n    await expect(page.locator('text=Queued message 2')).toBeVisible();\n  });\n\n  test('should handle slow network gracefully', async ({ page }) => {\n    \u002F\u002F Throttle the network to simulate a poor connection\n    const cdpSession = await page.context().newCDPSession(page);\n    await cdpSession.send('Network.emulateNetworkConditions', {\n      offline: false,\n      downloadThroughput: 5000,   \u002F\u002F 5 KB\u002Fs\n      uploadThroughput: 5000,     \u002F\u002F 5 KB\u002Fs\n      latency: 2000,              \u002F\u002F 2 seconds\n    });\n\n    await page.goto('\u002Fchat');\n\n    \u002F\u002F Connection should eventually establish even under slow conditions\n    await expect(page.locator('[data-testid=\"connection-status\"]')).toHaveText(\n      'Connected',\n      { timeout: 30000 }\n    );\n\n    \u002F\u002F Messages should still work (possibly with delay)\n    await page.fill('[data-testid=\"message-input\"]', 'Slow network message');\n    await page.click('[data-testid=\"send-button\"]');\n\n    await expect(page.locator('text=Slow network message')).toBeVisible({\n      timeout: 15000,\n    });\n\n    \u002F\u002F Reset network conditions\n    await cdpSession.send('Network.emulateNetworkConditions', {\n      offline: false,\n      downloadThroughput: -1,\n      uploadThroughput: -1,\n      latency: 0,\n    });\n  });\n});\n```\n\n## Authentication Token Refresh During WebSocket Sessions\n\n```typescript\n\u002F\u002F tests\u002Fwebsocket\u002Fconnection\u002Fauthentication.spec.ts\nimport { describe, test, expect, beforeAll, afterAll, afterEach } from 'vitest';\nimport { WSTestClient } from '..\u002F..\u002Fhelpers\u002Fws-test-client';\nimport { WebSocketServer, WebSocket } from 'ws';\nimport { IncomingMessage } from 'http';\n\ndescribe('WebSocket Authentication', () => {\n  let wss: WebSocketServer;\n  let client: WSTestClient;\n  const PORT = 8769;\n\n  beforeAll(() => {\n    wss = new WebSocketServer({\n      port: PORT,\n      verifyClient: (info: { req: IncomingMessage }) => {\n        const token = info.req.headers['authorization'];\n        \u002F\u002F Accept connections with valid tokens\n        return token === 'Bearer valid-token' || token === 'Bearer refreshed-token';\n      },\n    });\n\n    wss.on('connection', (ws) => {\n      ws.send(JSON.stringify({ type: 'auth_success' }));\n      ws.on('message', (data) => ws.send(data));\n    });\n  });\n\n  afterAll(() => wss.close());\n  afterEach(() => client?.close());\n\n  test('should connect with valid authentication token', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n      headers: { Authorization: 'Bearer valid-token' },\n    });\n\n    await client.connect();\n    expect(client.getState()).toBe(WebSocket.OPEN);\n\n    \u002F\u002F Wait for auth success message\n    await new Promise\u003Cvoid>((resolve) => {\n      client.on('message', (msg) => {\n        const parsed = JSON.parse(msg.data as string);\n        if (parsed.type === 'auth_success') resolve();\n      });\n    });\n  });\n\n  test('should reject connection with invalid token', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n      headers: { Authorization: 'Bearer invalid-token' },\n      maxReconnectAttempts: 0,\n    });\n\n    await expect(client.connect()).rejects.toThrow();\n  });\n\n  test('should reconnect with refreshed token after auth expiry', async () => {\n    let connectionCount = 0;\n\n    const authWss = new WebSocketServer({\n      port: PORT + 1,\n      verifyClient: (info: { req: IncomingMessage }) => {\n        connectionCount++;\n        if (connectionCount === 1) return true;  \u002F\u002F First connection succeeds\n        if (connectionCount === 2) return false;  \u002F\u002F Simulate token expiry\n        return true;  \u002F\u002F Third attempt with refreshed token succeeds\n      },\n    });\n\n    authWss.on('connection', (ws) => {\n      ws.on('message', (data) => ws.send(data));\n    });\n\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT + 1}`, {\n      maxReconnectAttempts: 3,\n      reconnectDelay: 100,\n    });\n\n    await client.connect();\n    expect(client.getState()).toBe(WebSocket.OPEN);\n\n    \u002F\u002F Simulate server-side token expiry by closing connection\n    authWss.clients.forEach((ws) => ws.close(4001, 'Token expired'));\n\n    \u002F\u002F Wait for reconnection attempts\n    await new Promise((resolve) => setTimeout(resolve, 2000));\n\n    \u002F\u002F Client should have attempted to reconnect\n    expect(connectionCount).toBeGreaterThanOrEqual(2);\n\n    authWss.close();\n  });\n});\n```\n\n## Backpressure Testing\n\n```typescript\n\u002F\u002F tests\u002Fwebsocket\u002Fresilience\u002Fbackpressure.spec.ts\nimport { describe, test, expect, beforeAll, afterAll, afterEach } from 'vitest';\nimport { WSTestClient } from '..\u002F..\u002Fhelpers\u002Fws-test-client';\nimport { WebSocketServer, WebSocket } from 'ws';\n\ndescribe('WebSocket Backpressure', () => {\n  let wss: WebSocketServer;\n  let client: WSTestClient;\n  const PORT = 8770;\n\n  beforeAll(() => {\n    wss = new WebSocketServer({ port: PORT });\n    wss.on('connection', (ws) => {\n      ws.on('message', (data) => {\n        \u002F\u002F Simulate slow processing\n        setTimeout(() => ws.send(data), 10);\n      });\n    });\n  });\n\n  afterAll(() => wss.close());\n  afterEach(() => client?.close());\n\n  test('should handle burst of messages without dropping', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`);\n    await client.connect();\n\n    const messageCount = 500;\n    let received = 0;\n\n    const allReceived = new Promise\u003Cvoid>((resolve) => {\n      client.on('message', () => {\n        received++;\n        if (received === messageCount) resolve();\n      });\n    });\n\n    \u002F\u002F Send burst of messages\n    for (let i = 0; i \u003C messageCount; i++) {\n      client.send(JSON.stringify({ seq: i, data: 'x'.repeat(100) }));\n    }\n\n    await allReceived;\n\n    expect(received).toBe(messageCount);\n\n    \u002F\u002F Verify no messages were dropped\n    const messages = client.getMessages();\n    const sequences = messages.map((m) => JSON.parse(m.data as string).seq);\n    const uniqueSequences = new Set(sequences);\n    expect(uniqueSequences.size).toBe(messageCount);\n  });\n\n  test('should handle large payloads', async () => {\n    client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`);\n    await client.connect();\n\n    \u002F\u002F Send increasingly large messages\n    const sizes = [1024, 10240, 102400, 1048576]; \u002F\u002F 1KB, 10KB, 100KB, 1MB\n\n    for (const size of sizes) {\n      const payload = JSON.stringify({\n        size,\n        data: 'x'.repeat(size),\n      });\n\n      const responsePromise = new Promise\u003Cvoid>((resolve) => {\n        client.once('message', () => resolve());\n      });\n\n      client.send(payload);\n      await responsePromise;\n\n      const lastMessage = client.getMessages().at(-1);\n      expect(lastMessage).toBeDefined();\n\n      const parsed = JSON.parse(lastMessage!.data as string);\n      expect(parsed.data.length).toBe(size);\n    }\n  });\n});\n```\n\n## Concurrent Connection Limits\n\n```typescript\n\u002F\u002F tests\u002Fwebsocket\u002Fconnection\u002Fconcurrent-connections.spec.ts\nimport { describe, test, expect, beforeAll, afterAll } from 'vitest';\nimport { WSTestClient } from '..\u002F..\u002Fhelpers\u002Fws-test-client';\nimport { WebSocketServer } from 'ws';\n\ndescribe('Concurrent WebSocket Connections', () => {\n  let wss: WebSocketServer;\n  const PORT = 8771;\n  const MAX_CONNECTIONS = 10;\n\n  beforeAll(() => {\n    wss = new WebSocketServer({ port: PORT });\n    let connectionCount = 0;\n\n    wss.on('connection', (ws) => {\n      connectionCount++;\n\n      if (connectionCount > MAX_CONNECTIONS) {\n        ws.close(4029, 'Too many connections');\n        return;\n      }\n\n      ws.on('message', (data) => ws.send(data));\n      ws.on('close', () => connectionCount--);\n    });\n  });\n\n  afterAll(() => wss.close());\n\n  test('should handle multiple concurrent connections', async () => {\n    const clients: WSTestClient[] = [];\n    const count = 5;\n\n    for (let i = 0; i \u003C count; i++) {\n      const client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n        maxReconnectAttempts: 0,\n      });\n      await client.connect();\n      clients.push(client);\n    }\n\n    \u002F\u002F All clients should be connected\n    for (const client of clients) {\n      expect(client.getStateName()).toBe('OPEN');\n    }\n\n    \u002F\u002F All clients should be able to send and receive\n    for (let i = 0; i \u003C clients.length; i++) {\n      const responsePromise = new Promise\u003Cvoid>((resolve) => {\n        clients[i].once('message', () => resolve());\n      });\n      clients[i].send(JSON.stringify({ client: i }));\n      await responsePromise;\n    }\n\n    \u002F\u002F Clean up\n    clients.forEach((c) => c.close());\n  });\n\n  test('should reject connections beyond the limit', async () => {\n    const clients: WSTestClient[] = [];\n\n    \u002F\u002F Fill up to the limit\n    for (let i = 0; i \u003C MAX_CONNECTIONS; i++) {\n      const client = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n        maxReconnectAttempts: 0,\n      });\n      await client.connect();\n      clients.push(client);\n    }\n\n    \u002F\u002F The next connection should be rejected\n    const extraClient = new WSTestClient(`ws:\u002F\u002Flocalhost:${PORT}`, {\n      maxReconnectAttempts: 0,\n    });\n\n    await extraClient.connect();\n\n    \u002F\u002F Should receive a close frame with the rejection code\n    const closePromise = new Promise\u003Cnumber>((resolve) => {\n      extraClient.on('close', (code) => resolve(code));\n    });\n\n    const code = await closePromise;\n    expect(code).toBe(4029);\n\n    \u002F\u002F Clean up\n    clients.forEach((c) => c.close());\n    extraClient.close();\n  });\n});\n```\n\n## Configuration\n\n### Playwright Configuration for WebSocket E2E Tests\n\n```typescript\n\u002F\u002F playwright.config.ts\nimport { defineConfig, devices } from '@playwright\u002Ftest';\n\nexport default defineConfig({\n  testDir: '.\u002Ftests\u002Fwebsocket\u002Fe2e',\n  fullyParallel: false, \u002F\u002F WebSocket tests may share server state\n  retries: 2,\n  timeout: 30000,\n  reporter: [\n    ['html', { open: 'never' }],\n    ['json', { outputFile: 'ws-test-results.json' }],\n  ],\n  use: {\n    baseURL: process.env.BASE_URL || 'http:\u002F\u002Flocalhost:3000',\n    trace: 'on-first-retry',\n    screenshot: 'only-on-failure',\n    video: 'retain-on-failure',\n  },\n  projects: [\n    {\n      name: 'ws-chrome',\n      use: { ...devices['Desktop Chrome'] },\n    },\n    {\n      name: 'ws-firefox',\n      use: { ...devices['Desktop Firefox'] },\n    },\n    {\n      name: 'ws-mobile',\n      use: { ...devices['iPhone 14'] },\n    },\n  ],\n});\n```\n\n### WebSocket Test Configuration\n\n```typescript\n\u002F\u002F config\u002Fws-test-config.ts\nexport const WS_TEST_CONFIG = {\n  \u002F\u002F Server configuration\n  serverUrl: process.env.WS_SERVER_URL || 'ws:\u002F\u002Flocalhost:8080',\n  serverPort: parseInt(process.env.WS_TEST_PORT || '8080', 10),\n\n  \u002F\u002F Connection settings\n  connectTimeout: 5000,\n  maxReconnectAttempts: 5,\n  reconnectBaseDelay: 1000,\n  reconnectMaxDelay: 30000,\n\n  \u002F\u002F Heartbeat settings\n  heartbeatInterval: 30000,\n  heartbeatTimeout: 5000,\n\n  \u002F\u002F Message settings\n  maxMessageSize: 1048576,  \u002F\u002F 1MB\n  messageTimeout: 10000,\n\n  \u002F\u002F Test data\n  burstMessageCount: 500,\n  concurrentClientCount: 10,\n  largePayloadSizes: [1024, 10240, 102400, 1048576],\n};\n```\n\n## Best Practices\n\n1. **Always implement exponential backoff with jitter for reconnection** -- A fixed reconnect interval causes all disconnected clients to reconnect simultaneously, creating a \"thundering herd\" that can overwhelm the server. Add random jitter to spread reconnection attempts.\n\n2. **Use connection state machines** -- Model the WebSocket lifecycle as a state machine with explicit states (DISCONNECTED, CONNECTING, CONNECTED, RECONNECTING) and valid transitions. This prevents impossible state combinations like sending messages while disconnected.\n\n3. **Implement message acknowledgment for critical operations** -- For messages that must not be lost (e.g., financial transactions, chat messages), implement application-level acknowledgments. Do not rely solely on TCP delivery guarantees.\n\n4. **Test with real-world disconnect scenarios** -- Lab-perfect connections hide bugs. Test with WiFi-to-cellular transitions, VPN disconnects, laptop lid close\u002Fopen, and browser tab backgrounding.\n\n5. **Add sequence numbers to messages** -- Every message should include a monotonically increasing sequence number. This enables detection of gaps, duplicates, and reordering on the receiving end.\n\n6. **Handle the \"half-open\" connection state** -- A TCP connection can appear open on one side while closed on the other. Heartbeats detect this condition. Without heartbeats, a client may believe it is connected while the server has already dropped the connection.\n\n7. **Buffer messages during reconnection** -- Messages sent while the WebSocket is reconnecting should be queued and delivered once the connection is re-established, not silently dropped.\n\n8. **Test binary message handling separately from text** -- Binary frames (ArrayBuffer, Blob) and text frames have different serialization paths. Test both frame types to ensure the application handles each correctly.\n\n9. **Implement connection pooling for multiple channels** -- Applications that need multiple logical channels should multiplex over a single WebSocket connection rather than opening separate connections per channel.\n\n10. **Set appropriate close codes** -- Use RFC 6455 close codes correctly: 1000 (normal), 1001 (going away), 1008 (policy violation), 1011 (unexpected condition). Custom codes should be in the 4000-4999 range.\n\n11. **Test WebSocket behavior across browser tabs** -- Browsers may throttle or suspend WebSocket connections in background tabs. Test that reconnection works correctly when a user returns to a backgrounded tab.\n\n12. **Monitor WebSocket connection metrics in production** -- Track connection duration, reconnection frequency, message latency, and error rates. These metrics reveal reliability issues that tests alone cannot catch.\n\n## Anti-Patterns to Avoid\n\n1. **Reconnecting immediately without backoff** -- Instant reconnection creates a retry storm that wastes bandwidth and can trigger rate limiting or server overload. Always use exponential backoff.\n\n2. **Silently dropping messages during disconnection** -- When a user sends a chat message during a brief disconnect and the message disappears, it erodes trust. Queue messages and deliver them after reconnection.\n\n3. **Using WebSocket as the only data channel** -- WebSocket connections are not guaranteed to stay open. Critical operations should have an HTTP fallback. Do not build flows that are impossible to complete without a persistent WebSocket.\n\n4. **Ignoring close frames and codes** -- Different close codes have different meanings. Code 1001 (going away) suggests the server is restarting and reconnection will likely succeed. Code 1008 (policy violation) suggests the client should not reconnect.\n\n5. **Opening a new WebSocket per request** -- WebSocket's advantage is persistent connections. Opening and closing a WebSocket for each message negates the protocol's benefits and adds significant overhead.\n\n6. **Trusting message order across reconnections** -- A new WebSocket connection is a new TCP stream. Messages in transit during reconnection may be lost or arrive on the new connection out of order. Always use sequence numbers.\n\n7. **Not testing concurrent connection limits** -- Browsers enforce per-domain WebSocket limits. Applications that open too many connections will silently fail to connect, causing features to break with no visible error.\n\n## Debugging Tips\n\n1. **Use Chrome DevTools WebSocket inspector** -- The Network tab in Chrome DevTools shows individual WebSocket frames (both sent and received). Filter by \"WS\" to see only WebSocket traffic. Click on a connection to inspect individual frames.\n\n2. **Log connection state transitions** -- Add logging for every state change: CONNECTING, OPEN, CLOSING, CLOSED, and any custom states like RECONNECTING. This trace is invaluable for debugging intermittent connection issues.\n\n3. **Check for load balancer idle timeout** -- Many load balancers (AWS ALB, nginx) close idle WebSocket connections after 60 seconds. If connections drop without heartbeat activity, the load balancer timeout is the likely culprit.\n\n4. **Verify WebSocket upgrade headers** -- Use `curl -i -N -H \"Connection: Upgrade\" -H \"Upgrade: websocket\"` to verify the server responds with a 101 Switching Protocols response. A 200 OK indicates the upgrade failed.\n\n5. **Test with `wscat` for quick manual verification** -- The `wscat` command-line tool (`npx wscat -c ws:\u002F\u002Flocalhost:8080`) provides a simple way to interactively test WebSocket endpoints without building a test client.\n\n6. **Monitor `readyState` before sending** -- Always check `ws.readyState === WebSocket.OPEN` before calling `ws.send()`. Sending on a non-OPEN socket throws an error that may not be caught by error boundaries.\n\n7. **Check for CORS issues on WebSocket upgrade** -- While the WebSocket protocol itself does not enforce CORS, some reverse proxies and CDNs may block WebSocket upgrade requests based on Origin headers. Check server logs for rejected upgrade requests.\n\n8. **Use Wireshark to inspect WebSocket frames at the protocol level** -- When high-level debugging is insufficient, Wireshark can decode WebSocket frames and show the raw binary content, opcode, masking, and frame boundaries.\n\n9. **Verify that ping\u002Fpong frames are not confused with application messages** -- WebSocket control frames (ping, pong, close) are distinct from data frames. Ensure your message handler does not process control frames as application messages.\n\n10. **Test reconnection with server-side logging** -- Log connection and disconnection events on the server with client identifiers. Compare server-side logs with client-side reconnection logs to identify mismatches where the client believes it is connected but the server does not have a matching connection.\n",{"name":5,"tags":24,"agents":33,"author":46,"domains":47,"license":15,"version":50,"languages":51,"frameworks":54,"description":7,"testingTypes":56},[25,26,27,28,29,30,31,32],"websocket","real-time","connection-testing","reconnection","message-ordering","heartbeat","socket-testing","ws",[34,35,36,37,38,39,40,41,42,43,44,45],"claude-code","cursor","github-copilot","windsurf","codex","aider","continue","cline","zed","bolt","gemini-cli","amp","Pramod",[48,49],"web","api","1.0.0",[52,53],"typescript","javascript",[55],"playwright",[57,58],"integration","e2e","main","eac438ea9216a7cb8a570cab803eb01eeafc6793","skills\u002Fqa\u002Fwebsocket-bug-finder","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m","https:\u002F\u002Fid-preview--d5bef06d-6c9e-4563-a3d4-a855b9d61610.lovable.app\u002F","Eu sou Antonio B. B. Ndombe \r\nEu sou um Pesquisador e desenvolvedor de sistema autonomia cognitivos, fundador de sistemas ODCs ( organismos digital conscientes)","2026-11-04 06:53:39",{"source":8,"skillName":5,"commands":68,"prompt":78,"zipAvailable":79},[69,72,75],{"tool":70,"command":71},"npx","npx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"WebSocket Bug Finder\"",{"tool":73,"command":74},"bunx","bunx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"WebSocket Bug Finder\"",{"tool":76,"command":77},"pnpm","pnpm dlx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"WebSocket Bug Finder\"","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fskills\u002Fqa\u002Fwebsocket-bug-finder\u002FSKILL.md",true,[],[82,90,97,104,111,118],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M7DASC6FSCJP49JZBSK0NY1Z","nemoclaw-user-reference","Describes the NemoClaw integration layer and blueprint architecture and how they orchestrate compatible agent sandboxes. Use when looking up architecture, agent integration, plugin structure, or blueprint design. Trigger keywords - nemoclaw architecture, nemoclaw agent architecture, nemoclaw plugin blueprint structure, nemoclaw vs openshell, which cli, nemoclaw cli, openshell cli, sandbox commands, nemoclaw cli commands, nemoclaw command reference, nemoclaw network policy, sandbox egress control operator approval, nemoclaw troubleshooting, nemoclaw debug sandbox issues.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-reference\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M7DAS5S79VK33XFGVAM2TFWF","nemoclaw-user-overview","Explains how OpenClaw, OpenShell, and NemoClaw form the ecosystem, NemoClaw's position in the stack, what NemoClaw adds beyond the community sandbox, and when to prefer NemoClaw versus integrating OpenShell and OpenClaw directly. Use when users ask about the relationship between OpenClaw, OpenShell, and NemoClaw, or when to use NemoClaw versus OpenShell. Trigger keywords - nemoclaw ecosystem, openclaw openshell, nemoclaw vs openshell, sandboxed openclaw, how nemoclaw works, nemoclaw sandbox lifecycle blueprint, nemoclaw overview, openclaw always-on assistants, nvidia openshell, nvidia nemotron, nemoclaw release notes, nemoclaw changelog.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-overview\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"01M7DAS0PQEMET5MNGZ1ABSZVS","nemoclaw-user-monitor-sandbox","Inspects sandbox health, traces agent behavior, and diagnoses problems. Use when monitoring a running sandbox, debugging agent issues, or checking sandbox logs. Trigger keywords - monitor nemoclaw sandbox, debug nemoclaw agent issues.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-monitor-sandbox\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":19},"01M7DARQYGF7E9A69VH6S3CGN9","nemoclaw-user-manage-sandboxes","Explains operational tasks after the quickstart: listing sandboxes, status and health checks, logs, diagnostics, port forwards, multiple sandboxes, credential reset, rebuilds, network presets, upgrades, and uninstall. Trigger keywords - manage nemoclaw sandboxes, nemoclaw status, nemoclaw list, nemoclaw dashboard port, nemoclaw rebuild, nemoclaw upgrade sandboxes, nemoclaw uninstall, sandbox mutability, sandbox runtime configuration, sandbox rebuild, nemoclaw backup, nemoclaw restore, workspace backup, openshell sandbox download upload, nemoclaw messaging channels, nemoclaw telegram, nemoclaw discord, nemoclaw slack, nemoclaw wechat, nemoclaw whatsapp, openshell channel messaging, nemoclaw workspace files, soul.md, user.md, identity.md, agents.md, sandbox persistence.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-manage-sandboxes\u002FSKILL.md",[],[],{"skillNo":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":117,"publishedAt":19},"01M7DARH8BRTG51TRCAB7YWDJ4","nemoclaw-user-manage-policy","Adds, removes, or modifies allowed endpoints in the sandbox policy. Use when customizing network policy, changing egress rules, or configuring sandbox endpoint access. Trigger keywords - customize nemoclaw network policy, sandbox egress policy configuration, nemoclaw integration policy examples, post-install policy setup, openshell approval workflow, policy preset, nemoclaw approve network requests, sandbox egress approval tui.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-manage-policy\u002FSKILL.md",[],[],{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":19},"01M7DARAT62M2VR37590VCZ5NS","nemoclaw-user-get-started","Installs NemoClaw, launches a sandbox, and runs the first agent prompt. Use when onboarding, installing, or launching a NemoClaw sandbox for the first time. Trigger keywords - nemoclaw quickstart, install nemoclaw openclaw sandbox, nemohermes quickstart, hermes agent nemoclaw, run hermes openshell sandbox, nemoclaw prerequisites, nemoclaw supported platforms, nemoclaw hardware software, nemoclaw windows wsl2 setup, nemoclaw install windows docker desktop.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-get-started\u002FSKILL.md",[],[]]