kolo docsbeta

Paso 6: Varias conversaciones en una app

Ten varias conversaciones en una sola ventana: cada una en su propia carpeta, con su propia clave, kolo-id, logs, pin e invitaciones, y un servicio que dirige las llamadas de la ventana.

En esta página

En el paso anterior añadiste perfiles y salas. Ahora una app guarda varias conversaciones: una "Family" y una "Work" en la misma ventana, cada una con sus miembros, sus salas y sus mensajes.

El código del chat que escribiste en los pasos 2 a 5 cambia poco. Pasa a ser el motor de una conversación, y un servicio nuevo, Conversations, ejecuta un motor por conversación y lleva cada llamada de la ventana al que corresponde. Cada conversación vive en su propia carpeta, con su propia clave, kolo-id, logs, capacidad del pin e invitaciones.

Este paso es solo backend, como el paso 5: escribes el código Go de abajo en el proyecto del paso anterior. La ventana de este paso, con su lista de conversaciones, ya está hecha, y la traes con un comando.

1Comprueba lo que necesitas

Necesitas lo mismo que en el paso 5: Go 1.26 o superior, Node.js, wails3, el nodo de bootstrap y un pin local. Parte del proyecto que terminaste en el paso 5. Este paso no añade ninguna biblioteca.

2Trae la ventana

La ventana de este paso tiene una primera columna nueva, de toda la altura de la ventana, con tus conversaciones, el número de mensajes nuevos de cada una, "New conversation" y "Join with an invite". Cada llamada que hace dice de qué conversación se trata. Ya está hecha: tráela desde la etiqueta step-6. La etiqueta también tiene la versión terminada de cada archivo de abajo, por si quieres comparar el tuyo.

Terminal
git fetch origin --tags
Terminal
git checkout step-6 -- frontend

3Guarda cada conversación en su propia carpeta

Hasta ahora una carpeta de datos era una conversación: su clave, su kolo-id, sus logs y sus invitaciones estaban en la raíz de la carpeta. Ahora la raíz tiene un layout.json, que dice cómo está organizada la carpeta, y una carpeta conversations/ con una carpeta por conversación:

Texto
<data>/                    0700
  layout.json              {"layout":2}, written once in a new data folder
  conversations/           0700
    <id>/                  0700; 32 hex characters from crypto/rand, not from the key
      identity.key         the kolo-id of this conversation
      local.json           the name only you see, and when it was added
      conversation.json    the key and the pin (not there while a join waits)
      members.json, directory-log, store/, invites/, pin-token   as in step 5

El ID de la carpeta de una conversación es aleatorio, así que no dice nada de la clave. Su nombre es local: vive en local.json, nunca se envía y solo lo ves tú.

Una carpeta de datos del paso 5 no tiene layout.json y guarda en su raíz los archivos de su única conversación. La app la rechaza y no cambia nada en ella: no hay migración, y nada se mueve ni se borra. El mensaje dice qué carpeta es, para que la apartes y empieces de nuevo. Un layout.json de otra organización, o uno dañado, se rechaza igual, y también una carpeta de datos que otros usuarios pueden abrir, porque podrían renombrar o reemplazar lo que la app guarda ahí. Antes de este paso, el archivo del kolo-id en la raíz hacía que kolo-id rechazara esa carpeta; ahora la app lo comprueba por sí misma.

Crea conversations.go con:

conversations.go
package main

//lint:file-ignore ST1005 these errors are sentences the window shows as they are

// Several conversations in one app.
//
// Each conversation lives in a folder of its own, <data>/conversations/<id>, with its own engine (ChatService) and
// so its own kolo-id, swarm, logs, pin and invites. One engine per conversation follows the rules of the libraries
// as they are: a pin keeps the newest capability of each owner, and a connection to a peer key serves one protocol.
// Conversations lists the folders, starts an engine for each, and routes every call of the window by ID.

import (
	"cmp"
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io/fs"
	"log"
	"os"
	"path/filepath"
	"runtime"
	"slices"
	"strings"
	"sync"
	"time"
	"unicode/utf8"
)

Añade a conversations.go los límites, los nombres que tiene una carpeta del paso 5 y los errores. Cada error es una frase que la ventana muestra tal cual:

conversations.go
const (
	layoutVersion    = 2
	layoutFile       = "layout.json"
	conversationDir  = "conversations"
	localFile        = "local.json"
	defaultConvName  = "Conversation"
	maxConvName      = 32 // characters in a conversation's name, as in a room's
	maxConversations = 8  // engines one app runs, each with its own socket, swarm and two stores
)

// oldLayoutNames are the files a data folder of step 5 or older held at its top, for its one conversation.
var oldLayoutNames = []string{"identity.key", "conversation.json", "members.json", "directory-log", "store", "invites", "pin-token"}

var (
	// ErrOldLayout matches the *DataDirError of a data folder of step 5 or older (Layout 1).
	ErrOldLayout            = errors.New("data folder made by Kolo Chat step 5 or older")
	ErrUnknownConversation  = errors.New("That conversation is not on this computer.")
	ErrTooManyConversations = errors.New("You have the most conversations this app keeps.")
	ErrNoPins               = errors.New("Start Kolo Chat with -pin-key to start a conversation. You can still join one with an invite.")
	ErrInvalidName          = errors.New("That name cannot be used")

	errNotStarted = errors.New("not started")
)

El rechazo es un error tipado que dice qué carpeta es, para que la ventana lo muestre y el código pueda preguntar errors.Is(err, ErrOldLayout):

