AGENT SKILL

websockets

Real-time communication over WebSockets with a NestJS gateway. Use when the app needs live updates, chat, notifications, presence, collaborative editing, multiplayer state, or any server-pushed data — anything where polling would be too slow or wasteful.

License 许可
AGPL-3.0
最近更新
2026-11-05
Stars
★ 43
Forks
9

01 前言 Front Matter

name
websockets
description
Real-time communication over WebSockets with a NestJS gateway. Use when the app needs live updates, chat, notifications, presence, collaborative editing, multiplayer state, or any server-pushed data — anything where polling would be too slow or wasteful.

03 SKILL.md 正文

WebSockets

The platform proxies WebSocket upgrades end-to-end and keeps the app running while connections are open. Everything is preconfigured: main.ts registers the WsAdapter, and the Vite proxy forwards upgrades for paths under /api.

Two rules the setup depends on:

  • The gateway path must start with /api (e.g. /api/ws). Gateways bypass the NestJS global prefix, so set it explicitly — any other prefix never reaches the backend.
  • Connect from the frontend on the same origin — never hardcode a host or port.

Server — gateway

A gateway is a provider like any service. Messages are JSON frames of the shape { "event": "...", "data": ... }; @SubscribeMessage("event") routes on the event field, and a returned { event, data } object is sent back to the sender.

import {
  OnGatewayConnection,
  OnGatewayDisconnect,
  SubscribeMessage,
  MessageBody,
  WebSocketGateway,
} from "@nestjs/websockets"
import { WebSocket } from "ws"

interface ChatMessage {
  author: string
  text: string
  sentAt: string
}

@WebSocketGateway({ path: "/api/ws" })
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
  private readonly clients = new Set<WebSocket>()
  private readonly history: ChatMessage[] = []

  handleConnection(client: WebSocket) {
    this.clients.add(client)
    client.send(JSON.stringify({ event: "history", data: this.history }))
  }

  handleDisconnect(client: WebSocket) {
    this.clients.delete(client)
  }

  @SubscribeMessage("message")
  onMessage(@MessageBody() body: { author: string; text: string }) {
    const message: ChatMessage = { ...body, sentAt: new Date().toISOString() }
    this.history.push(message)
    this.broadcast("message", message)
  }

  private broadcast(event: string, data: unknown) {
    const frame = JSON.stringify({ event, data })
    for (const client of this.clients) {
      if (client.readyState === WebSocket.OPEN) client.send(frame)
    }
  }
}

Register it as a provider and add the module to app.module.ts, same as any service:

@Module({
  providers: [ChatGateway],
})
export class ChatModule {}

The app runs as a single process, so in-memory state (connected clients, recent messages, presence) is correct and simple — no external broker needed. Memory does not survive an app restart; persist anything that must outlive one to SQLite and replay it on connection.

To push server-initiated events (from a schedule, another service, an LLM stream), inject the gateway and call its broadcast method.

Frontend — hook with reconnect

import { useEffect, useRef, useState } from "react"

type Frame = { event: string; data: unknown }

export function useWebSocket(onFrame: (frame: Frame) => void) {
  const [connected, setConnected] = useState(false)
  const socketRef = useRef<WebSocket | null>(null)
  const onFrameRef = useRef(onFrame)
  onFrameRef.current = onFrame

  useEffect(() => {
    let socket: WebSocket
    let retryTimer: ReturnType<typeof setTimeout>
    let disposed = false

    function connect() {
      const protocol = location.protocol === "https:" ? "wss" : "ws"
      socket = new WebSocket(`${protocol}://${location.host}/api/ws`)
      socketRef.current = socket
      socket.onopen = () => setConnected(true)
      socket.onmessage = (e) => onFrameRef.current(JSON.parse(e.data))
      socket.onclose = () => {
        setConnected(false)
        if (!disposed) retryTimer = setTimeout(connect, 2000)
      }
    }

    connect()
    return () => {
      disposed = true
      clearTimeout(retryTimer)
      socket.close()
    }
  }, [])

  function send(event: string, data: unknown) {
    if (socketRef.current?.readyState === WebSocket.OPEN) {
      socketRef.current.send(JSON.stringify({ event, data }))
    }
  }

  return { connected, send }
}

Always reconnect on close — the connection drops on backend restarts (every backend file save in dev) and network blips. Re-sync state from the server after each reconnect (like the history frame above) rather than assuming continuity.

When NOT to use WebSockets

  • One-way streaming of a single response (e.g. LLM output) — plain HTTP streaming is simpler.
  • Data that changes rarely — fetch on demand or poll with react-query's refetchInterval.

04 同仓库更多 Skills

SimaDevelopment
SimaDevelopment/opsiforce

figma-use

**MANDATORY prerequisite** — you MUST invoke this skill BEFORE every `use_figma` tool call. NEVER call `use_figma` directly without loading this skill first. Skipping it causes common, hard-to-debug failures. Trigger whenever the user wants to perform a write action or a unique read action that requires JavaScript execution in the Figma file context — e.g. create/edit/delete nodes, set up variables or tokens, build components and variants, modify auto-layout or fills, bind variables to properties, or inspect file structure programmatically.

★ 43
SimaDevelopment
SimaDevelopment/opsiforce

figma-use-slides

This skill helps agents use Figma's use_figma MCP tool in the Slides context. Can be used alongside figma-use which has foundational context for using the use_figma tool.

★ 43
SimaDevelopment
SimaDevelopment/opsiforce

figma-use-motion

Motion / animation context for the `use_figma` MCP tool — animating Figma nodes via manual keyframes, animation styles, easing, and timeline duration. Load alongside figma-use whenever a task involves adding, editing, or inspecting animation on a node.

★ 43
SimaDevelopment
SimaDevelopment/opsiforce

figma-use-figjam

This skill helps agents use Figma's use_figma MCP tool in the FigJam context. Can be used alongside figma-use which has foundational context for using the use_figma tool.

★ 43
SimaDevelopment
SimaDevelopment/opsiforce

figma-swiftui

SwiftUI ↔ Figma translation. Use whenever the user mentions Swift, SwiftUI, iOS, iPhone, or iPad — in EITHER direction — translating a Figma design into SwiftUI (design → code), or pushing SwiftUI views / screens / tokens back into a Figma file (code → design). Triggers on phrases like 'implement this Figma design in SwiftUI', 'build this screen in Swift', 'push this SwiftUI view to Figma', 'mirror my Swift code in a Figma file', or whenever a Figma URL appears alongside `.swift` files / an `.xcodeproj`. Routes to a direction-specific reference doc; loads alongside `figma-use` for the code → design path.

★ 43
SimaDevelopment
SimaDevelopment/opsiforce

figma-shaders

**MANDATORY prerequisite** — load this skill before calling `create_shader` or `update_shader`. Use when the user asks to create, author, change, fix, or iterate on a shader effect, shader fill, custom effect, custom fill, or procedural shader in Figma.

★ 43