kolo docsbeta

Step 2: Build a desktop chat

A step-by-step tutorial. Fill in the Kolo part of a ready-made desktop window: two instances find each other through a bootstrap node and chat directly, with no server in between.

On this page

In the previous step you built a chat in your terminal. Now you build a desktop chat.

In about fifteen minutes you will write the Kolo part of a small desktop chat. The window, built with Wails 3 and React, is already done (it is plain JavaScript; TypeScript works too): you only write the Go service behind it, which finds other copies of the app and talks to them directly.

Everything stays on your computer, on the address 127.0.0.1. You run a bootstrap node and two copies of the app. Nothing here needs an account or a server of ours.

1Check what you need

You need Go 1.26 or newer, Node.js with npm, Git, and three terminal windows. If Go is not installed yet, follow the first step of Build a chat in your terminal. Then install the Wails 3 command line tool, which builds the app:

Terminal
go install github.com/wailsapp/wails/v3/cmd/wails3@v3.0.0

Check it:

Terminal
wails3 version

You should see:

Text
v3.0.0

On Linux, run wails3 doctor: it lists the system packages the window needs.

2Get the starter

Terminal
git clone https://github.com/ciranda-dev/kolo-chat-wails3-starter.git && cd kolo-chat-wails3-starter

The window is already built, so this tutorial only covers the Kolo part: the service in chatservice.go, which today only declares its methods.

3Add the Kolo libraries

Add three libraries: kolo-id makes the key of each user, kolo-dht runs the bootstrap node that is already in the starter, and kolo-swarm finds peers and talks to them.

Terminal
go get github.com/ciranda-dev/kolo-id@v0.1.0 github.com/ciranda-dev/kolo-dht@v0.1.0 github.com/ciranda-dev/kolo-swarm@v0.1.0

Go adds what is missing (the starter already had the other two):

Text
go: added github.com/ciranda-dev/kolo-relay v0.1.0
go: added github.com/ciranda-dev/kolo-swarm v0.1.0
go: added golang.org/x/time v0.16.0

4Run the bootstrap node

The bootstrap node is the first address an app asks. It helps the copies find each other, then steps aside: your messages never go through it. It is already in the starter, in cmd/bootstrap. In Terminal 1, start it and leave it open:

Terminal
go run ./cmd/bootstrap

It prints one line and keeps running. Your time will differ:

Text
2026/11/12 19:20:21 bootstrap node on 127.0.0.1:4000

5Write the chat service

Open chatservice.go and delete what is in it. Then paste the blocks below one after the other, each one continuing where the previous one ended, with a blank line between functions. Each block comes with a short note on why it is there. The window calls Start and Send; the service sends the window a chat:msg event for every message that arrives and a chat:peers event whenever the number of connected peers changes.

State

chatservice.go
package main

import (
	"context"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"io"
	"log"
	"net/netip"
	"sync"
	"time"

	koloid "github.com/ciranda-dev/kolo-id"
	koloswarm "github.com/ciranda-dev/kolo-swarm"
	"github.com/wailsapp/wails/v3/pkg/application"
)

const maxMessage = 64 * 1024

// ChatMsg is the payload of the "chat:msg" event; From is the sender's kolo-id (hex public key).
type ChatMsg struct {
	From string `json:"from"`
	Text string `json:"text"`
}

type ChatService struct {
	mu      sync.Mutex
	started bool
	id      string
	ctx     context.Context
	peers   map[string]*koloswarm.Peer
}

A message crosses from Go to the window as a ChatMsg: who sent it and what it says. The service keeps the peers it is connected to in a map, behind a mutex, because the swarm and the window call it from different goroutines.

Identity