conversations.go
// DataDirError is returned for a data folder this version cannot use, and nothing in it is changed. Layout 1 is a
// folder of step 5 or older, which held one conversation; another Layout is one of another version (-1: its
// layout.json is damaged), and Open one that other users can open. Dir is that folder.
type DataDirError struct {
	Dir    string `json:"dir"`
	Layout int    `json:"layout,omitempty"`
	Open   bool   `json:"open,omitempty"`
}

func (e *DataDirError) Error() string {
	switch {
	case e.Open:
		return "The data folder " + e.Dir + " is open to other users, who could change what Kolo Chat keeps in it. " +
			"Run chmod 700 on it, or start with another -data. Nothing in the folder is changed."
	case e.Layout == 1:
		return "The data folder " + e.Dir + " holds one conversation of Kolo Chat step 5 or older, and this version keeps " +
			"each conversation in a folder of its own. Quit Kolo Chat, move or rename that folder (nothing in it is " +
			"deleted), then open Kolo Chat again: start a new conversation, or paste a new invite."
	}
	return fmt.Sprintf("The data folder %s was made by another version of Kolo Chat (layout %d). Use that version, "+
		"or start with another -data. Nothing in the folder is changed.", e.Dir, e.Layout)
}

func (e *DataDirError) Is(target error) bool { return e.Layout == 1 && target == ErrOldLayout }

openLayout se ejecuta primero en cada arranque. Escribe layout.json solo en una carpeta nueva, después de comprobar que no hay ninguno de los nombres del paso 5:

conversations.go
// localInfo is local.json: the name only we see, and when the conversation was added here, in Unix seconds.
type localInfo struct {
	Name    string `json:"name"`
	Created int64  `json:"created"`
}

// openLayout checks the data folder's layout.json, or writes it in a new folder. A folder of step 5 or older, or of
// another layout, is refused and nothing in it is changed: there is no migration.
func openLayout(root string) error {
	if err := os.MkdirAll(root, 0o700); err != nil {
		return err
	}
	if err := privateDir(root); err != nil {
		return err
	}
	data, err := os.ReadFile(filepath.Join(root, layoutFile))
	switch {
	case err == nil:
		var l struct {
			Layout int `json:"layout"`
		}
		if json.Unmarshal(data, &l) != nil || l.Layout < layoutVersion {
			return &DataDirError{Dir: root, Layout: -1}
		}
		if l.Layout != layoutVersion {
			return &DataDirError{Dir: root, Layout: l.Layout}
		}
		if err := os.MkdirAll(filepath.Join(root, conversationDir), 0o700); err != nil { // deleted by hand: start empty
			return err
		}
		return privateDir(filepath.Join(root, conversationDir))
	case !errors.Is(err, fs.ErrNotExist): // a folder or a file we cannot read: no version wrote it
		return &DataDirError{Dir: root, Layout: -1}
	}
	for _, name := range oldLayoutNames {
		if _, err := os.Lstat(filepath.Join(root, name)); !errors.Is(err, fs.ErrNotExist) {
			return &DataDirError{Dir: root, Layout: 1}
		}
	}
	if err := os.MkdirAll(filepath.Join(root, conversationDir), 0o700); err != nil {
		return err
	}
	if err := privateDir(filepath.Join(root, conversationDir)); err != nil {
		return err
	}
	return writeJSON(filepath.Join(root, layoutFile), map[string]int{"layout": layoutVersion})
}

// privateDir refuses a folder that other users can open, who could list, rename or replace what the app keeps
// there. Windows has no such mode bits; there the folder's place in the user's profile protects it.
func privateDir(dir string) error {
	fi, err := os.Stat(dir)
	if err != nil {
		return err
	}
	if runtime.GOOS != "windows" && fi.Mode().Perm()&0o077 != 0 {
		return &DataDirError{Dir: dir, Open: true}
	}
	return nil
}

La lista de conversaciones es el listado de conversations/, así que no hay una segunda lista que mantener al día. Una carpeta sin conversation.json es una entrada que espera la respuesta de una invitación. Un local.json que falta o está dañado da el nombre "Conversation", y la conversación se abre igual:

conversations.go
// listConversations lists the conversation folders, oldest first. Of the folders without a conversation.json, the
// joins that wait, only the first is used.
func listConversations(root string) ([]*convEntry, error) {
	dir := filepath.Join(root, conversationDir)
	items, err := os.ReadDir(dir)
	if err != nil {
		return nil, err
	}
	var all []*convEntry
	for _, it := range items {
		if !it.IsDir() || !validID(it.Name()) {
			log.Printf("%s/%q: not a conversation, ignored", conversationDir, it.Name())
			continue
		}
		e := &convEntry{id: it.Name(), dir: filepath.Join(dir, it.Name())}
		e.local = loadLocal(e.dir)
		_, err := os.Lstat(filepath.Join(e.dir, "conversation.json"))
		e.joined = err == nil
		all = append(all, e)
	}
	slices.SortFunc(all, compareEntries)
	out, pending := all[:0], false
	for _, e := range all {
		if !e.joined && pending {
			log.Printf("%s/%s: not a conversation, ignored", conversationDir, e.id)
			continue
		}
		pending = pending || !e.joined
		out = append(out, e)
	}
	return out, nil
}

func compareEntries(x, y *convEntry) int {
	return cmp.Or(cmp.Compare(x.local.Created, y.local.Created), strings.Compare(x.id, y.id))
}

