Skip to content
1k-adding-socket-events logo

Adding WebSocket Event Subscriptions

1k-adding-socket-events

Adds new WebSocket event subscriptions to OneKey. Use when implementing new socket events, handling server push messages, or adding real-time data subscriptions. Socket, WebSocket, event, subscription, push, real-time.

SKILL.md

Full skill instructions

Adding WebSocket Event Subscriptions

This skill documents how to add new WebSocket event subscriptions in the OneKey app.

Overview

WebSocket events enable real-time server-to-client communication. The pattern involves:

  1. Define the event name in EAppSocketEventNames enum
  2. Define the payload type interface
  3. Add the event handler in PushProviderWebSocket

Key Files

PurposeLocation
Event names & payload typespackages/​shared/​types/​socket.ts
WebSocket event handlerspackages/​kit-bg/​src/​services/​ServiceNotification/​PushProvider/​PushProviderWebSocket.ts

Step-by-Step Guide

Step 1: Define Event Name

Add the new event name to EAppSocketEventNames in packages/​shared/​types/​socket.ts:

export enum EAppSocketEventNames {
  notification = 'notification',
  ping = 'ping',
  pong = 'pong',
  ack = 'ack',
  market = 'market',
  primeConfigChanged = 'CONFIG_CHANGE',
  // ... existing events
  myNewEvent = 'MY_NEW_EVENT',  // Add your new event
}

Convention: Use camelCase for the enum key, SCREAMING_SNAKE_CASE for the string value.

Step 2: Define Payload Type

Add the payload interface in packages/​shared/​types/​socket.ts:

export interface IMyNewEventPayload {
  msgId: string;  // Required for acknowledgment
  // Add other fields as needed
  someData?: string;
  someNumber?: number;
}

Important: Always include msgId: string for message acknowledgment.

Step 3: Add Event Handler

In packages/​kit-bg/​src/​services/​ServiceNotification/​PushProvider/​PushProviderWebSocket.ts:

  1. Import the new payload type:
import type {
  // ... existing imports
  IMyNewEventPayload,
} from '@onekeyhq/​shared/​types/​socket';
  1. Add the event handler in initWebSocket() method:
this.socket.on(EAppSocketEventNames.myNewEvent, (payload: IMyNewEventPayload) => {
  // 1. Acknowledge receipt (required for most events)
  void this.backgroundApi.serviceNotification.ackNotificationMessage({
    msgId: payload.msgId,
    action: ENotificationPushMessageAckAction.arrived,
  });

  // 2. Handle the event (call appropriate service method)
  void this.backgroundApi.someService.handleMyNewEvent(payload);
});

Complete Example: userInfoUpdated Event

Here's a real example from the codebase:

1. Event Name (socket.ts)

export enum EAppSocketEventNames {
  // ... other events
  userInfoUpdated = 'USER_INFO_UPDATED',
}

2. Payload Type (socket.ts)

export interface IUserInfoUpdatedPayload {
  msgId: string;
}

3. Event Handler (PushProviderWebSocket.ts)

this.socket.on(EAppSocketEventNames.userInfoUpdated, (payload: IUserInfoUpdatedPayload) => {
  void this.backgroundApi.serviceNotification.ackNotificationMessage({
    msgId: payload.msgId,
    action: ENotificationPushMessageAckAction.arrived,
  });
  void this.backgroundApi.servicePrime.apiFetchPrimeUserInfo();
});

Event Handler Patterns

Simple Acknowledgment + Action

this.socket.on(EAppSocketEventNames.myEvent, (payload: IMyPayload) => {
  void this.backgroundApi.serviceNotification.ackNotificationMessage({
    msgId: payload.msgId,
    action: ENotificationPushMessageAckAction.arrived,
  });
  void this.backgroundApi.someService.doSomething();
});

With Logging

this.socket.on(EAppSocketEventNames.myEvent, (payload: IMyPayload) => {
  defaultLogger.notification.websocket.consoleLog(
    'WebSocket received myEvent:',
    payload,
  );
  void this.backgroundApi.serviceNotification.ackNotificationMessage({
    msgId: payload.msgId,
    action: ENotificationPushMessageAckAction.arrived,
  });
  void this.backgroundApi.someService.doSomething(payload);
});

With Validation

this.socket.on(EAppSocketEventNames.myEvent, async (payload: IMyPayload) => {
  if (!payload?.requiredField) {
    console.error('myEvent ERROR: requiredField is missing', payload);
    return;
  }
  void this.backgroundApi.serviceNotification.ackNotificationMessage({
    msgId: payload.msgId,
    action: ENotificationPushMessageAckAction.arrived,
  });
  await this.backgroundApi.someService.doSomething(payload);
});

With EventBus Emission