chatservice.go
// Start joins the network and returns this user's kolo-id (hex public key).
func (c *ChatService) Start() (string, error) {
	c.mu.Lock()
	if c.started {
		id := c.id
		c.mu.Unlock()
		return id, nil
	}
	c.started = true
	c.peers = map[string]*koloswarm.Peer{}
	c.mu.Unlock()

	ctx := context.Background()
	c.ctx = ctx

	id, err := koloid.Generate()
	if err != nil {
		return "", err
	}
	c.mu.Lock()
	c.id = id.PublicKeyString()
	c.mu.Unlock()

koloid.Generate makes a new key pair in memory on every start, so each run is a new user. The public key, as a hex string, is that user's name: the window shows it and other peers see it as the sender. Start returns it to the window. The started flag makes a second call to Start return the same key and do nothing else, which matters because the window may call it twice in development.

Swarm and bootstrap

chatservice.go
	sw, err := koloswarm.New(ctx, "127.0.0.1:0", id, &koloswarm.Config{LookupInterval: 5 * time.Second})
	if err != nil {
		return "", err
	}
	boot := netip.MustParseAddrPort("127.0.0.1:4000")
	if err := sw.Bootstrap(ctx, []netip.AddrPort{boot}); err != nil {
		return "", err
	}

koloswarm.New opens a UDP endpoint on a free port of 127.0.0.1 and ties it to the identity. LookupInterval makes it look the topic up again every five seconds, which is how it finds a peer that starts later. Bootstrap asks the node from step 4 for the first contacts: without it the swarm has nobody to ask.

Join the topic

chatservice.go
	// swarm events
	go func() {
		for {
			ev, err := sw.Next(ctx)
			if err != nil {
				log.Print("swarm: ", err)
				return
			}
			if ev.Kind == koloswarm.Connected && ev.Peer != nil {
				c.addPeer(ev.Peer)
			}
		}
	}()

	// join the fixed chat topic
	sum := sha256.Sum256([]byte("kolochat/v1"))
	var topic koloswarm.Topic
	copy(topic[:], sum[:])
	go func() {
		if err := sw.Join(ctx, topic, &koloswarm.JoinOptions{Announce: true, Lookup: true}); err != nil {
			log.Print("join: ", err)
		}
	}()
	return id.PublicKeyString(), nil
}

A topic is 32 bytes, here the SHA-256 of a fixed name, so every copy of the app derives the same topic with no coordination. Join with Announce and Lookup both on says "I am here" and "who else is here" in one call. It blocks, so it runs in its own goroutine, next to the loop that reads the swarm's events and hands each newly connected peer to addPeer.

Accept streams

chatservice.go
func (c *ChatService) addPeer(p *koloswarm.Peer) {
	key := hex.EncodeToString(p.PublicKey())
	c.mu.Lock()
	c.peers[key] = p
	c.mu.Unlock()
	log.Print("peer connected: ", key[:8])
	c.emitPeers()

	go func() {
		defer func() {
			c.mu.Lock()
			delete(c.peers, key)
			c.mu.Unlock()
			log.Print("peer gone: ", key[:8])
			c.emitPeers()
		}()
		for {
			s, err := p.Conn().AcceptStream(c.ctx)
			if err != nil {
				return
			}
			go func() {
				defer s.Close()
				data, err := io.ReadAll(io.LimitReader(s, maxMessage))
				if err != nil || len(data) == 0 {
					return
				}
				c.emit(key, data)
			}()
		}
	}()
}

A connected peer is a QUIC connection. addPeer stores it, so that Send can reach it, and then accepts streams from it. One stream is one message: the code reads until the sender closes it, and io.LimitReader stops at 64 KiB so a peer cannot make the app read forever. When the connection ends the peer is removed from the map.

Open streams and send

chatservice.go
func (c *ChatService) Send(text string) error {
	if len(text) > maxMessage {
		return errors.New("message too long")
	}
	c.mu.Lock()
	peers := make([]*koloswarm.Peer, 0, len(c.peers))
	for _, p := range c.peers {
		peers = append(peers, p)
	}
	c.mu.Unlock()
	if len(peers) == 0 {
		return errors.New("no peers connected")
	}
	var firstErr error
	for _, p := range peers {
		s, err := p.Conn().OpenStream(c.ctx)
		if err != nil {
			if firstErr == nil {
				firstErr = err
			}
			continue
		}
		if _, err := s.Write([]byte(text)); err != nil && firstErr == nil {
			firstErr = err
		}
		s.Close()
	}
	return firstErr
}

Send opens a new stream to every connected peer, writes the text and closes the stream, which is what marks the end of the message. An error with one peer does not stop the others, and the first error is returned to the window.

Emit the events to the window