// loadLocal reads local.json. A damaged or missing one gives the name "Conversation", and the conversation opens.
func loadLocal(dir string) localInfo {
	var l localInfo
	data, err := os.ReadFile(filepath.Join(dir, localFile))
	if err == nil {
		err = json.Unmarshal(data, &l)
	}
	if err != nil {
		return localInfo{Name: defaultConvName}
	}
	if l.Name, err = convName(l.Name, defaultConvName); err != nil {
		l.Name = defaultConvName
	}
	return l
}

// convName checks a conversation's name: plain text of 1 to maxConvName characters. An empty one is def, or refused
// when def is empty.
func convName(name, def string) (string, error) {
	if name = strings.TrimSpace(name); name == "" {
		name = def
	}
	if name == "" || utf8.RuneCountInString(name) > maxConvName || !plainText(name) {
		return "", fmt.Errorf("%w: a name has 1 to %d characters, with no control characters.", ErrInvalidName, maxConvName)
	}
	return name, nil
}

// validID says whether id is one the app makes: 32 lowercase hex characters.
func validID(id string) bool {
	return len(id) == 32 && strings.Trim(id, "0123456789abcdef") == ""
}

// writeJSON replaces the file at path with v in one step, mode 0600.
func writeJSON(path string, v any) error {
	data, err := json.Marshal(v)
	if err != nil {
		return err
	}
	tmp := path + ".tmp"
	if err := os.WriteFile(tmp, data, 0o600); err != nil {
		return err
	}
	return os.Rename(tmp, path)
}

4Da a cada conversación su propio kolo-id y su propio swarm

¿Por qué no un solo kolo-id y un solo swarm para todas las conversaciones? Lo deciden dos reglas de las bibliotecas. Un pin guarda la capacidad más reciente de cada dueño, así que con un solo kolo-id la capacidad de una conversación quitaría del pin los logs de la otra. Y una conexión con la clave de un peer sirve a un solo protocolo, así que alguien ya conectado contigo en una conversación no podría usar en esa conexión la invitación de otra. Con un motor por conversación no pasa ninguna de las dos cosas, y el código de los pasos 2 a 5 queda como está.

La ventana recibe una lista de ConversationInfo, y cada evento de un motor le llega como un ConvEvent, con el ID de su conversación:

conversations.go
// ConversationInfo is one conversation as the window lists it. Me is our kolo-id in it, Joined is false for the
// join that waits for an invite's answer, and Error says why it did not start, with the Folder it is in.
type ConversationInfo struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Me     string `json:"me"`
	Joined bool   `json:"joined"`
	Owner  bool   `json:"owner"`
	Error  string `json:"error"`
	Folder string `json:"folder"`
}

// AppInfo is what Start returns. CanCreate says the app has a pin, which a new conversation needs.
type AppInfo struct {
	Conversations    []ConversationInfo `json:"conversations"`
	MaxConversations int                `json:"maxConversations"`
	CanCreate        bool               `json:"canCreate"`
}

// ConvEvent is the payload of every chat event: the conversation it is about, and the engine's payload.
type ConvEvent struct {
	Conv string `json:"conv"`
	Data any    `json:"data"`
}

// convEntry is one conversation folder and its engine, nil when it did not start.
type convEntry struct {
	id, dir string
	local   localInfo
	joined  bool
	chat    *ChatService
	me      string
	err     error
}

// Conversations is the window's service: it keeps one engine per conversation folder and routes every call by ID.
type Conversations struct {
	cfg  Config
	emit func(name string, data any)

	opMu sync.Mutex // one Start, Create, Join or ServiceShutdown at a time
	set  settings
	root string

	mu      sync.Mutex // guards the fields below
	started bool
	convs   map[string]*convEntry
}

// NewConversations returns the service that reads cfg when it starts and tells the window what happens through emit.
func NewConversations(cfg Config, emit func(name string, data any)) *Conversations {
	return &Conversations{cfg: cfg, emit: emit}
}

Un motor es un ChatService con la configuración de la app, en la carpeta de la conversación. La clave, el pin y el token de la línea de comandos van solo a la conversación que nombran. El emit del motor envuelve cada evento con el ID:

conversations.go
// engineConfig is the configuration of one engine: the app's, in the conversation's folder. The key, the pin and
// the token are only for the -conversation-key conversation; every other one reads its own conversation.json.
func (a *Conversations) engineConfig(dir string, configured bool) Config {
	cfg := a.cfg
	cfg.DataDir = dir
	if !configured {
		cfg.ConversationKey, cfg.PinAddr, cfg.PinKey, cfg.PinToken = "", "", "", ""
	}
	return cfg
}

// startEngine starts the conversation's engine, whose events go to the window tagged with the conversation's ID.
func (a *Conversations) startEngine(e *convEntry, cfg Config) {
	c := NewChatService(cfg, func(name string, data any) { a.emit(name, ConvEvent{Conv: e.id, Data: data}) })
	if e.me, e.err = c.Start(); e.err == nil {
		e.chat, e.joined = c, c.Joined()
	} else {
		log.Printf("conversation %s did not start: %v", e.id, e.err)
	}
}

func (a *Conversations) add(e *convEntry) {
	a.mu.Lock()
	defer a.mu.Unlock()
	a.convs[e.id] = e
}

5Crea conversaciones y únete a ellas

