Add rpc

From mits-pl/wove · View interactive version

Add rpc is an AI agent skill from the GitHub repository mits-pl/wove. Guide for adding new RPC calls to Wave Terminal. Use when implementing new RPC commands, adding server-client communication methods, or extending the RPC interface with new functionality.

How to use this skill

Skill file

Adding RPC Calls Guide

Overview

Wave Terminal uses a WebSocket-based RPC (Remote Procedure Call) system for communication between different components. The RPC system allows the frontend, backend, electron main process, remote servers, and terminal blocks to communicate with each other through well-defined commands.

This guide covers how to add a new RPC command to the system.

Key Files

RPC Command Structure

RPC commands in Wave Terminal follow these conventions:

Adding a New RPC Call

Step 1: Define the Command in the Interface

Add your command to the WshRpcInterface in pkg/wshrpc/wshrpctypes.go:

type WshRpcInterface interface {
    // ... existing commands ...
    
    // Add your new command
    YourNewCommand(ctx context.Context, data CommandYourNewData) (*YourNewResponse, error)
}

Method Signature Rules:

Step 2: Define Request and Response Types

If your command needs structured input or output, define types in the same file:

type CommandYourNewData struct {
    FieldOne   string `json:"fieldone"`
    FieldTwo   int    `json:"fieldtwo"`
    SomeId     string `json:"someid"`
}

type YourNewResponse struct {
    ResultField string `json:"resultfield"`
    Success     bool   `json:"success"`
}

Type Naming Conventions:

Step 3: Generate Bindings

After modifying pkg/wshrpc/wshrpctypes.go, run code generation to create TypeScript bindings and Go helper code:

task generate

This command will:

Note: If generation fails, check that your method signature follows all the rules above.

Step 4: Implement the Command

Choose where to implement your command based on what it needs to do:

A. Main Server Implementation (Most Common)

Implement in pkg/wshrpc/wshserver/wshserver.go:

func (ws *WshServer) YourNewCommand(ctx context.Context, data wshrpc.CommandYourNewData) (*wshrpc.YourNewResponse, error) {
    // Validate input
    if data.SomeId == "" {
        return nil, fmt.Errorf("someid is required")
    }
    
    // Implement your logic
    result := doSomething(data)
    
    // Return response
    return &wshrpc.YourNewResponse{
        ResultField: result,
        Success:     true,
    }, nil
}

Use main server when:

B. Electron Implementation

Implement in emain/emain-wsh.ts:

async handle_yournew(rh: RpcResponseHelper, data: CommandYourNewData): Promise<YourNewResponse> {
    // Electron-specific logic
    const result = await electronAPI.doSomething(data);
    
    return {
        resultfield: result,
        success: true,
    };
}

Use Electron when:

C. Frontend Tab Implementation

Implement in frontend/app/store/tabrpcclient.ts:

async handle_yournew(rh: RpcResponseHelper, data: CommandYourNewData): Promise<YourNewResponse> {
    // Access frontend state/models
    const layoutModel = getLayoutModelForStaticTab();
    
    // Implement tab-specific logic
    const result = layoutModel.doSomething(data);
    
    return {
        resultfield: result,
        success: true,
    };
}

Use tab client when:

D. Remote Server Implementation

Implement in pkg/wshrpc/wshremote/wshremote.go:

func (impl *ServerImpl) RemoteYourNewCommand(ctx context.Context, data wshrpc.CommandRemoteYourNewData) (*wshrpc.YourNewResponse, error) {
    // Remote filesystem or process operations
    result, err := performRemoteOperation(data)
    if err != nil {
        return nil, fmt.Errorf("remote operation failed: %w", err)
    }
    
    return &wshrpc.YourNewResponse{
        ResultField: result,
        Success:     true,
    }, nil
}

Use remote server when:

E. Terminal Block Implementation

Implement in frontend/app/view/term/term-wsh.tsx:

async handle_yournew(rh: RpcResponseHelper, data: CommandYourNewData): Promise<YourNewResponse> {
    // Access terminal-specific data
    const termWrap = this.model.termRef.current;
    
    // Implement terminal logic
    const result = termWrap.doSomething(data);
    
    return {
        resultfield: result,
        success: true,
    };
}

Use terminal client when:

Complete Example: Adding GetWaveInfo Command

1. Define Interface

In pkg/wshrpc/wshrpctypes.go:

type WshRpcInterface interface {
    // ... other commands ...
    WaveInfoCommand(ctx context.Context) (*WaveInfoData, error)
}