this.socket.on(EAppSocketEventNames.myEvent, (payload: IMyPayload) => {
  void this.backgroundApi.serviceNotification.ackNotificationMessage({
    msgId: payload.msgId,
    action: ENotificationPushMessageAckAction.arrived,
  });
  appEventBus.emit(EAppEventBusNames.MyEventReceived, payload);
});

Important: Message Acknowledgment

You MUST acknowledge messages via serviceNotification.ackNotificationMessage. If you don't acknowledge the msgId, the server will assume the message was not delivered and will retry sending it repeatedly.

void this.backgroundApi.serviceNotification.ackNotificationMessage({
  msgId: payload.msgId,
  action: ENotificationPushMessageAckAction.arrived,
});

This should be called as early as possible in your event handler to prevent duplicate message delivery.

Acknowledgment Actions

Available actions in ENotificationPushMessageAckAction:

  • arrived - Message was received (use this for most cases)
  • clicked - User clicked the notification

Checklist

  • Event name added to EAppSocketEventNames enum
  • Payload interface defined with msgId: string
  • Payload type imported in PushProviderWebSocket.ts
  • Event handler added in initWebSocket() method
  • Message acknowledged via ackNotificationMessage (required to prevent server retries)
  • Appropriate service method called to handle the event
  • Logging added if needed for debugging

More skills from diegosouzapw

accessibility logo
diegosouzapw/awesome-omni-skill

accessibility

Accessibility guidelines for VS Code features — covers accessibility help dialogs, accessible views, verbosity settings, accessibility signals, ARIA alerts/status announcements, keyboard navigation, and ARIA labels/roles. Applies to both new interactive UI surfaces and updates to existing feature...

62 1
View
mermaid-diagrams logo
diegosouzapw/awesome-omni-skill

mermaid-diagrams

Mermaid diagram creation for flowcharts, sequences, ERDs, and more. Generate diagrams from text in markdown files. Use for documentation, architecture diagrams, and visual representations. Triggers on mermaid, flowchart, sequence diagram, ERD, entity relationship, gantt chart, pie chart, class di...

62 1
View
tauri2-react-rust logo
diegosouzapw/awesome-omni-skill

tauri2-react-rust

Guides development of cross-platform desktop apps with Tauri 2, TypeScript, React, and Rust. Use when building Tauri apps, implementing IPC, designing Rust backend or TypeScript/React frontend, when researching or cloning a website (open site, snapshot elements), when verifying local dev or built...

62 1
View
fp-ts-errors logo
diegosouzapw/awesome-omni-skill

fp-ts-errors

Handle errors as values using fp-ts Either and TaskEither for cleaner, more predictable TypeScript code. Use when implementing error handling patterns with fp-ts.

62 0
View
ring:pre-dev-research logo
diegosouzapw/awesome-omni-skill

ring:pre-dev-research

Gate 0 research phase for pre-dev workflow. Dispatches 3 parallel research agents to gather codebase patterns, external best practices, and framework documentation BEFORE creating PRD/TRD. Outputs research.md with file:line references.

62 0
View
create-assistant logo
diegosouzapw/awesome-omni-skill

create-assistant

Create and configure Vapi voice AI assistants with models, voices, transcribers, tools, hooks, and advanced settings. Use when building voice agents, phone bots, customer support assistants, or any conversational AI that handles phone or web calls.

62 0
View
codex-headless logo
diegosouzapw/awesome-omni-skill

codex-headless

Delegiere Aufgaben an OpenAI Codex CLI im Headless-Mode. Nutzt ChatGPT Subscription (KEIN API Key). Nur Workspace-Zugriff, KEIN System-Zugriff. Auto-Accept mit --full-auto. Web-Recherche mit --search.

62 0
View
social-media-scheduler logo
diegosouzapw/awesome-omni-skill

social-media-scheduler

Generate a full week of social media content for any topic. Outputs platform-optimized posts for Twitter/X, LinkedIn, and Instagram with hashtags and posting times.

62 0
View
Data Privacy Compliance logo
diegosouzapw/awesome-omni-skill

Data Privacy Compliance

Data privacy and regulatory compliance specialist for GDPR, CCPA, HIPAA, and international data protection laws. Use when implementing privacy controls, conducting data protection impact assessments, ensuring regulatory compliance, or managing data subject rights. Expert in consent management, da...

62 0
View
triple-review logo
diegosouzapw/awesome-omni-skill

triple-review

Reviews a task using the TRIPLE protocol, as the review agent.

62 0
View
Tech Stack & Architecture Decision logo
diegosouzapw/awesome-omni-skill

Tech Stack & Architecture Decision

Define and document the technology stack and architecture decisions for a project. Use when the user needs to choose a tech stack, make architecture decisions, define infrastructure choices, or document technology selections. Triggers on requests like "define the tech stack", "choose technologies...

62 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View