Start abre la carpeta de datos, lista las conversaciones y arranca todos los motores a la vez. Una conversación que no arranca muestra por qué en su fila de la lista, con su carpeta, y las demás funcionan. -conversation-key sigue funcionando: arranca la carpeta cuyo conversation.json tiene esa clave, o crea una para ella. Un puerto fijo de -listen admite una sola conversación, porque cada motor tiene su propio socket:

conversations.go
// Start opens the data folder and starts every conversation in it, each on its own. It fails only for a bad
// setting (*ConfigError) or a data folder it cannot use (*DataDirError): a conversation that does not start
// shows its Error in the list, and the others run.
func (a *Conversations) Start() (AppInfo, error) {
	a.opMu.Lock()
	defer a.opMu.Unlock()
	if a.isStarted() {
		return a.info(), nil
	}
	set, err := a.cfg.resolve()
	if err != nil {
		return AppInfo{}, err
	}
	if err := openLayout(set.DataDir); err != nil {
		return AppInfo{}, err
	}
	entries, err := listConversations(set.DataDir)
	if err != nil {
		return AppInfo{}, err
	}
	a.set, a.root = set, set.DataDir
	configured, err := a.findConfigured(entries)
	if err != nil {
		return AppInfo{}, err
	}
	isNew := configured != nil && !slices.Contains(entries, configured)
	if isNew {
		entries = append(entries, configured)
	}
	if set.fixedPort() && len(entries) > 1 {
		if isNew {
			a.dropFolder(configured)
		}
		return AppInfo{}, &ConfigError{Setting: "listen", Err: errFixedPort}
	}

	a.mu.Lock()
	a.started, a.convs = true, map[string]*convEntry{}
	a.mu.Unlock()
	var wg sync.WaitGroup
	for _, e := range entries {
		wg.Go(func() { a.startEngine(e, a.engineConfig(e.dir, e == configured)) })
	}
	wg.Wait()
	for _, e := range entries {
		a.add(e)
	}
	if isNew && configured.err != nil { // a bad setting, such as a -pin-token, as before there were several
		a.dropFolder(configured)
		a.shutdown()
		return AppInfo{}, configured.err
	}
	a.emitList()
	return a.info(), nil
}

// findConfigured returns the conversation that -conversation-key names: the folder whose conversation.json holds
// the key, or a new folder for it. It is nil without the setting.
func (a *Conversations) findConfigured(entries []*convEntry) (*convEntry, error) {
	if !a.set.inConversation {
		return nil, nil
	}
	for _, e := range entries {
		if v, found, err := loadConversation(e.dir); err == nil && found && slices.Equal(v.Key, a.set.conversationKey[:]) {
			return e, nil
		}
	}
	return a.newFolder(defaultConvName)
}

Create empieza una conversación de la que eres dueño. Su clave son 32 bytes de crypto/rand, en memoria hasta que el motor la guarda en conversation.json, con modo 0600. Usa el pin de -pin y -pin-key. Un Create que falla antes de guardar la clave borra su carpeta nueva:

conversations.go
// Create starts a new conversation that we own, with a key from crypto/rand and the app's pin. name is only ours.
func (a *Conversations) Create(name string) (ConversationInfo, error) {
	a.opMu.Lock()
	defer a.opMu.Unlock()
	name, err := convName(name, defaultConvName)
	if err != nil {
		return ConversationInfo{}, err
	}
	if err := a.hasRoom(); err != nil {
		return ConversationInfo{}, err
	}
	if len(a.set.pinKey) == 0 {
		return ConversationInfo{}, ErrNoPins
	}
	e, err := a.newFolder(name)
	if err != nil {
		return ConversationInfo{}, err
	}
	key := make([]byte, 32)
	if _, err := rand.Read(key); err != nil {
		a.dropFolder(e)
		return ConversationInfo{}, err
	}
	cfg := a.engineConfig(e.dir, false)
	cfg.ConversationKey, cfg.PinAddr, cfg.PinKey = hex.EncodeToString(key), a.cfg.PinAddr, a.cfg.PinKey
	clear(key)
	if a.startEngine(e, cfg); e.err != nil {
		a.dropFolder(e)
		return ConversationInfo{}, e.err
	}
	a.add(e)
	a.emitList()
	return a.infoOf(e), nil
}

// newFolder makes the folder of a new conversation, with a random ID that has nothing to do with its key.
func (a *Conversations) newFolder(name string) (*convEntry, error) {
	b := make([]byte, 16)
	if _, err := rand.Read(b); err != nil {
		return nil, err
	}
	id := hex.EncodeToString(b)
	e := &convEntry{id: id, dir: filepath.Join(a.root, conversationDir, id), local: localInfo{Name: name, Created: time.Now().Unix()}}
	if err := os.Mkdir(e.dir, 0o700); err != nil {
		return nil, err
	}
	if err := writeJSON(filepath.Join(e.dir, localFile), e.local); err != nil {
		os.RemoveAll(e.dir)
		return nil, err
	}
	return e, nil
}

// dropFolder removes the folder of a conversation that failed before it had a conversation.json: nothing in it is
// worth keeping.
func (a *Conversations) dropFolder(e *convEntry) {
	if _, err := os.Lstat(filepath.Join(e.dir, "conversation.json")); errors.Is(err, fs.ErrNotExist) {
		os.RemoveAll(e.dir)
	}
}

Join recibe un código de invitación y un nombre. Cada invitación es una conversación propia, en una carpeta nueva con un kolo-id nuevo, así que quien te invitó nunca está ya conectado a ese kolo-id. Un Join que falla, o que cancelas, conserva su carpeta, y el siguiente Join la vuelve a usar. El límite de ocho conversaciones cuenta la entrada que espera:

