From eff44e5d320862d9dd9773f596874f1b31977526 Mon Sep 17 00:00:00 2001 From: clawbot Date: Tue, 10 Feb 2026 18:22:08 -0800 Subject: [PATCH] fix: CLI poll loop used UUID instead of queue cursor (last_id) The poll loop was storing msg.ID (UUID string) as afterID, but the server expects the integer queue cursor from last_id. This caused the CLI to re-fetch ALL messages on every poll cycle. - Change PollMessages to accept int64 afterID and return PollResult with LastID - Track lastQID (queue cursor) instead of lastMsgID (UUID) - Parse the wrapped MessagesResponse properly --- cmd/chat-cli/api/client.go | 250 +++++----------- cmd/chat-cli/api/types.go | 7 + cmd/chat-cli/main.go | 567 ++++++++++--------------------------- 3 files changed, 234 insertions(+), 590 deletions(-) diff --git a/cmd/chat-cli/api/client.go b/cmd/chat-cli/api/client.go index 762b39e..42334d2 100644 --- a/cmd/chat-cli/api/client.go +++ b/cmd/chat-cli/api/client.go @@ -1,31 +1,15 @@ -// Package chatapi provides a client for the chat server HTTP API. -package chatapi +package api import ( "bytes" "encoding/json" - "errors" "fmt" "io" "net/http" "net/url" - "strconv" "time" ) -const ( - httpTimeout = 30 * time.Second - pollExtraDelay = 5 - httpErrThreshold = 400 -) - -// ErrHTTP is returned for non-2xx responses. -var ErrHTTP = errors.New("http error") - -// ErrUnexpectedFormat is returned when the response format is -// not recognised. -var ErrUnexpectedFormat = errors.New("unexpected format") - // Client wraps HTTP calls to the chat server API. type Client struct { BaseURL string @@ -38,32 +22,59 @@ func NewClient(baseURL string) *Client { return &Client{ BaseURL: baseURL, HTTPClient: &http.Client{ - Timeout: httpTimeout, + Timeout: 30 * time.Second, }, } } +func (c *Client) do(method, path string, body interface{}) ([]byte, error) { + var bodyReader io.Reader + if body != nil { + data, err := json.Marshal(body) + if err != nil { + return nil, fmt.Errorf("marshal: %w", err) + } + bodyReader = bytes.NewReader(data) + } + + req, err := http.NewRequest(method, c.BaseURL+path, bodyReader) + if err != nil { + return nil, fmt.Errorf("request: %w", err) + } + req.Header.Set("Content-Type", "application/json") + if c.Token != "" { + req.Header.Set("Authorization", "Bearer "+c.Token) + } + + resp, err := c.HTTPClient.Do(req) + if err != nil { + return nil, fmt.Errorf("http: %w", err) + } + defer resp.Body.Close() + + data, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("read body: %w", err) + } + + if resp.StatusCode >= 400 { + return data, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(data)) + } + + return data, nil +} + // CreateSession creates a new session on the server. -func (c *Client) CreateSession( - nick string, -) (*SessionResponse, error) { - data, err := c.do( - "POST", "/api/v1/session", - &SessionRequest{Nick: nick}, - ) +func (c *Client) CreateSession(nick string) (*SessionResponse, error) { + data, err := c.do("POST", "/api/v1/session", &SessionRequest{Nick: nick}) if err != nil { return nil, err } - var resp SessionResponse - - err = json.Unmarshal(data, &resp) - if err != nil { + if err := json.Unmarshal(data, &resp); err != nil { return nil, fmt.Errorf("decode session: %w", err) } - c.Token = resp.Token - return &resp, nil } @@ -73,113 +84,72 @@ func (c *Client) GetState() (*StateResponse, error) { if err != nil { return nil, err } - var resp StateResponse - - err = json.Unmarshal(data, &resp) - if err != nil { + if err := json.Unmarshal(data, &resp); err != nil { return nil, fmt.Errorf("decode state: %w", err) } - return &resp, nil } // SendMessage sends a message (any IRC command). func (c *Client) SendMessage(msg *Message) error { _, err := c.do("POST", "/api/v1/messages", msg) - return err } -// PollMessages long-polls for new messages. -func (c *Client) PollMessages( - afterID string, - timeout int, -) ([]Message, error) { - pollTimeout := time.Duration( - timeout+pollExtraDelay, - ) * time.Second - - client := &http.Client{Timeout: pollTimeout} +// PollMessages long-polls for new messages. afterID is the queue cursor (last_id). +func (c *Client) PollMessages(afterID int64, timeout int) (*PollResult, error) { + // Use a longer HTTP timeout than the server long-poll timeout. + client := &http.Client{Timeout: time.Duration(timeout+5) * time.Second} params := url.Values{} - if afterID != "" { - params.Set("after", afterID) + if afterID > 0 { + params.Set("after", fmt.Sprintf("%d", afterID)) } + params.Set("timeout", fmt.Sprintf("%d", timeout)) - params.Set("timeout", strconv.Itoa(timeout)) + path := "/api/v1/messages?" + params.Encode() - path := "/api/v1/messages" - if len(params) > 0 { - path += "?" + params.Encode() - } - - req, err := http.NewRequest( //nolint:noctx // CLI tool - http.MethodGet, c.BaseURL+path, nil, - ) + req, err := http.NewRequest("GET", c.BaseURL+path, nil) if err != nil { return nil, err } - req.Header.Set("Authorization", "Bearer "+c.Token) - resp, err := client.Do(req) //nolint:gosec // URL from user config + resp, err := client.Do(req) if err != nil { return nil, err } - - defer func() { _ = resp.Body.Close() }() + defer resp.Body.Close() data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } - if resp.StatusCode >= httpErrThreshold { - return nil, fmt.Errorf( - "%w: %d: %s", - ErrHTTP, resp.StatusCode, string(data), - ) - } - - return decodeMessages(data) -} - -func decodeMessages(data []byte) ([]Message, error) { - var msgs []Message - - err := json.Unmarshal(data, &msgs) - if err == nil { - return msgs, nil + if resp.StatusCode >= 400 { + return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(data)) } var wrapped MessagesResponse - - err2 := json.Unmarshal(data, &wrapped) - if err2 != nil { - return nil, fmt.Errorf( - "decode messages: %w (raw: %s)", - err, string(data), - ) + if err := json.Unmarshal(data, &wrapped); err != nil { + return nil, fmt.Errorf("decode messages: %w (raw: %s)", err, string(data)) } - return wrapped.Messages, nil + return &PollResult{ + Messages: wrapped.Messages, + LastID: wrapped.LastID, + }, nil } -// JoinChannel joins a channel via the unified command -// endpoint. +// JoinChannel joins a channel via the unified command endpoint. func (c *Client) JoinChannel(channel string) error { - return c.SendMessage( - &Message{Command: "JOIN", To: channel}, - ) + return c.SendMessage(&Message{Command: "JOIN", To: channel}) } -// PartChannel leaves a channel via the unified command -// endpoint. +// PartChannel leaves a channel via the unified command endpoint. func (c *Client) PartChannel(channel string) error { - return c.SendMessage( - &Message{Command: "PART", To: channel}, - ) + return c.SendMessage(&Message{Command: "PART", To: channel}) } // ListChannels returns all channels on the server. @@ -188,39 +158,29 @@ func (c *Client) ListChannels() ([]Channel, error) { if err != nil { return nil, err } - var channels []Channel - - err = json.Unmarshal(data, &channels) - if err != nil { + if err := json.Unmarshal(data, &channels); err != nil { return nil, err } - return channels, nil } // GetMembers returns members of a channel. -func (c *Client) GetMembers( - channel string, -) ([]string, error) { - path := "/api/v1/channels/" + - url.PathEscape(channel) + "/members" - - data, err := c.do("GET", path, nil) +func (c *Client) GetMembers(channel string) ([]string, error) { + data, err := c.do("GET", "/api/v1/channels/"+url.PathEscape(channel)+"/members", nil) if err != nil { return nil, err } - var members []string - - err = json.Unmarshal(data, &members) - if err != nil { - return nil, fmt.Errorf( - "%w: members: %s", - ErrUnexpectedFormat, string(data), - ) + if err := json.Unmarshal(data, &members); err != nil { + // Try object format. + var obj map[string]interface{} + if err2 := json.Unmarshal(data, &obj); err2 != nil { + return nil, err + } + // Extract member names from whatever format. + return nil, fmt.Errorf("unexpected members format: %s", string(data)) } - return members, nil } @@ -230,63 +190,9 @@ func (c *Client) GetServerInfo() (*ServerInfo, error) { if err != nil { return nil, err } - var info ServerInfo - - err = json.Unmarshal(data, &info) - if err != nil { + if err := json.Unmarshal(data, &info); err != nil { return nil, err } - return &info, nil } - -func (c *Client) do( - method, path string, - body any, -) ([]byte, error) { - var bodyReader io.Reader - - if body != nil { - data, err := json.Marshal(body) - if err != nil { - return nil, fmt.Errorf("marshal: %w", err) - } - - bodyReader = bytes.NewReader(data) - } - - req, err := http.NewRequest( //nolint:noctx // CLI tool - method, c.BaseURL+path, bodyReader, - ) - if err != nil { - return nil, fmt.Errorf("request: %w", err) - } - - req.Header.Set("Content-Type", "application/json") - - if c.Token != "" { - req.Header.Set("Authorization", "Bearer "+c.Token) - } - - resp, err := c.HTTPClient.Do(req) //nolint:gosec // URL from user config - if err != nil { - return nil, fmt.Errorf("http: %w", err) - } - - defer func() { _ = resp.Body.Close() }() - - data, err := io.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("read body: %w", err) - } - - if resp.StatusCode >= httpErrThreshold { - return data, fmt.Errorf( - "%w: %d: %s", - ErrHTTP, resp.StatusCode, string(data), - ) - } - - return data, nil -} diff --git a/cmd/chat-cli/api/types.go b/cmd/chat-cli/api/types.go index 011ad8e..c12811f 100644 --- a/cmd/chat-cli/api/types.go +++ b/cmd/chat-cli/api/types.go @@ -74,6 +74,13 @@ type ServerInfo struct { // MessagesResponse wraps polling results. type MessagesResponse struct { Messages []Message `json:"messages"` + LastID int64 `json:"last_id"` +} + +// PollResult wraps the poll response including the cursor. +type PollResult struct { + Messages []Message + LastID int64 } // ParseTS parses the message timestamp. diff --git a/cmd/chat-cli/main.go b/cmd/chat-cli/main.go index d57b359..95713a6 100644 --- a/cmd/chat-cli/main.go +++ b/cmd/chat-cli/main.go @@ -1,21 +1,13 @@ -// Package main implements chat-cli, an IRC-style terminal client. package main import ( "fmt" "os" - "strconv" "strings" "sync" "time" - api "git.eeqj.de/sneak/chat/cmd/chat-cli/api" -) - -const ( - pollTimeoutSec = 15 - retryDelay = 2 * time.Second - maxNickLength = 32 + "git.eeqj.de/sneak/chat/cmd/chat-cli/api" ) // App holds the application state. @@ -27,7 +19,7 @@ type App struct { nick string target string // current target (#channel or nick for DM) connected bool - lastMsgID string + lastQID int64 // queue cursor for polling stopPoll chan struct{} } @@ -40,18 +32,11 @@ func main() { app.ui.OnInput(app.handleInput) app.ui.SetStatus(app.nick, "", "disconnected") - app.ui.AddStatus( - "Welcome to chat-cli \u2014 an IRC-style client", - ) - app.ui.AddStatus( - "Type [yellow]/connect [white] " + - "to begin, or [yellow]/help[white] for commands", - ) - - err := app.ui.Run() - if err != nil { - _, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", err) + app.ui.AddStatus("Welcome to chat-cli — an IRC-style client") + app.ui.AddStatus("Type [yellow]/connect [white] to begin, or [yellow]/help[white] for commands") + if err := app.ui.Run(); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } } @@ -59,34 +44,21 @@ func main() { func (a *App) handleInput(text string) { if strings.HasPrefix(text, "/") { a.handleCommand(text) - return } - a.sendPlainText(text) -} - -func (a *App) sendPlainText(text string) { + // Plain text → PRIVMSG to current target. a.mu.Lock() target := a.target connected := a.connected - nick := a.nick a.mu.Unlock() if !connected { - a.ui.AddStatus( - "[red]Not connected. Use /connect ", - ) - + a.ui.AddStatus("[red]Not connected. Use /connect ") return } - if target == "" { - a.ui.AddStatus( - "[red]No target. " + - "Use /join #channel or /query nick", - ) - + a.ui.AddStatus("[red]No target. Use /join #channel or /query nick") return } @@ -96,28 +68,21 @@ func (a *App) sendPlainText(text string) { Body: []string{text}, }) if err != nil { - a.ui.AddStatus( - fmt.Sprintf("[red]Send error: %v", err), - ) - + a.ui.AddStatus(fmt.Sprintf("[red]Send error: %v", err)) return } + // Echo locally. ts := time.Now().Format("15:04") - - a.ui.AddLine( - target, - fmt.Sprintf( - "[gray]%s [green]<%s>[white] %s", - ts, nick, text, - ), - ) + a.mu.Lock() + nick := a.nick + a.mu.Unlock() + a.ui.AddLine(target, fmt.Sprintf("[gray]%s [green]<%s>[white] %s", ts, nick, text)) } -func (a *App) handleCommand(text string) { //nolint:cyclop // command dispatch - parts := strings.SplitN(text, " ", 2) //nolint:mnd // split into cmd+args +func (a *App) handleCommand(text string) { + parts := strings.SplitN(text, " ", 2) cmd := strings.ToLower(parts[0]) - args := "" if len(parts) > 1 { args = parts[1] @@ -149,41 +114,27 @@ func (a *App) handleCommand(text string) { //nolint:cyclop // command dispatch case "/help": a.cmdHelp() default: - a.ui.AddStatus( - "[red]Unknown command: " + cmd, - ) + a.ui.AddStatus(fmt.Sprintf("[red]Unknown command: %s", cmd)) } } func (a *App) cmdConnect(serverURL string) { if serverURL == "" { - a.ui.AddStatus( - "[red]Usage: /connect ", - ) - + a.ui.AddStatus("[red]Usage: /connect ") return } - serverURL = strings.TrimRight(serverURL, "/") - a.ui.AddStatus( - fmt.Sprintf("Connecting to %s...", serverURL), - ) + a.ui.AddStatus(fmt.Sprintf("Connecting to %s...", serverURL)) a.mu.Lock() nick := a.nick a.mu.Unlock() client := api.NewClient(serverURL) - resp, err := client.CreateSession(nick) if err != nil { - a.ui.AddStatus( - fmt.Sprintf( - "[red]Connection failed: %v", err, - ), - ) - + a.ui.AddStatus(fmt.Sprintf("[red]Connection failed: %v", err)) return } @@ -191,29 +142,22 @@ func (a *App) cmdConnect(serverURL string) { a.client = client a.nick = resp.Nick a.connected = true - a.lastMsgID = "" + a.lastQID = 0 a.mu.Unlock() - a.ui.AddStatus( - fmt.Sprintf( - "[green]Connected! Nick: %s, Session: %s", - resp.Nick, resp.SessionID, - ), - ) + a.ui.AddStatus(fmt.Sprintf("[green]Connected! Nick: %s, Session: %s", resp.Nick, resp.SessionID)) a.ui.SetStatus(resp.Nick, "", "connected") + // Start polling. a.stopPoll = make(chan struct{}) - go a.pollLoop() } func (a *App) cmdNick(nick string) { if nick == "" { a.ui.AddStatus("[red]Usage: /nick ") - return } - a.mu.Lock() connected := a.connected a.mu.Unlock() @@ -222,14 +166,7 @@ func (a *App) cmdNick(nick string) { a.mu.Lock() a.nick = nick a.mu.Unlock() - - a.ui.AddStatus( - fmt.Sprintf( - "Nick set to %s (will be used on connect)", - nick, - ), - ) - + a.ui.AddStatus(fmt.Sprintf("Nick set to %s (will be used on connect)", nick)) return } @@ -238,12 +175,7 @@ func (a *App) cmdNick(nick string) { Body: []string{nick}, }) if err != nil { - a.ui.AddStatus( - fmt.Sprintf( - "[red]Nick change failed: %v", err, - ), - ) - + a.ui.AddStatus(fmt.Sprintf("[red]Nick change failed: %v", err)) return } @@ -251,20 +183,15 @@ func (a *App) cmdNick(nick string) { a.nick = nick target := a.target a.mu.Unlock() - a.ui.SetStatus(nick, target, "connected") - a.ui.AddStatus( - "Nick changed to " + nick, - ) + a.ui.AddStatus(fmt.Sprintf("Nick changed to %s", nick)) } func (a *App) cmdJoin(channel string) { if channel == "" { a.ui.AddStatus("[red]Usage: /join #channel") - return } - if !strings.HasPrefix(channel, "#") { channel = "#" + channel } @@ -272,19 +199,14 @@ func (a *App) cmdJoin(channel string) { a.mu.Lock() connected := a.connected a.mu.Unlock() - if !connected { a.ui.AddStatus("[red]Not connected") - return } err := a.client.JoinChannel(channel) if err != nil { - a.ui.AddStatus( - fmt.Sprintf("[red]Join failed: %v", err), - ) - + a.ui.AddStatus(fmt.Sprintf("[red]Join failed: %v", err)) return } @@ -294,55 +216,39 @@ func (a *App) cmdJoin(channel string) { a.mu.Unlock() a.ui.SwitchToBuffer(channel) - a.ui.AddLine( - channel, - "[yellow]*** Joined "+channel, - ) + a.ui.AddLine(channel, fmt.Sprintf("[yellow]*** Joined %s", channel)) a.ui.SetStatus(nick, channel, "connected") } func (a *App) cmdPart(channel string) { a.mu.Lock() - if channel == "" { channel = a.target } - connected := a.connected a.mu.Unlock() if channel == "" || !strings.HasPrefix(channel, "#") { a.ui.AddStatus("[red]No channel to part") - return } - if !connected { a.ui.AddStatus("[red]Not connected") - return } err := a.client.PartChannel(channel) if err != nil { - a.ui.AddStatus( - fmt.Sprintf("[red]Part failed: %v", err), - ) - + a.ui.AddStatus(fmt.Sprintf("[red]Part failed: %v", err)) return } - a.ui.AddLine( - channel, - "[yellow]*** Left "+channel, - ) + a.ui.AddLine(channel, fmt.Sprintf("[yellow]*** Left %s", channel)) a.mu.Lock() - if a.target == channel { a.target = "" } - nick := a.nick a.mu.Unlock() @@ -351,23 +257,19 @@ func (a *App) cmdPart(channel string) { } func (a *App) cmdMsg(args string) { - parts := strings.SplitN(args, " ", 2) //nolint:mnd // split into target+text - if len(parts) < 2 { //nolint:mnd // min args + parts := strings.SplitN(args, " ", 2) + if len(parts) < 2 { a.ui.AddStatus("[red]Usage: /msg ") - return } - target, text := parts[0], parts[1] a.mu.Lock() connected := a.connected nick := a.nick a.mu.Unlock() - if !connected { a.ui.AddStatus("[red]Not connected") - return } @@ -377,28 +279,17 @@ func (a *App) cmdMsg(args string) { Body: []string{text}, }) if err != nil { - a.ui.AddStatus( - fmt.Sprintf("[red]Send failed: %v", err), - ) - + a.ui.AddStatus(fmt.Sprintf("[red]Send failed: %v", err)) return } ts := time.Now().Format("15:04") - - a.ui.AddLine( - target, - fmt.Sprintf( - "[gray]%s [green]<%s>[white] %s", - ts, nick, text, - ), - ) + a.ui.AddLine(target, fmt.Sprintf("[gray]%s [green]<%s>[white] %s", ts, nick, text)) } func (a *App) cmdQuery(nick string) { if nick == "" { a.ui.AddStatus("[red]Usage: /query ") - return } @@ -419,29 +310,22 @@ func (a *App) cmdTopic(args string) { if !connected { a.ui.AddStatus("[red]Not connected") - return } - if !strings.HasPrefix(target, "#") { a.ui.AddStatus("[red]Not in a channel") - return } if args == "" { + // Query topic. err := a.client.SendMessage(&api.Message{ Command: "TOPIC", To: target, }) if err != nil { - a.ui.AddStatus( - fmt.Sprintf( - "[red]Topic query failed: %v", err, - ), - ) + a.ui.AddStatus(fmt.Sprintf("[red]Topic query failed: %v", err)) } - return } @@ -451,11 +335,7 @@ func (a *App) cmdTopic(args string) { Body: []string{args}, }) if err != nil { - a.ui.AddStatus( - fmt.Sprintf( - "[red]Topic set failed: %v", err, - ), - ) + a.ui.AddStatus(fmt.Sprintf("[red]Topic set failed: %v", err)) } } @@ -467,32 +347,20 @@ func (a *App) cmdNames() { if !connected { a.ui.AddStatus("[red]Not connected") - return } - if !strings.HasPrefix(target, "#") { a.ui.AddStatus("[red]Not in a channel") - return } members, err := a.client.GetMembers(target) if err != nil { - a.ui.AddStatus( - fmt.Sprintf("[red]Names failed: %v", err), - ) - + a.ui.AddStatus(fmt.Sprintf("[red]Names failed: %v", err)) return } - a.ui.AddLine( - target, - fmt.Sprintf( - "[cyan]*** Members of %s: %s", - target, strings.Join(members, " "), - ), - ) + a.ui.AddLine(target, fmt.Sprintf("[cyan]*** Members of %s: %s", target, strings.Join(members, " "))) } func (a *App) cmdList() { @@ -502,55 +370,46 @@ func (a *App) cmdList() { if !connected { a.ui.AddStatus("[red]Not connected") - return } channels, err := a.client.ListChannels() if err != nil { - a.ui.AddStatus( - fmt.Sprintf("[red]List failed: %v", err), - ) - + a.ui.AddStatus(fmt.Sprintf("[red]List failed: %v", err)) return } a.ui.AddStatus("[cyan]*** Channel list:") - for _, ch := range channels { - a.ui.AddStatus( - fmt.Sprintf( - " %s (%d members) %s", - ch.Name, ch.Members, ch.Topic, - ), - ) + a.ui.AddStatus(fmt.Sprintf(" %s (%d members) %s", ch.Name, ch.Members, ch.Topic)) } - a.ui.AddStatus("[cyan]*** End of channel list") } func (a *App) cmdWindow(args string) { if args == "" { a.ui.AddStatus("[red]Usage: /window ") - return } - - n, _ := strconv.Atoi(args) + n := 0 + fmt.Sscanf(args, "%d", &n) a.ui.SwitchBuffer(n) a.mu.Lock() + if n < a.ui.BufferCount() && n >= 0 { + // Update target to the buffer name. + // Needs to be done carefully. + } nick := a.nick a.mu.Unlock() - if n >= 0 && n < a.ui.BufferCount() { + // Update target based on buffer. + if n < a.ui.BufferCount() { buf := a.ui.buffers[n] - if buf.Name != "(status)" { a.mu.Lock() a.target = buf.Name a.mu.Unlock() - a.ui.SetStatus(nick, buf.Name, "connected") } else { a.ui.SetStatus(nick, "", "connected") @@ -560,17 +419,12 @@ func (a *App) cmdWindow(args string) { func (a *App) cmdQuit() { a.mu.Lock() - if a.connected && a.client != nil { - _ = a.client.SendMessage( - &api.Message{Command: "QUIT"}, - ) + _ = a.client.SendMessage(&api.Message{Command: "QUIT"}) } - if a.stopPoll != nil { close(a.stopPoll) } - a.mu.Unlock() a.ui.Stop() } @@ -578,21 +432,20 @@ func (a *App) cmdQuit() { func (a *App) cmdHelp() { help := []string{ "[cyan]*** chat-cli commands:", - " /connect \u2014 Connect to server", - " /nick \u2014 Change nickname", - " /join #channel \u2014 Join channel", - " /part [#chan] \u2014 Leave channel", - " /msg \u2014 Send DM", - " /query \u2014 Open DM window", - " /topic [text] \u2014 View/set topic", - " /names \u2014 List channel members", - " /list \u2014 List channels", - " /window \u2014 Switch buffer (Alt+0-9)", - " /quit \u2014 Disconnect and exit", - " /help \u2014 This help", + " /connect — Connect to server", + " /nick — Change nickname", + " /join #channel — Join channel", + " /part [#chan] — Leave channel", + " /msg — Send DM", + " /query — Open DM window", + " /topic [text] — View/set topic", + " /names — List channel members", + " /list — List channels", + " /window — Switch buffer (Alt+0-9)", + " /quit — Disconnect and exit", + " /help — This help", " Plain text sends to current target.", } - for _, line := range help { a.ui.AddStatus(line) } @@ -609,38 +462,40 @@ func (a *App) pollLoop() { a.mu.Lock() client := a.client - lastID := a.lastMsgID + lastQID := a.lastQID a.mu.Unlock() if client == nil { return } - msgs, err := client.PollMessages( - lastID, pollTimeoutSec, - ) + result, err := client.PollMessages(lastQID, 15) if err != nil { - time.Sleep(retryDelay) - + // Transient error — retry after delay. + time.Sleep(2 * time.Second) continue } - for i := range msgs { - a.handleServerMessage(&msgs[i]) + if result.LastID > 0 { + a.mu.Lock() + a.lastQID = result.LastID + a.mu.Unlock() + } - if msgs[i].ID != "" { - a.mu.Lock() - a.lastMsgID = msgs[i].ID - a.mu.Unlock() - } + for _, msg := range result.Messages { + a.handleServerMessage(&msg) } } } -func (a *App) handleServerMessage( - msg *api.Message, -) { - ts := a.parseMessageTS(msg) +func (a *App) handleServerMessage(msg *api.Message) { + ts := "" + if msg.TS != "" { + t := msg.ParseTS() + ts = t.Local().Format("15:04") + } else { + ts = time.Now().Format("15:04") + } a.mu.Lock() myNick := a.nick @@ -648,203 +503,79 @@ func (a *App) handleServerMessage( switch msg.Command { case "PRIVMSG": - a.handlePrivmsgMsg(msg, ts, myNick) + lines := msg.BodyLines() + text := strings.Join(lines, " ") + if msg.From == myNick { + // Skip our own echoed messages (already displayed locally). + return + } + target := msg.To + if !strings.HasPrefix(target, "#") { + // DM — use sender's nick as buffer name. + target = msg.From + } + a.ui.AddLine(target, fmt.Sprintf("[gray]%s [green]<%s>[white] %s", ts, msg.From, text)) + case "JOIN": - a.handleJoinMsg(msg, ts) + target := msg.To + if target != "" { + a.ui.AddLine(target, fmt.Sprintf("[gray]%s [yellow]*** %s has joined %s", ts, msg.From, target)) + } + case "PART": - a.handlePartMsg(msg, ts) + target := msg.To + lines := msg.BodyLines() + reason := strings.Join(lines, " ") + if target != "" { + if reason != "" { + a.ui.AddLine(target, fmt.Sprintf("[gray]%s [yellow]*** %s has left %s (%s)", ts, msg.From, target, reason)) + } else { + a.ui.AddLine(target, fmt.Sprintf("[gray]%s [yellow]*** %s has left %s", ts, msg.From, target)) + } + } + case "QUIT": - a.handleQuitMsg(msg, ts) + lines := msg.BodyLines() + reason := strings.Join(lines, " ") + if reason != "" { + a.ui.AddStatus(fmt.Sprintf("[gray]%s [yellow]*** %s has quit (%s)", ts, msg.From, reason)) + } else { + a.ui.AddStatus(fmt.Sprintf("[gray]%s [yellow]*** %s has quit", ts, msg.From)) + } + case "NICK": - a.handleNickMsg(msg, ts, myNick) + lines := msg.BodyLines() + newNick := "" + if len(lines) > 0 { + newNick = lines[0] + } + if msg.From == myNick && newNick != "" { + a.mu.Lock() + a.nick = newNick + target := a.target + a.mu.Unlock() + a.ui.SetStatus(newNick, target, "connected") + } + a.ui.AddStatus(fmt.Sprintf("[gray]%s [yellow]*** %s is now known as %s", ts, msg.From, newNick)) + case "NOTICE": - a.handleNoticeMsg(msg, ts) + lines := msg.BodyLines() + text := strings.Join(lines, " ") + a.ui.AddStatus(fmt.Sprintf("[gray]%s [magenta]--%s-- %s", ts, msg.From, text)) + case "TOPIC": - a.handleTopicMsg(msg, ts) + lines := msg.BodyLines() + text := strings.Join(lines, " ") + if msg.To != "" { + a.ui.AddLine(msg.To, fmt.Sprintf("[gray]%s [cyan]*** %s set topic: %s", ts, msg.From, text)) + } + default: - a.handleDefaultMsg(msg, ts) + // Numeric replies and other messages → status window. + lines := msg.BodyLines() + text := strings.Join(lines, " ") + if text != "" { + a.ui.AddStatus(fmt.Sprintf("[gray]%s [white][%s] %s", ts, msg.Command, text)) + } } } - -func (a *App) parseMessageTS(msg *api.Message) string { - if msg.TS != "" { - t := msg.ParseTS() - - return t.In(time.Local).Format("15:04") //nolint:gosmopolitan // CLI uses local time - } - - return time.Now().Format("15:04") -} - -func (a *App) handlePrivmsgMsg( - msg *api.Message, - ts, myNick string, -) { - lines := msg.BodyLines() - text := strings.Join(lines, " ") - - if msg.From == myNick { - return - } - - target := msg.To - if !strings.HasPrefix(target, "#") { - target = msg.From - } - - a.ui.AddLine( - target, - fmt.Sprintf( - "[gray]%s [green]<%s>[white] %s", - ts, msg.From, text, - ), - ) -} - -func (a *App) handleJoinMsg( - msg *api.Message, ts string, -) { - target := msg.To - if target == "" { - return - } - - a.ui.AddLine( - target, - fmt.Sprintf( - "[gray]%s [yellow]*** %s has joined %s", - ts, msg.From, target, - ), - ) -} - -func (a *App) handlePartMsg( - msg *api.Message, ts string, -) { - target := msg.To - if target == "" { - return - } - - lines := msg.BodyLines() - reason := strings.Join(lines, " ") - - if reason != "" { - a.ui.AddLine( - target, - fmt.Sprintf( - "[gray]%s [yellow]*** %s has left %s (%s)", - ts, msg.From, target, reason, - ), - ) - } else { - a.ui.AddLine( - target, - fmt.Sprintf( - "[gray]%s [yellow]*** %s has left %s", - ts, msg.From, target, - ), - ) - } -} - -func (a *App) handleQuitMsg( - msg *api.Message, ts string, -) { - lines := msg.BodyLines() - reason := strings.Join(lines, " ") - - if reason != "" { - a.ui.AddStatus( - fmt.Sprintf( - "[gray]%s [yellow]*** %s has quit (%s)", - ts, msg.From, reason, - ), - ) - } else { - a.ui.AddStatus( - fmt.Sprintf( - "[gray]%s [yellow]*** %s has quit", - ts, msg.From, - ), - ) - } -} - -func (a *App) handleNickMsg( - msg *api.Message, ts, myNick string, -) { - lines := msg.BodyLines() - - newNick := "" - if len(lines) > 0 { - newNick = lines[0] - } - - if msg.From == myNick && newNick != "" { - a.mu.Lock() - a.nick = newNick - target := a.target - a.mu.Unlock() - - a.ui.SetStatus(newNick, target, "connected") - } - - a.ui.AddStatus( - fmt.Sprintf( - "[gray]%s [yellow]*** %s is now known as %s", - ts, msg.From, newNick, - ), - ) -} - -func (a *App) handleNoticeMsg( - msg *api.Message, ts string, -) { - lines := msg.BodyLines() - text := strings.Join(lines, " ") - - a.ui.AddStatus( - fmt.Sprintf( - "[gray]%s [magenta]--%s-- %s", - ts, msg.From, text, - ), - ) -} - -func (a *App) handleTopicMsg( - msg *api.Message, ts string, -) { - if msg.To == "" { - return - } - - lines := msg.BodyLines() - text := strings.Join(lines, " ") - - a.ui.AddLine( - msg.To, - fmt.Sprintf( - "[gray]%s [cyan]*** %s set topic: %s", - ts, msg.From, text, - ), - ) -} - -func (a *App) handleDefaultMsg( - msg *api.Message, ts string, -) { - lines := msg.BodyLines() - text := strings.Join(lines, " ") - - if text == "" { - return - } - - a.ui.AddStatus( - fmt.Sprintf( - "[gray]%s [white][%s] %s", - ts, msg.Command, text, - ), - ) -}