[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EWDM5FXKB9KHPB29N2EDJK":3,"skill-same:01M7EWDM5FXKB9KHPB29N2EDJK":45},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":23,"commitSha":24,"skillDirectory":25,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":29,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M7EWDM5FXKB9KHPB29N2EDJK","ams-websocket-patterns",null,"TanNhatCMS\u002Fjarvis","TanNhatCMS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F113796420?v=4","01M753MV17KG5CD3152G3WQEQY","KietNT","01M7EKEDYVYQ6PWVJJMZ911VMX",0,"MIT","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fams-websocket-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: websocket-patterns\ndescription: WebSocket patterns for web apps: robust clients, reconnection, resync, multiplexing, and scaling realtime features. Use when adding live features to web frontends.\ncategory: web-development\n---\n\n# WebSocket Patterns\n\nA frontend-focused companion to WebSocket fundamentals: the client-side patterns for reliable realtime web features — connection management, reconnection with resync, multiplexing topics, and scaling considerations from the web app's perspective.\n\n## Overview\n\nFrom the web app's side, WebSockets are deceptively simple (`new WebSocket(url)`) and deceptively fragile (networks drop, servers restart, messages get missed). This skill covers the **client patterns** that make realtime features feel solid: a robust socket wrapper, reconnection with backoff and resync, topic multiplexing over one connection, and graceful degradation — plus what to ask of the backend.\n\n## When to use\n\n- Adding live updates, chat, notifications, or presence to a web app.\n- Building a reusable realtime client layer.\n- Debugging missed messages after reconnects.\n- Deciding message protocol and topic structure with the backend team.\n\n## Core concepts\n\n- **One connection, many topics.** Multiplex: a single socket carrying subscriptions (`{ type: 'subscribe', topic: 'orders:123' }`) rather than a socket per feature. Fewer handshakes, simpler lifecycle, one reconnect path.\n- **Message envelope.** `{ type, topic?, id, payload, ts }` — types route to handlers, ids enable dedup\u002Facks, timestamps help ordering and debugging.\n- **Reconnection with backoff + jitter.** Exponential backoff (1s → 2s → 4s..., capped ~30s) with random jitter prevents thundering herds after server restarts.\n- **Resync cursors.** Track the last-seen message id per topic; on reconnect, send cursors and let the server replay what was missed — or trigger a full refresh of affected UI state.\n- **Connection state machine.** `connecting → open → (reconnecting) → open → closed`. Expose state to the UI (live indicator, \"reconnecting…\" banner, queued-action counts).\n- **Heartbeat.** Application-level ping every ~25s (in addition to protocol ping\u002Fpong) to detect half-open connections through proxies.\n- **Graceful degradation.** If the socket can't connect after N tries: fall back to polling or show stale data with a clear \"offline\" state — never a silently dead UI.\n\n## Practical workflow\n\n**1. Build the client wrapper.**\n```ts\ntype Handler = (msg: Envelope) => void;\n\nclass RealtimeClient {\n  private ws?: WebSocket;\n  private retry = 0;\n  private subs = new Map\u003Cstring, Handler[]>();\n  private cursors = new Map\u003Cstring, string>();\n  state: 'connecting' | 'open' | 'reconnecting' | 'closed' = 'connecting';\n\n  constructor(private url: string) { this.connect(); }\n\n  connect() {\n    this.state = this.retry ? 'reconnecting' : 'connecting';\n    const ws = new WebSocket(this.url);\n    ws.onopen = () => {\n      this.retry = 0; this.state = 'open';\n      \u002F\u002F re-auth + resubscribe with cursors\n      ws.send(JSON.stringify({ type: 'hello', subs: [...this.subs.keys()],\n        cursors: Object.fromEntries(this.cursors) }));\n      this.heartbeat();\n    };\n    ws.onmessage = (e) => this.route(JSON.parse(e.data));\n    ws.onclose = () => this.reconnect();\n    this.ws = ws;\n  }\n\n  private reconnect() {\n    this.state = 'reconnecting';\n    const delay = Math.min(1000 * 2 ** this.retry++, 30000) * (0.5 + Math.random());\n    setTimeout(() => this.connect(), delay);\n  }\n\n  subscribe(topic: string, fn: Handler) {\n    const list = this.subs.get(topic) ?? [];\n    list.push(fn); this.subs.set(topic, list);\n    this.send({ type: 'subscribe', topic });\n    return () => this.unsubscribe(topic, fn);\n  }\n  \u002F\u002F route(): dispatch by topic, update cursors, dedupe by id\n}\n```\n\n**2. Wire into the app.** Provide via context\u002Fhook (`useSubscription('orders:123', handler)`); components subscribe declaratively and clean up on unmount.\n\n**3. Show connection state.** A subtle status indicator (live \u002F reconnecting \u002F offline); disable or queue mutating actions while offline (\"will send when reconnected\").\n\n**4. Coordinate with the backend.** Agree on: envelope format, `hello` resync semantics, heartbeat interval, auth (cookie session or first-message token — not long-lived tokens in the URL), per-topic authorization.\n\n**5. Test the failure modes.** Kill the server mid-session; throttle to offline in DevTools; sleep\u002Fwake the laptop. Verify: reconnects, resubscribes, resyncs, no duplicates rendered, UI state honest throughout.\n\n## Common pitfalls\n\n- **Naked `new WebSocket`.** No reconnection, no resync, no state — the #1 realtime bug. Always wrap.\n- **Fixed retry delay.** 10k clients retrying every 5s after a deploy = self-inflicted DDoS. Backoff + jitter.\n- **No resync.** Reconnected clients silently miss messages. Cursors + replay, or explicit refresh.\n- **Duplicate rendering.** Replayed messages rendered twice. Dedupe by message id client-side.\n- **Socket per component.** N components × N sockets = N handshakes, N reconnect paths. One multiplexed connection.\n- **Leaking subscriptions.** Components unmounting without unsubscribing = handlers firing on dead components. Return cleanup functions; enforce in review.\n- **State lies.** UI showing \"live\" while the socket has been dead for minutes. Drive indicators from the real connection state machine.\n- **Auth token in URL.** `wss:\u002F\u002F...?token=secret` leaks into logs\u002Fproxies. Cookie sessions or post-connect auth frames.\n- **No offline queue.** User actions during disconnect vanish. Queue mutations locally, flush on reconnect, show pending state.\n- **Ignoring the fallback.** Some networks block websockets entirely. Have a polling\u002FSSE fallback path for critical features, or at minimum a clear degraded state.\n","# WebSocket Patterns\n\nA frontend-focused companion to WebSocket fundamentals: the client-side patterns for reliable realtime web features — connection management, reconnection with resync, multiplexing topics, and scaling considerations from the web app's perspective.\n\n## Overview\n\nFrom the web app's side, WebSockets are deceptively simple (`new WebSocket(url)`) and deceptively fragile (networks drop, servers restart, messages get missed). This skill covers the **client patterns** that make realtime features feel solid: a robust socket wrapper, reconnection with backoff and resync, topic multiplexing over one connection, and graceful degradation — plus what to ask of the backend.\n\n## When to use\n\n- Adding live updates, chat, notifications, or presence to a web app.\n- Building a reusable realtime client layer.\n- Debugging missed messages after reconnects.\n- Deciding message protocol and topic structure with the backend team.\n\n## Core concepts\n\n- **One connection, many topics.** Multiplex: a single socket carrying subscriptions (`{ type: 'subscribe', topic: 'orders:123' }`) rather than a socket per feature. Fewer handshakes, simpler lifecycle, one reconnect path.\n- **Message envelope.** `{ type, topic?, id, payload, ts }` — types route to handlers, ids enable dedup\u002Facks, timestamps help ordering and debugging.\n- **Reconnection with backoff + jitter.** Exponential backoff (1s → 2s → 4s..., capped ~30s) with random jitter prevents thundering herds after server restarts.\n- **Resync cursors.** Track the last-seen message id per topic; on reconnect, send cursors and let the server replay what was missed — or trigger a full refresh of affected UI state.\n- **Connection state machine.** `connecting → open → (reconnecting) → open → closed`. Expose state to the UI (live indicator, \"reconnecting…\" banner, queued-action counts).\n- **Heartbeat.** Application-level ping every ~25s (in addition to protocol ping\u002Fpong) to detect half-open connections through proxies.\n- **Graceful degradation.** If the socket can't connect after N tries: fall back to polling or show stale data with a clear \"offline\" state — never a silently dead UI.\n\n## Practical workflow\n\n**1. Build the client wrapper.**\n```ts\ntype Handler = (msg: Envelope) => void;\n\nclass RealtimeClient {\n  private ws?: WebSocket;\n  private retry = 0;\n  private subs = new Map\u003Cstring, Handler[]>();\n  private cursors = new Map\u003Cstring, string>();\n  state: 'connecting' | 'open' | 'reconnecting' | 'closed' = 'connecting';\n\n  constructor(private url: string) { this.connect(); }\n\n  connect() {\n    this.state = this.retry ? 'reconnecting' : 'connecting';\n    const ws = new WebSocket(this.url);\n    ws.onopen = () => {\n      this.retry = 0; this.state = 'open';\n      \u002F\u002F re-auth + resubscribe with cursors\n      ws.send(JSON.stringify({ type: 'hello', subs: [...this.subs.keys()],\n        cursors: Object.fromEntries(this.cursors) }));\n      this.heartbeat();\n    };\n    ws.onmessage = (e) => this.route(JSON.parse(e.data));\n    ws.onclose = () => this.reconnect();\n    this.ws = ws;\n  }\n\n  private reconnect() {\n    this.state = 'reconnecting';\n    const delay = Math.min(1000 * 2 ** this.retry++, 30000) * (0.5 + Math.random());\n    setTimeout(() => this.connect(), delay);\n  }\n\n  subscribe(topic: string, fn: Handler) {\n    const list = this.subs.get(topic) ?? [];\n    list.push(fn); this.subs.set(topic, list);\n    this.send({ type: 'subscribe', topic });\n    return () => this.unsubscribe(topic, fn);\n  }\n  \u002F\u002F route(): dispatch by topic, update cursors, dedupe by id\n}\n```\n\n**2. Wire into the app.** Provide via context\u002Fhook (`useSubscription('orders:123', handler)`); components subscribe declaratively and clean up on unmount.\n\n**3. Show connection state.** A subtle status indicator (live \u002F reconnecting \u002F offline); disable or queue mutating actions while offline (\"will send when reconnected\").\n\n**4. Coordinate with the backend.** Agree on: envelope format, `hello` resync semantics, heartbeat interval, auth (cookie session or first-message token — not long-lived tokens in the URL), per-topic authorization.\n\n**5. Test the failure modes.** Kill the server mid-session; throttle to offline in DevTools; sleep\u002Fwake the laptop. Verify: reconnects, resubscribes, resyncs, no duplicates rendered, UI state honest throughout.\n\n## Common pitfalls\n\n- **Naked `new WebSocket`.** No reconnection, no resync, no state — the #1 realtime bug. Always wrap.\n- **Fixed retry delay.** 10k clients retrying every 5s after a deploy = self-inflicted DDoS. Backoff + jitter.\n- **No resync.** Reconnected clients silently miss messages. Cursors + replay, or explicit refresh.\n- **Duplicate rendering.** Replayed messages rendered twice. Dedupe by message id client-side.\n- **Socket per component.** N components × N sockets = N handshakes, N reconnect paths. One multiplexed connection.\n- **Leaking subscriptions.** Components unmounting without unsubscribing = handlers firing on dead components. Return cleanup functions; enforce in review.\n- **State lies.** UI showing \"live\" while the socket has been dead for minutes. Drive indicators from the real connection state machine.\n- **Auth token in URL.** `wss:\u002F\u002F...?token=secret` leaks into logs\u002Fproxies. Cookie sessions or post-connect auth frames.\n- **No offline queue.** User actions during disconnect vanish. Queue mutations locally, flush on reconnect, show pending state.\n- **Ignoring the fallback.** Some networks block websockets entirely. Have a polling\u002FSSE fallback path for critical features, or at minimum a clear degraded state.\n",{},"main","af388a77c2fe5e0b4fd879cca4300a0ffa9a6579","skills\u002Fams-websocket-patterns",1,"https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis","https:\u002F\u002Fgithub.com\u002FTanNhatCMS","https:\u002F\u002Fmrkiet.name.vn","2026-11-07 14:23:08",{"source":7,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add TanNhatCMS\u002Fjarvis --skill ams-websocket-patterns",{"tool":37,"command":38},"bunx","bunx skills add TanNhatCMS\u002Fjarvis --skill ams-websocket-patterns",{"tool":40,"command":41},"pnpm","pnpm dlx skills add TanNhatCMS\u002Fjarvis --skill ams-websocket-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fams-websocket-patterns\u002FSKILL.md",true,[],[46,53,61,68,75,82],{"skillNo":47,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":50,"categories":51,"keywords":52,"publishedAt":18},"01M7EWYJR0J8DARY7E59Z6Y9MV","web-scrape","Turn web pages into LLM-ready markdown via the Firecrawl API (renders JS, anti-bot handling). Use when browser_open\u002Ffetch fails on JS-heavy pages, or when you need clean markdown\u002Fstructured extraction from a site. Requires FIRECRAWL_API_KEY.","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fweb-scrape\u002FSKILL.md",[],[],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":57,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":18},"01M7EWYBN5P6F2AJG3FR24T9BP","design-taste-frontend","tasteskill v2, the anti-slop frontend skill. Art direction for websites, distilled from a study of 247 curated gallery sites (One Page Love, Awwwards Sites of the Day). Deals researched directions (idea, composition, type, palette, photographs, section blueprints) from a library, enforces a strict no-slop house style with a real-browser inspector, and runs a look-and-fix loop on screenshots. Use this whenever you build, design, redesign, restyle, polish or review a landing page, marketing site, portfolio, product page, one-pager, hero or any public-facing web page, in any stack (HTML\u002FCSS, React, Next.js, Vue, Svelte, Astro, Tailwind) — also when the user says a page looks generic, templated, \"AI-made\", sloppy, or asks to make it look designed, premium, award-level or less like every other site. Not for dashboards or app screens.","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Ftaste-design\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Ftaste-design\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7EWY8FQFNQ2GB7NZZWGSSDX","test-driven-development","Use when implementing any feature or bugfix, before writing implementation code","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fsuperpowers-tdd\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":18},"01M7EWY5SHBFRH1HDHVWM9K7TV","systematic-debugging","Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fsuperpowers-debugging\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":18},"01M7EWY3NM0Z0JAKS7HDZ24K66","requesting-code-review","Use when completing tasks, implementing major features, or before merging to verify work meets requirements","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fsuperpowers-code-review\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":18},"01M7EWY0WRMWX4M9ZFY0WKC593","brainstorming","You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fsuperpowers-brainstorming\u002FSKILL.md",[],[]]