conversations.go
// Join uses an invite code in the join that waits, or in a new folder: each invite is a conversation of its own,
// with a new kolo-id. A Join that fails or is cancelled keeps that folder for the next one.
func (a *Conversations) Join(code, name string) (ConversationInfo, error) {
	name, err := convName(name, defaultConvName)
	if err != nil {
		return ConversationInfo{}, err
	}
	a.opMu.Lock()
	e, err := a.pendingJoin()
	a.opMu.Unlock()
	if err != nil {
		return ConversationInfo{}, err
	}
	if err := e.chat.Join(code); err != nil {
		return ConversationInfo{}, err
	}
	a.opMu.Lock()
	defer a.opMu.Unlock()
	a.mu.Lock()
	e.local.Name, e.joined = name, true
	local := e.local
	a.mu.Unlock()
	if err := writeJSON(filepath.Join(e.dir, localFile), local); err != nil {
		log.Print("conversation name: ", err) // the conversation works, and shows as "Conversation" after a restart
	}
	a.emitList()
	return a.infoOf(e), nil
}

// pendingJoin returns the conversation that waits for a join, made and started when there is none. One that did not
// start is refused with its error: its folder has to be moved first.
func (a *Conversations) pendingJoin() (*convEntry, error) {
	a.mu.Lock()
	var pending *convEntry
	for _, e := range a.convs {
		if !e.joined {
			pending = e
		}
	}
	a.mu.Unlock()
	switch {
	case pending != nil && pending.chat == nil:
		return nil, pending.err
	case pending != nil:
		return pending, nil
	}
	if err := a.hasRoom(); err != nil {
		return nil, err
	}
	e, err := a.newFolder(defaultConvName)
	if err != nil {
		return nil, err
	}
	if a.startEngine(e, a.engineConfig(e.dir, false)); e.err != nil {
		a.dropFolder(e)
		return nil, e.err
	}
	a.add(e)
	a.emitList() // the window shows the kolo-id the join uses, for an invite that needs approval
	return e, nil
}

// CancelJoin stops the Join that waits, for the inviter or for its answer.
func (a *Conversations) CancelJoin() {
	a.mu.Lock()
	var c *ChatService
	for _, e := range a.convs {
		if !e.joined && e.chat != nil {
			c = e.chat
		}
	}
	a.mu.Unlock()
	if c != nil {
		c.CancelJoin()
	}
}

// hasRoom says whether one more conversation may be added: the bound counts the join that waits and the ones that
// did not start, and a fixed -listen port holds one conversation only.
func (a *Conversations) hasRoom() error {
	a.mu.Lock()
	defer a.mu.Unlock()
	switch n := len(a.convs); {
	case !a.started:
		return errNotStarted
	case n >= maxConversations:
		return ErrTooManyConversations
	case n >= 1 && a.set.fixedPort():
		return &ConfigError{Setting: "listen", Err: errFixedPort}
	}
	return nil
}

6Lleva las llamadas de la ventana a la conversación correcta

Cada llamada de la ventana nombra su conversación. engine busca el ID en el mapa de motores en marcha y devuelve ErrUnknownConversation para cualquier otro. El mapa solo tiene IDs que la app listó o creó, así que nunca se arma una ruta con lo que envía la ventana:

conversations.go
// List returns the conversations in the order they were added, never nil.
func (a *Conversations) List() []ConversationInfo {
	a.mu.Lock()
	entries := make([]convEntry, 0, len(a.convs))
	for _, e := range a.convs {
		entries = append(entries, *e)
	}
	a.mu.Unlock()
	slices.SortFunc(entries, func(x, y convEntry) int { return compareEntries(&x, &y) })
	out := make([]ConversationInfo, 0, len(entries))
	for _, e := range entries {
		out = append(out, e.info())
	}
	return out
}

func (e convEntry) info() ConversationInfo {
	info := ConversationInfo{ID: e.id, Name: e.local.Name, Me: e.me, Joined: e.joined}
	if e.chat != nil {
		info.Owner = e.chat.IsOwner()
	}
	if e.err != nil {
		info.Error, info.Folder = e.err.Error(), e.dir
	}
	return info
}

func (a *Conversations) info() AppInfo {
	return AppInfo{Conversations: a.List(), MaxConversations: maxConversations, CanCreate: len(a.set.pinKey) > 0}
}

func (a *Conversations) infoOf(e *convEntry) ConversationInfo {
	a.mu.Lock()
	snapshot := *e
	a.mu.Unlock()
	return snapshot.info()
}

func (a *Conversations) emitList() { a.emit("chat:conversations", a.List()) }
conversations.go
// Send, Members and the methods down to Deny are the engine's, for the conversation conv.

func (a *Conversations) Send(conv, room, text string) error {
	return call(a, conv, func(c *ChatService) error { return c.Send(room, text) })
}

func (a *Conversations) Members(conv string) ([]Member, error) {
	return get(a, conv, (*ChatService).Members)
}

func (a *Conversations) Rooms(conv string) ([]string, error) {
	return get(a, conv, (*ChatService).Rooms)
}

func (a *Conversations) IsOwner(conv string) (bool, error) {
	return get(a, conv, (*ChatService).IsOwner)
}