type WaveInfoData struct {
    Version      string            `json:"version"`
    BuildTime    string            `json:"buildtime"`
    ConfigPath   string            `json:"configpath"`
    DataPath     string            `json:"datapath"`
}

2. Generate Bindings

task generate

3. Implement in Main Server

In pkg/wshrpc/wshserver/wshserver.go:

func (ws *WshServer) WaveInfoCommand(ctx context.Context) (*wshrpc.WaveInfoData, error) {
    return &wshrpc.WaveInfoData{
        Version:    wavebase.WaveVersion,
        BuildTime:  wavebase.BuildTime,
        ConfigPath: wavebase.GetConfigDir(),
        DataPath:   wavebase.GetWaveDataDir(),
    }, nil
}

4. Call from Frontend

import { RpcApi } from "@/app/store/wshclientapi";

// Call the RPC
const info = await RpcApi.WaveInfoCommand(TabRpcClient);
console.log("Wave Version:", info.version);

Streaming Commands

For commands that return data progressively, use channels:

Define Streaming Interface

type WshRpcInterface interface {
    StreamYourDataCommand(ctx context.Context, request YourDataRequest) chan RespOrErrorUnion[YourDataType]
}

Implement Streaming Command

func (ws *WshServer) StreamYourDataCommand(ctx context.Context, request wshrpc.YourDataRequest) chan wshrpc.RespOrErrorUnion[wshrpc.YourDataType] {
    rtn := make(chan wshrpc.RespOrErrorUnion[wshrpc.YourDataType])
    
    go func() {
        defer close(rtn)
        defer func() {
            panichandler.PanicHandler("StreamYourDataCommand", recover())
        }()
        
        // Stream data
        for i := 0; i < 10; i++ {
            select {
            case <-ctx.Done():
                return
            default:
                rtn <- wshrpc.RespOrErrorUnion[wshrpc.YourDataType]{
                    Response: wshrpc.YourDataType{
                        Value: i,
                    },
                }
                time.Sleep(100 * time.Millisecond)
            }
        }
    }()
    
    return rtn
}

Best Practices

  1. Validation First: Always validate input parameters at the start of your implementation
  1. Descriptive Names: Use clear, action-oriented command names (e.g., GetFullConfigCommand, not ConfigCommand)
  1. Error Handling: Return descriptive errors with context:

```go

return nil, fmt.Errorf("error creating block: %w", err)

```

  1. Context Awareness: Respect context cancellation for long-running operations:

```go

select {

case <-ctx.Done():

return ctx.Err()

default:

// continue

}

```

  1. Consistent Types: Follow existing naming patterns for request/response types
  1. JSON Tags: Always use lowercase JSON tags matching frontend conventions
  1. Documentation: Add comments explaining complex commands or special behaviors
  1. Type Safety: Leverage TypeScript generation - your types will be checked on both ends
  1. Panic Recovery: Use panichandler.PanicHandler in goroutines to prevent crashes
  1. Route Awareness: For multi-route scenarios, use wshutil.GetRpcSourceFromContext(ctx) to identify callers

Common Command Patterns

Simple Query

func (ws *WshServer) GetSomethingCommand(ctx context.Context, id string) (*Something, error) {
    obj, err := wstore.DBGet[*Something](ctx, id)
    if err != nil {
        return nil, fmt.Errorf("error getting something: %w", err)
    }
    return obj, nil
}

Mutation with Updates

func (ws *WshServer) UpdateSomethingCommand(ctx context.Context, data wshrpc.CommandUpdateData) error {
    ctx = waveobj.ContextWithUpdates(ctx)
    
    // Make changes
    err := wstore.UpdateObject(ctx, data.ORef, data.Updates)
    if err != nil {
        return fmt.Errorf("error updating: %w", err)
    }
    
    // Broadcast updates
    updates := waveobj.ContextGetUpdatesRtn(ctx)
    wps.Broker.SendUpdateEvents(updates)
    
    return nil
}

Command with Side Effects

func (ws *WshServer) DoActionCommand(ctx context.Context, data wshrpc.CommandActionData) error {
    // Perform action
    result, err := performAction(data)
    if err != nil {
        return err
    }
    
    // Publish event about the action
    go func() {
        wps.Broker.Publish(wps.WaveEvent{
            Event: wps.Event_ActionComplete,
            Data:  result,
        })
    }()
    
    return nil
}

Troubleshooting

Command Not Found

Type Mismatch Errors

Command Times Out

Routing Issues

Quick Reference

When adding a new RPC command:

Related Documentation

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.