chatservice.go
// emit hands a received message to the window as the "chat:msg" event.
func (c *ChatService) emit(from string, data []byte) {
	application.Get().Event.Emit("chat:msg", ChatMsg{From: from, Text: string(data)})
}

// emitPeers tells the window how many peers are connected, as the "chat:peers" event.
func (c *ChatService) emitPeers() {
	c.mu.Lock()
	n := len(c.peers)
	c.mu.Unlock()
	application.Get().Event.Emit("chat:peers", n)
}

The window cannot read a Go stream, so emit sends it an event named chat:msg with the sender's key and the text, and emitPeers sends chat:peers with the number of connected peers, which is what turns the badge from "Waiting for peer" to "1 peer".

6How the window talks to Go

Wails turns the public methods of the service into JavaScript functions. Make it generate them now that Start and Send exist:

Terminal
wails3 generate bindings

You should see something like this; your counts and time will differ:

Text
Wails v3.0.0 › Generate Bindings
 INFO  Processed: 291 Packages, 1 Service, 2 Methods, 0 Enums, 0 Models, 0 Events in 811.469125ms.

The starter's React code already uses them. Only these few lines matter here. The functions are plain imports from the generated bindings:

frontend/src/App.jsx
import { Start, Send } from "../bindings/github.com/ciranda-dev/kolo-chat-wails3-starter/chatservice.js"
import { Events } from "@wailsio/runtime"

The window calls Start once when it opens, and keeps the key it returns:

frontend/src/App.jsx
    Start()
      .then((id) => setMe(id))
      .catch((err) => {
        setFailed(true)
        setError(errorText(err))
      })

It listens for the peer count, which drives the badge:

frontend/src/App.jsx
    const offPeers = Events.On("chat:peers", (e) => setPeers(Number(e.data) || 0))

And for every message another peer sends:

frontend/src/App.jsx
    const off = Events.On("chat:msg", e => {
      const data = e.data
      const from = typeof data === 'object' && data ? (data.from ?? '') : ''
      const text = typeof data === 'object' && data ? (data.text ?? '') : String(data ?? '')
      setMessages((prev) => appendMessage(prev, { id: nextId.current++, from, text, mine: false }))
    })

When you press Send, the window calls Send and shows the message as yours once it went out:

frontend/src/App.jsx
    Send(text)
      .then(() => {
        setError('')
        setMessages((prev) => appendMessage(prev, { id: nextId.current++, from: me, text, mine: true }))
        setDraft('')
      })
      .catch((err) => {
        setError(errorText(err))
      })

Build and open two instances

In Terminal 2, from the project folder, build the app. This also builds the window:

Terminal
wails3 build

The binary is bin/kolo-chat. On macOS you may see a linker warning about the macOS version; it is harmless. With the bootstrap node still running in Terminal 1, start the app in Terminal 2, then again in Terminal 3:

bash
./bin/kolo-chat

Two windows open, both saying "Waiting for peer". Within a few seconds each terminal logs the other instance connecting, and the badge changes to "1 peer". Your keys will differ.

Terminal 2:

Text
2026/11/12 19:38:12 peer connected: 3db98117

Terminal 3:

Text
2026/11/12 19:38:12 peer connected: 17a2e0e9

Type in one window and press Send: the message shows up in the other, next to the first eight characters of the sender's key. If you press Send before the other window has joined, the window shows no peers connected: wait a moment and try again.

What just happened

  • Each copy joined the topic through the bootstrap node's DHT, announced itself and looked the topic up. See Topics.
  • The two copies then connected directly. The bootstrap node only helped them meet; your messages never went through it.
  • The connection is encrypted and tied to each peer's key. See Peers.
  • Here the bootstrap node runs on 127.0.0.1, so everything stays on your computer. The finished Kolo Chat uses the public network by default, and -bootstrap points it at an entry node of your own.

Next steps

  • Read the kolo-swarm page: its API, its limits and what each event means.
  • Do the same in a terminal: Build a chat in your terminal, which also covers two computers on different networks.
  • The finished code of this example is in the kolo-chat-wails3-example repository of the ciranda-dev organization.

Want more? Now add a pin: Step 3: Keep messages for offline peers.