func (a *Conversations) SetProfile(conv, name, avatar string) error {
	return call(a, conv, func(c *ChatService) error { return c.SetProfile(name, avatar) })
}

func (a *Conversations) AddRoom(conv, name string) error {
	return call(a, conv, func(c *ChatService) error { return c.AddRoom(name) })
}

func (a *Conversations) CreateInvite(conv string, opts InviteOptions) (InviteInfo, error) {
	c, err := a.engine(conv)
	if err != nil {
		return InviteInfo{}, err
	}
	return c.CreateInvite(opts)
}

func (a *Conversations) Invites(conv string) ([]InviteInfo, error) {
	c, err := a.engine(conv)
	if err != nil {
		return nil, err
	}
	return c.Invites()
}

func (a *Conversations) Revoke(conv, id string) error {
	return call(a, conv, func(c *ChatService) error { return c.Revoke(id) })
}

func (a *Conversations) Approve(conv string, request uint64) error {
	return call(a, conv, func(c *ChatService) error { return c.Approve(request) })
}

func (a *Conversations) Deny(conv string, request uint64) error {
	return call(a, conv, func(c *ChatService) error { return c.Deny(request) })
}
conversations.go
// engine returns the running engine of conv. Only IDs the app listed or made are in the map, so no path is ever
// built from what the window sends.
func (a *Conversations) engine(conv string) (*ChatService, error) {
	a.mu.Lock()
	defer a.mu.Unlock()
	if e := a.convs[conv]; e != nil && e.chat != nil {
		return e.chat, nil
	}
	return nil, ErrUnknownConversation
}

func call(a *Conversations, conv string, f func(*ChatService) error) error {
	c, err := a.engine(conv)
	if err != nil {
		return err
	}
	return f(c)
}

func get[T any](a *Conversations, conv string, f func(*ChatService) T) (T, error) {
	c, err := a.engine(conv)
	if err != nil {
		var zero T
		return zero, err
	}
	return f(c), nil
}

Cuando la app se cierra, Wails llama a ServiceShutdown, que detiene todos los motores:

conversations.go
// ServiceShutdown stops every conversation. Wails calls it when the app quits.
func (a *Conversations) ServiceShutdown() error {
	a.opMu.Lock()
	defer a.opMu.Unlock()
	return a.shutdown()
}

func (a *Conversations) shutdown() error {
	a.mu.Lock()
	engines := a.running()
	a.started, a.convs = false, nil
	a.mu.Unlock()
	errs := make([]error, len(engines))
	var wg sync.WaitGroup
	for i, c := range engines {
		wg.Go(func() { errs[i] = c.ServiceShutdown() })
	}
	wg.Wait()
	return errors.Join(errs...)
}

// running returns the engines that run. The caller holds mu.
func (a *Conversations) running() []*ChatService {
	var out []*ChatService
	for _, e := range a.convs {
		if e.chat != nil {
			out = append(out, e.chat)
		}
	}
	return out
}

func (a *Conversations) isStarted() bool {
	a.mu.Lock()
	defer a.mu.Unlock()
	return a.started
}

7Deja que el pin empiece conversaciones

En el paso 5, -pin-key se rechazaba sin -conversation-key. Ahora -pin y -pin-key nombran el pin de las conversaciones que empiezas en la ventana, así que -pin-key se acepta solo. -pin-token sigue necesitando -conversation-key: un token lo emite un kolo-id, y solo esa conversación lo tiene.

En config.go, reemplaza las causas de un ConfigError por:

config.go
// Causes of a ConfigError, besides the errors of kolo-pin for a bad token.
var (
	ErrMissing   = errors.New("is required")
	ErrMalformed = errors.New("is malformed")

	errFixedPort = errors.New("has a fixed port, which only one conversation can use: use port 0")
)

En config.go, reemplaza Config por:

config.go
// Config is everything the chat needs from outside. A zero field takes its default, if it has one.
// LoadConfig fills it from flags and environment variables.
type Config struct {
	DataDir         string        // -data, KOLO_CHAT_DATA: one folder per conversation, see conversations.go. Default: <user config dir>/kolo-chat
	Bootstrap       string        // -bootstrap, KOLO_CHAT_BOOTSTRAP: IP:PORT of a bootstrap node. Default 127.0.0.1:4000
	Listen          string        // -listen, KOLO_CHAT_LISTEN: local IP:PORT of every conversation. Default 127.0.0.1:0; a fixed port allows one conversation
	ConversationKey string        // -conversation-key, KOLO_CHAT_CONVERSATION_KEY: 64 hex characters (32 bytes), the key of one conversation, kept in its folder. Empty to start conversations in the window or join with an invite
	PinAddr         string        // -pin, KOLO_CHAT_PIN: IP:PORT of the pin. Default 127.0.0.1:7450. The pin of the conversations started here; a joiner gets the pin from the invite
	PinKey          string        // -pin-key, KOLO_CHAT_PIN_KEY: the pin's public key in hex (`kolo-pin id`). Required with a conversation key and to start conversations in the window
	PinToken        string        // -pin-token, KOLO_CHAT_PIN_TOKEN: a capability in hex for the -conversation-key conversation, issued by its kolo-id. Default: the app issues one
	PinTTL          time.Duration // -pin-ttl, KOLO_CHAT_PIN_TTL: lifetime of the capability the app issues. Default 720h
	PinQuota        uint64        // -pin-quota, KOLO_CHAT_PIN_QUOTA: bytes the pin may keep for you, in the capability the app issues. Default 16777216
	LookupInterval  time.Duration // -lookup-interval, KOLO_CHAT_LOOKUP_INTERVAL: time between topic lookups. Default 5s
}

En LoadConfig, reemplaza las líneas de conversation-key, pin, pin-key y pin-token por:

config.go
		{"conversation-key", "KOLO_CHAT_CONVERSATION_KEY", "32-byte key of one conversation, in hex (leave it out to start conversations in the window or join with an invite)", text(&c.ConversationKey)},
		{"pin", "KOLO_CHAT_PIN", "IP:PORT of the pin (default " + defaultPinAddr + ")", text(&c.PinAddr)},
		{"pin-key", "KOLO_CHAT_PIN_KEY", "public key of the pin, in hex: the pin of the conversations you start (required with -conversation-key)", text(&c.PinKey)},
		{"pin-token", "KOLO_CHAT_PIN_TOKEN", "capability for the pin of the -conversation-key conversation, in hex (default: issued by the app)", text(&c.PinToken)},

En config.go, reemplaza el comentario de resolve por:

config.go
// resolve applies the defaults and checks every setting, returning a *ConfigError for the first bad one.
// Without a conversation key a chat starts as a joiner: the key and the pin come from an invite (see
// useConversation). The pin is then the one of the conversations started in the window, and a token, which is
// for the key's conversation only, is refused. A token is checked later, in capability, because it needs the
// identity.
func (c Config) resolve() (settings, error) {

En resolve, reemplaza las comprobaciones de la clave de la conversación y de la clave del pin, hasta s.inConversation = true, por:

config.go
	if c.ConversationKey == "" && c.PinToken != "" {
		return s, &ConfigError{Setting: "conversation-key", Err: ErrMissing}
	}
	if c.ConversationKey != "" || c.PinKey != "" {
		s.pinKey = make(ed25519.PublicKey, ed25519.PublicKeySize)
		if err := parseHex("pin-key", c.PinKey, s.pinKey); err != nil {
			return s, err
		}
	}
	if c.ConversationKey == "" {
		return s, nil
	}
	if err := parseHex("conversation-key", c.ConversationKey, s.conversationKey[:]); err != nil {
		return s, err
	}
	s.inConversation = true

Añade a config.go:

config.go
// fixedPort says whether the listen address names a port, which one socket only can hold.
func (s settings) fixedPort() bool {
	ap, err := netip.ParseAddrPort(s.Listen)
	return err == nil && ap.Port() != 0
}

Un dueño del paso 5 daba su clave en cada arranque. Una conversación creada con New conversation solo tiene su clave en su carpeta, así que ahora el motor guarda en conversation.json la clave que recibió. En invite.go, reemplaza savedConversation por:

invite.go
// savedConversation returns the conversation this chat is in at start: the one in the configuration, or the one
// the data directory keeps, from an invite or from an earlier start with a key. A joiner that has none yet returns
// false. The configured one is kept, so the app finds it again after a restart.
func (c *ChatService) savedConversation() (conversation, bool, error) {
	saved, found, err := loadConversation(c.set.DataDir)
	if err != nil {
		return saved, false, err
	}
	if !c.set.inConversation {
		return saved, found, nil
	}
	mine := conversation{Key: slices.Clone(c.set.conversationKey[:]), PinAddr: c.set.PinAddr, PinKey: slices.Clone(c.set.pinKey), Owner: slices.Clone(c.pub)}
	if found && !slices.Equal(saved.Key, mine.Key) {
		err := errors.New("is not the conversation this data directory joined with an invite: use another -data")
		return mine, false, &ConfigError{Setting: "conversation-key", Err: err}
	}
	if found {
		mine.Owner = saved.Owner // a member that also has the key is still a member
	}
	if err := saveConversation(c.set.DataDir, mine); err != nil {
		return mine, false, err
	}
	return mine, true, nil
}

El motor ya no es el servicio de la ventana. En chatservice.go, añade este comentario encima de ChatService:

chatservice.go
// ChatService is the engine of one conversation: its own kolo-id, swarm, logs, pin and invites in its own folder.
// Conversations runs one per conversation and routes the window's calls to it.
type ChatService struct {

En chatservice.go, reemplaza el comentario de ServiceShutdown por:

chatservice.go
// ServiceShutdown stops the chat and closes the store. Conversations calls it when the app quits.
func (c *ChatService) ServiceShutdown() error {

8Conéctalo en main.go

Ahora la ventana habla con Conversations. En main.go, reemplaza el comentario encima de emit y el servicio por:

main.go
	// Each conversation tells the window what happens by emitting events; the Wails app is only needed once one is.
	emit := func(name string, data any) { application.Get().Event.Emit(name, data) }

	app := application.New(application.Options{
		Name:        "Kolo Chat",
		Description: "Peer-to-peer desktop chat built with Kolo",
		Icon:        appIcon,
		Services: []application.Service{
			application.NewService(NewConversations(cfg, emit)),

9Lo que hace la ventana con esto

La ventana guarda por separado el estado de cada conversación. Escucha cada evento del chat y se lo da a la conversación que nombra, y a la lista:

frontend/src/App.jsx
    const offs = CHAT_EVENTS.map((name) => Events.On(name, (e) => dispatch({ type: 'event', name, payload: e.data })))
    offs.push(Events.On('chat:conversations', (e) => dispatch({ type: 'list', list: e.data })))

Enviar nombra la conversación seleccionada:

frontend/src/App.jsx
    Send(id, room, text)
      .then(() => {
        setError('')
        dispatch({ type: 'sent', conv: id, from: row.me, room, text })
      })
      .catch((err) => setError(errorText(err)))

New conversation llama a Create con el nombre que escribiste:

frontend/src/Conversations.jsx
    Create(name)
      .then((info) => {
        setName('')
        setNaming(false)
        onCreated(info)
      })
      .catch((err) => setError(errorText(err)))

Y Join with an invite llama a Join con el código y el nombre:

frontend/src/Invite.jsx
    Join(code, name)
      .then((info) => onJoined(info))

10Ejecútalo

Arranca el nodo de bootstrap y déjalo en marcha:

Terminal
go run ./cmd/bootstrap

En otra terminal, arranca el pin local y déjalo en marcha:

Terminal
go run github.com/ciranda-dev/kolo-pin/cmd/kolo-pin run -data .data/pin -max-bytes 100MB

Compila la app:

Terminal
GOWORK=off wails3 build

Las carpetas de datos del paso 5 ahora se rechazan. Pruébalo si quieres: la ventana dice qué carpeta es y que no se cambió nada en ella.

Terminal
./bin/kolo-chat -data .data/alice

Así que usa carpetas nuevas. Alice solo necesita la clave pública del pin, en su terminal, para empezar conversaciones:

Terminal
export KOLO_CHAT_PIN_KEY=$(go run github.com/ciranda-dev/kolo-pin/cmd/kolo-pin id -data .data/pin)
Terminal
./bin/kolo-chat -data .data/alice-6

En la ventana de Alice haz clic en New conversation, escribe "Family" y haz clic en Create. Hazlo otra vez con "Work". Cada conversación tiene su propio kolo-id: el comienzo de la clave junto a "you" cambia cuando seleccionas la otra.

Arranca a Bob en otra terminal, sin la variable:

Terminal
./bin/kolo-chat -data .data/bob-6

Bob se une a las dos. En la ventana de Alice selecciona Family, haz clic en Invite y crea una invitación. En la ventana de Bob haz clic en Join with an invite, pega el código, escribe el nombre "Family" y haz clic en Join. Con "Require my approval", Alice ve "wants to join" bajo Family y hace clic en Approve. Después haz lo mismo con Work. Bob se une a la segunda conversación de Alice mientras está en la primera: para él, el otro kolo-id de Alice es un desconocido.

Arranca a Carol en una tercera terminal, e invítala solo a Work:

Terminal
./bin/kolo-chat -data .data/carol-6

Envía un mensaje en Family y otro en Work. Cada uno aparece solo en su conversación. La ventana de Carol tiene Work y nada de Family. Cuando llega un mensaje a una conversación que no tienes seleccionada, la lista muestra cuántos son nuevos.

11Ejecuta las pruebas

La etiqueta tiene las pruebas de este paso: dos conversaciones que nunca ven los mensajes de la otra, una segunda entrada mientras estás en la primera, las dos conversaciones en un mismo pin, el rechazo de una carpeta del paso 5, -conversation-key y cada llamada rechazada. Tráelas:

Terminal
git checkout step-6 -- '*_test.go'
Terminal
GOWORK=off go test ./...

12Lo que queda separado, y los límites

Cada conversación tiene su propia clave, kolo-id, perfil, salas, logs, capacidad del pin e invitaciones. El nombre de una conversación es local. Los miembros de dos conversaciones no pueden relacionarte por tu kolo-id, porque tienes uno distinto en cada una, pero la dirección de tu computadora y el momento de tus conexiones sí pueden.

Conoce los límites:

  • No hay Leave en este paso. El ejemplo terminado tiene Leave, que quita una conversación de tu computadora: su carpeta, con su clave, sus logs, sus invitaciones y el kolo-id que usaba. A los demás no se les avisa y conservan lo que enviaste, y tus otras conversaciones siguen.
  • No se puede quitar a un miembro. Nadie puede quitar a un miembro ni cambiar la clave de una conversación, como en el paso 5. Revocar una invitación frena a gente nueva, no a quien ya entró.
  • Ocho conversaciones como máximo, contando la entrada que espera. Cada una cuesta un socket UDP, un nodo DHT, un swarm y dos almacenes Pebble. El ejemplo terminado convierte el límite en un ajuste, 64 por defecto.
  • Las carpetas antiguas se rechazan. Una carpeta de datos del paso 5 se rechaza, nunca se migra, y no se cambia nada en ella.
  • Un puerto fijo, una conversación. Con -listen en un puerto distinto de 0, una segunda conversación se rechaza.
  • Una segunda invitación a la misma conversación crea una segunda carpeta con un segundo kolo-id: los demás ven a un miembro nuevo.

Siguientes pasos

  • Pónganse de acuerdo en quién está en una conversación y qué salas tiene: Paso 7: Acordar miembros y salas con kolo-braid.
  • El ejemplo terminado, kolo-chat-wails3-example, añade Leave, un ajuste para el límite, relays de conexión, el notch y la bandeja. Su docs/how-it-works.md, sección "Several conversations", cuenta cómo; su docs/security.md tiene las notas de seguridad. El ejemplo terminado muestra una sola lista de salas, una por conversación, y su pin es opcional: sin él, los mensajes llegan a la gente solo mientras está en línea.
  • Lee la página de kolo-swarm: una conexión por clave de peer, y sus topics.
  • Para comparar tus archivos con los terminados, usa la etiqueta step-6 del repositorio del starter.