Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d9c9d1524 | ||
|
|
f5fb0862ff | ||
|
|
dab5387cbd | ||
|
|
1d9827beb0 | ||
|
|
fcbd84f873 | ||
|
|
cef9374416 | ||
|
|
9ad3c96d43 | ||
|
|
48400440dd | ||
|
|
0e812a2479 | ||
|
|
f319721e01 | ||
|
|
9de625d617 | ||
|
|
15306dc0c2 | ||
|
|
7c3cedc549 | ||
|
|
1c73f1b1ef | ||
|
|
b2b5c8c7cb | ||
|
|
b6ff30de78 | ||
|
|
1bd719fa58 | ||
|
|
be297d3a49 |
@@ -7,55 +7,8 @@ on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
# ── Server binaries (no CGo, cross-compile freely) ───────────────────────────
|
||||
|
||||
server:
|
||||
name: Server binaries
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- goos: linux
|
||||
goarch: amd64
|
||||
- goos: linux
|
||||
goarch: arm64
|
||||
- goos: darwin
|
||||
goarch: amd64
|
||||
- goos: darwin
|
||||
goarch: arm64
|
||||
- goos: windows
|
||||
goarch: amd64
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
|
||||
- name: Build daemon + anchor
|
||||
env:
|
||||
GOOS: ${{ matrix.goos }}
|
||||
GOARCH: ${{ matrix.goarch }}
|
||||
CGO_ENABLED: "0"
|
||||
run: |
|
||||
SUFFIX="${{ matrix.goos }}-${{ matrix.goarch }}"
|
||||
[ "${{ matrix.goos }}" = "windows" ] && EXT=".exe" || EXT=""
|
||||
go build -trimpath -ldflags="-s -w" -o "dist/waste-daemon-${SUFFIX}${EXT}" ./cmd/daemon
|
||||
go build -trimpath -ldflags="-s -w" -o "dist/waste-anchor-${SUFFIX}${EXT}" ./cmd/anchor
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: server-${{ matrix.goos }}-${{ matrix.goarch }}
|
||||
path: dist/
|
||||
|
||||
# ── Desktop app (Wails, requires CGo + webview libs) ─────────────────────────
|
||||
# Runs only on Linux amd64 with the default runner.
|
||||
# For macOS/Windows desktop builds, add self-hosted runners with those platforms
|
||||
# and duplicate this job (adjusting the runs-on and platform deps).
|
||||
|
||||
desktop-linux:
|
||||
name: Desktop app (Linux amd64)
|
||||
build:
|
||||
name: Build & release
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
@@ -67,7 +20,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: '24'
|
||||
|
||||
- name: Install Wails CLI
|
||||
run: go install github.com/wailsapp/wails/v2/cmd/wails@latest
|
||||
@@ -77,44 +30,52 @@ jobs:
|
||||
sudo apt-get update -q
|
||||
sudo apt-get install -y \
|
||||
libgtk-3-dev \
|
||||
libwebkit2gtk-4.0-dev \
|
||||
libwebkit2gtk-4.1-dev \
|
||||
libayatana-appindicator3-dev
|
||||
|
||||
# ── Server binaries (CGO_ENABLED=0, cross-compile freely) ──────────────
|
||||
|
||||
- name: Build server binaries
|
||||
run: |
|
||||
mkdir -p dist
|
||||
build() {
|
||||
local GOOS=$1 GOARCH=$2
|
||||
local SUFFIX="${GOOS}-${GOARCH}"
|
||||
local EXT=""
|
||||
[ "$GOOS" = "windows" ] && EXT=".exe"
|
||||
CGO_ENABLED=0 GOOS=$GOOS GOARCH=$GOARCH \
|
||||
go build -trimpath -ldflags="-s -w" \
|
||||
-o "dist/waste-daemon-${SUFFIX}${EXT}" ./cmd/daemon
|
||||
CGO_ENABLED=0 GOOS=$GOOS GOARCH=$GOARCH \
|
||||
go build -trimpath -ldflags="-s -w" \
|
||||
-o "dist/waste-anchor-${SUFFIX}${EXT}" ./cmd/anchor
|
||||
}
|
||||
build linux amd64
|
||||
build linux arm64
|
||||
build darwin amd64
|
||||
build darwin arm64
|
||||
build windows amd64
|
||||
|
||||
# ── Desktop app (Linux amd64, CGo + Wails) ─────────────────────────────
|
||||
|
||||
- name: Build frontend
|
||||
run: |
|
||||
cd web
|
||||
npm ci
|
||||
npm install
|
||||
npm run build
|
||||
cp -r dist ../cmd/app/frontend/dist
|
||||
|
||||
- name: Build desktop app
|
||||
run: |
|
||||
mkdir -p dist
|
||||
cd cmd/app
|
||||
wails build -trimpath -ldflags="-s -w" -o ../../dist/waste-linux-amd64
|
||||
wails build -trimpath -ldflags="-s -w" -tags webkit2_41 -o ../../dist/waste-linux-amd64
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: desktop-linux-amd64
|
||||
path: dist/waste-linux-amd64
|
||||
|
||||
# ── Release: collect all artifacts and publish ────────────────────────────────
|
||||
|
||||
release:
|
||||
name: Publish release
|
||||
needs: [server, desktop-linux]
|
||||
runs-on: ubuntu-latest
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts/
|
||||
merge-multiple: true
|
||||
# ── Publish release (tags only) ─────────────────────────────────────────
|
||||
|
||||
- name: Create release
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
uses: https://gitea.com/actions/gitea-release-action@main
|
||||
with:
|
||||
token: ${{ secrets.RELEASE_TOKEN }}
|
||||
files: artifacts/*
|
||||
files: dist/*
|
||||
prerelease: ${{ contains(github.ref_name, '-') }}
|
||||
|
||||
@@ -224,3 +224,83 @@ Each in-progress `.tmp` file has a corresponding `.tmp.meta` JSON sidecar:
|
||||
|
||||
The sidecar is written when the transfer starts and removed on completion or
|
||||
corruption. Interrupted transfers keep the sidecar indefinitely.
|
||||
|
||||
---
|
||||
|
||||
## EXT-007 — P2P Message History Gossip
|
||||
|
||||
**Status:** implemented (daemon mode)
|
||||
**Affects:** peer-to-peer wire (two new message types); IPC (new event)
|
||||
|
||||
### Motivation
|
||||
|
||||
When a peer joins a network for the first time (or reconnects after an
|
||||
absence), they have no history. This extension lets them request recent
|
||||
messages from an existing peer over the already-established encrypted
|
||||
DataChannel, without involving the anchor.
|
||||
|
||||
### Wire messages
|
||||
|
||||
#### `history_request`
|
||||
|
||||
Sent by the newly-connected peer to the first peer whose hello is verified.
|
||||
One request per room.
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "history_request",
|
||||
"room": "general",
|
||||
"since": 1700000000000,
|
||||
"limit": 200
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|---------|---------------|-------------|
|
||||
| `room` | string | Room to request history for. |
|
||||
| `since` | int64 (ms) | Only return messages with `ts > since`. 0 = return up to `limit` most recent. |
|
||||
| `limit` | int (max 500) | Maximum messages to return. Responder may return fewer. |
|
||||
|
||||
#### `history_chunk`
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "history_chunk",
|
||||
"room": "general",
|
||||
"history": [
|
||||
{ "mid": "...", "from": "<peer-id>", "from_alias": "alice", "text": "hello", "ts": 1700000001000 }
|
||||
],
|
||||
"history_done": true
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|----------------|--------|-------------|
|
||||
| `history` | array | Messages, oldest-first. |
|
||||
| `history_done` | bool | Always `true` (single-chunk response). |
|
||||
|
||||
### Deduplication
|
||||
|
||||
`mid` is the deduplication key. The store uses `INSERT OR IGNORE` on `mid`,
|
||||
so receiving a message twice (live or via gossip) is a no-op. Messages
|
||||
without a `mid` are assigned one at receive time and are not gossipped.
|
||||
|
||||
### Behaviour
|
||||
|
||||
- The **receiver** sends one `history_request` per known room immediately
|
||||
after hello verification with the **first** peer it connects to. Requesting
|
||||
only the first peer avoids fan-out amplification.
|
||||
- The **responder** queries its SQLite store and replies with a single
|
||||
`history_chunk`. `limit` is capped at 500 server-side. Rate-limited to one
|
||||
request per (peer, room) per 60 seconds.
|
||||
- Received history messages are saved to the local store (`INSERT OR IGNORE`)
|
||||
and emitted as `history_loaded` IPC events so the UI can display them.
|
||||
|
||||
### IPC event
|
||||
|
||||
```json
|
||||
{ "type": "history_loaded", "room": "general", "messages": [...] }
|
||||
```
|
||||
|
||||
Emitted once per room after a `history_chunk` is fully processed. The UI
|
||||
should render these messages with a visual separator from live messages.
|
||||
|
||||
@@ -91,10 +91,10 @@ DM rooms (`dm:<peerId>`) appear automatically in both interfaces when messages a
|
||||
- Live progress bar per active transfer
|
||||
- Push (📎) sends directly to a peer without them needing to share a folder
|
||||
|
||||
**Not yet done:** daemon-side resume UX (IPC event to surface resumable transfers to the UI on reconnect).
|
||||
On daemon start, the download directory is scanned for `.tmp.meta` sidecars and a `resumable_transfers` IPC event is emitted so the UI can show pending transfers with a progress bar.
|
||||
|
||||
### Native UI
|
||||
Web frontend (React, already built) + [Wails v2](https://wails.io) shell for native packaging. Wails is Go-native — no Rust toolchain required. The daemon runs embedded in the same process; the webview connects to the existing WebSocket IPC at `ws://127.0.0.1:17338`. Scaffolded in `cmd/app/`; build with `./build-app.sh`. Remaining work: system tray, OS notifications.
|
||||
Web frontend (React, already built) + [Wails v2](https://wails.io) shell for native packaging. Wails is Go-native — no Rust toolchain required. The daemon runs embedded in the same process; the webview connects to the existing WebSocket IPC at `ws://127.0.0.1:17338`. Built in `cmd/app/` via `./build-app.sh`. System tray (Linux/Windows) and OS notifications are implemented. macOS menu-bar tray requires Cocoa main-thread integration — currently a stub.
|
||||
|
||||
---
|
||||
|
||||
@@ -133,6 +133,10 @@ Web frontend (React, already built) + [Wails v2](https://wails.io) shell for nat
|
||||
| ✅ shipped | PWA manifest — installable via "Add to Home Screen" on iOS and Android |
|
||||
| ✅ shipped | Native desktop app (Wails 2) — system tray (Linux/Windows), OS notifications, single binary |
|
||||
| ✅ shipped | Gitea Actions CI — server binaries (all platforms via cross-compile) + desktop app (Linux amd64) |
|
||||
| ✅ shipped | File transfer resume UX — resumable transfers surfaced in Transfers panel on reconnect |
|
||||
| ✅ shipped | P2P message history gossip (EXT-007) — new peers receive recent history from first connected peer |
|
||||
| ✅ shipped | Date-aware timestamps in TUI and web UI |
|
||||
| ✅ shipped | Historical peer alias resolution in web UI |
|
||||
|
||||
---
|
||||
|
||||
|
||||
89
QUICKSTART.md
Normal file
89
QUICKSTART.md
Normal file
@@ -0,0 +1,89 @@
|
||||
# waste — quick start
|
||||
|
||||
waste is a private, encrypted chat and file sharing app for people you trust.
|
||||
No accounts, no phone numbers, no central server that knows your messages.
|
||||
|
||||
Pick the option that fits you best.
|
||||
|
||||
---
|
||||
|
||||
## Option 1 — Just open it in your browser
|
||||
|
||||
If someone is running a waste anchor server and has shared the URL with you:
|
||||
|
||||
1. Open the URL in any modern browser
|
||||
2. Enter your name and a network name your group has agreed on
|
||||
3. Done — you're in
|
||||
|
||||
On mobile, tap **Share → Add to Home Screen** to install it as an app icon.
|
||||
|
||||
To invite someone: click the 🔗 button in the sidebar and share the link.
|
||||
|
||||
> Your identity and messages stay in your browser. Nothing is stored on the server — the server only helps peers find each other.
|
||||
|
||||
---
|
||||
|
||||
## Option 2 — Desktop app (recommended for regular use)
|
||||
|
||||
Download the latest `waste` binary for your platform from the [releases page](../../releases).
|
||||
|
||||
**Linux / macOS:**
|
||||
```bash
|
||||
chmod +x waste-linux-amd64 # or waste-darwin-arm64, etc.
|
||||
./waste-linux-amd64
|
||||
```
|
||||
|
||||
**Windows:** double-click `waste-windows-amd64.exe`.
|
||||
|
||||
The app opens a window with the waste UI. Enter your name, the anchor URL, and a network name to join. Your identity is saved between sessions in your config directory (`~/.config/waste` on Linux, `~/Library/Application Support/waste` on macOS, `%APPDATA%\waste` on Windows).
|
||||
|
||||
On Linux and Windows a tray icon appears — closing the window hides to tray rather than quitting. Right-click the tray icon to reopen or quit.
|
||||
|
||||
---
|
||||
|
||||
## Option 3 — Run the daemon manually (headless / power users)
|
||||
|
||||
If you want the daemon running in the background without the desktop UI — on a server, over SSH, or with the web UI in a browser pointed at your local machine:
|
||||
|
||||
```bash
|
||||
# Download waste-daemon from the releases page, then:
|
||||
./waste-daemon -alias yourname -anchor wss://your-anchor-server/ws
|
||||
```
|
||||
|
||||
Then open the web UI in a browser at the anchor URL, or point the web UI's daemon mode at `ws://127.0.0.1:17338`.
|
||||
|
||||
Full flag reference:
|
||||
|
||||
| Flag | Default | Description |
|
||||
|---|---|---|
|
||||
| `-alias` | `anon` | Your display name |
|
||||
| `-anchor` | — | Anchor server WebSocket URL |
|
||||
| `-data-dir` | `~/.waste` | Where identity and messages are stored |
|
||||
| `-download-dir` | same as data-dir | Where received files are saved |
|
||||
| `-ipc-port` | `17337` | Local TCP IPC port |
|
||||
| `-ws-port` | `0` (off) | WebSocket IPC port (needed for web UI) |
|
||||
| `-turn-url` | — | TURN relay URL (fixes mobile/CGNAT) |
|
||||
| `-turn-secret` | — | TURN shared secret |
|
||||
|
||||
---
|
||||
|
||||
## Inviting someone
|
||||
|
||||
1. Click `Ctrl+I` in the TUI, or click **Generate invite** in the web UI
|
||||
2. Share the `waste:...` link with your friend (Signal, email, anything)
|
||||
3. They open it in a browser or pass it to `waste-daemon --join 'waste:...'`
|
||||
|
||||
Invite links encode the anchor URL and network name. The anchor never sees your messages.
|
||||
|
||||
---
|
||||
|
||||
## Running your own anchor server
|
||||
|
||||
The anchor is a tiny signaling server that helps peers find each other — it never sees plaintext messages or file contents. You need a VPS with a domain and TLS.
|
||||
|
||||
```bash
|
||||
# On your VPS:
|
||||
./waste-anchor -bind 127.0.0.1:8080
|
||||
```
|
||||
|
||||
Put it behind nginx with a `/ws` WebSocket proxy and serve the web UI static files at `/`. See [README.md](README.md#hosting-on-a-vps) for the full nginx setup.
|
||||
@@ -383,7 +383,7 @@ func (m model) refreshViewport() model {
|
||||
w := m.vpContentWidth()
|
||||
var sb strings.Builder
|
||||
for _, e := range m.messages[room] {
|
||||
ts := styleMsgTime.Render(e.at.Format("15:04"))
|
||||
ts := styleMsgTime.Render(formatMsgTime(e.at))
|
||||
var from string
|
||||
if e.fromMe {
|
||||
from = styleMsgMe.Render(e.from)
|
||||
@@ -614,6 +614,17 @@ func filterIDs(ids []proto.PeerID, remove proto.PeerID) []proto.PeerID {
|
||||
return out
|
||||
}
|
||||
|
||||
func formatMsgTime(t time.Time) string {
|
||||
now := time.Now()
|
||||
if t.Year() == now.Year() && t.YearDay() == now.YearDay() {
|
||||
return t.Format("15:04")
|
||||
}
|
||||
if t.Year() == now.Year() && t.YearDay() == now.YearDay()-1 {
|
||||
return "Yesterday " + t.Format("15:04")
|
||||
}
|
||||
return t.Format("Jan 2 15:04")
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
|
||||
@@ -127,6 +127,8 @@ func handleClient(conn net.Conn, mgr *netmgr.Manager) {
|
||||
|
||||
// Send initial state snapshot.
|
||||
send(stateSnapshot(mgr))
|
||||
// Send stored history for each room so the UI is populated on connect.
|
||||
sendStoredHistory(mgr, send)
|
||||
|
||||
scanner := bufio.NewScanner(conn)
|
||||
for scanner.Scan() {
|
||||
@@ -214,6 +216,7 @@ func handleClient(conn net.Conn, mgr *netmgr.Manager) {
|
||||
} else {
|
||||
// Group chat → spec "chat" type: flat {type, mid, room, text, ts}
|
||||
mid := randomHex(16)
|
||||
msgID := proto.ComputeMsgID(n.Identity.PeerID(), cmd.Room, ts, cmd.Body)
|
||||
wire, err := json.Marshal(proto.PeerMessage{
|
||||
Type: proto.MsgChat,
|
||||
Mid: mid,
|
||||
@@ -226,11 +229,12 @@ func handleClient(conn net.Conn, mgr *netmgr.Manager) {
|
||||
}
|
||||
n.Mesh.Broadcast(wire)
|
||||
local := &proto.ChatMessage{
|
||||
Mid: mid,
|
||||
From: n.Identity.PeerID(),
|
||||
Room: cmd.Room,
|
||||
Text: cmd.Body,
|
||||
Ts: ts,
|
||||
Mid: mid,
|
||||
MsgID: msgID,
|
||||
From: n.Identity.PeerID(),
|
||||
Room: cmd.Room,
|
||||
Text: cmd.Body,
|
||||
Ts: ts,
|
||||
}
|
||||
n.Mesh.SaveMessage(local)
|
||||
n.Mesh.Emit(proto.IpcMessage{
|
||||
@@ -455,11 +459,55 @@ func stateSnapshot(mgr *netmgr.Manager) proto.IpcMessage {
|
||||
msg.Rooms = append(msg.Rooms, r)
|
||||
}
|
||||
}
|
||||
// Include all historically-known peers so the UI can resolve aliases in history.
|
||||
if known, err := all[0].Store.KnownPeers(); err == nil {
|
||||
connected := map[proto.PeerID]bool{}
|
||||
for _, p := range msg.ConnectedPeers {
|
||||
connected[p.ID] = true
|
||||
}
|
||||
for id, alias := range known {
|
||||
if connected[id] {
|
||||
continue // already in ConnectedPeers
|
||||
}
|
||||
msg.KnownPeers = append(msg.KnownPeers, proto.PeerInfo{
|
||||
ID: id,
|
||||
Alias: alias,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return msg
|
||||
}
|
||||
|
||||
// sendStoredHistory pushes recent messages for all known rooms to a newly-connected IPC client.
|
||||
func sendStoredHistory(mgr *netmgr.Manager, send func(proto.IpcMessage)) {
|
||||
all := mgr.All()
|
||||
if len(all) == 0 {
|
||||
return
|
||||
}
|
||||
n := all[0] // use first network; multi-network history follows same pattern
|
||||
if n.Store == nil {
|
||||
return
|
||||
}
|
||||
rooms := []string{"general"}
|
||||
if extra, err := n.Store.Rooms(); err == nil {
|
||||
rooms = append(rooms, extra...)
|
||||
}
|
||||
for _, room := range rooms {
|
||||
msgs, err := n.Store.RecentMessagesSince(room, 0, 200)
|
||||
if err != nil || len(msgs) == 0 {
|
||||
continue
|
||||
}
|
||||
send(proto.IpcMessage{
|
||||
Type: proto.EvtHistoryLoaded,
|
||||
NetworkID: n.ID,
|
||||
Room: room,
|
||||
Messages: msgs,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func errMsg(s string) proto.IpcMessage {
|
||||
return proto.IpcMessage{Type: proto.EvtError, ErrorMessage: s}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
package mesh
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os"
|
||||
"sync"
|
||||
@@ -51,6 +52,12 @@ type Mesh struct {
|
||||
// attempt to connect to. Drained by the anchor client's runOnce loop.
|
||||
PendingConnect chan proto.PeerID
|
||||
|
||||
// historyRequested tracks rooms for which we have already sent a history_request
|
||||
// this session. Reset on reconnect is intentional (new peers may have newer history).
|
||||
historyMu sync.Mutex
|
||||
historyRequested map[string]bool // room → true
|
||||
historyFirstPeer proto.PeerID // ID of the peer we requested history from
|
||||
|
||||
// subscribers receive a copy of every event (fan-out to IPC clients)
|
||||
subMu sync.Mutex
|
||||
subs []chan proto.IpcMessage
|
||||
@@ -60,12 +67,13 @@ type Mesh struct {
|
||||
// Pass a non-nil store to enable message and peer persistence.
|
||||
func New(id *crypto.Identity, st *store.Store) *Mesh {
|
||||
return &Mesh{
|
||||
Identity: id,
|
||||
Store: st,
|
||||
peers: make(map[proto.PeerID]*PeerConn),
|
||||
outbound: make(map[string]*outboundTransfer),
|
||||
inbound: make(map[string]*inboundTransfer),
|
||||
PendingConnect: make(chan proto.PeerID, 32),
|
||||
Identity: id,
|
||||
Store: st,
|
||||
peers: make(map[proto.PeerID]*PeerConn),
|
||||
outbound: make(map[string]*outboundTransfer),
|
||||
inbound: make(map[string]*inboundTransfer),
|
||||
PendingConnect: make(chan proto.PeerID, 32),
|
||||
historyRequested: make(map[string]bool),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -235,6 +243,122 @@ func (m *Mesh) Unsubscribe(ch <-chan proto.IpcMessage) {
|
||||
}
|
||||
}
|
||||
|
||||
// RequestHistoryFrom sends history_request messages to peerID for all rooms
|
||||
// we know about but haven't yet requested this session. Only contacts the first
|
||||
// peer we connect to, to avoid fan-out amplification.
|
||||
func (m *Mesh) RequestHistoryFrom(peerID proto.PeerID) {
|
||||
if m.Store == nil {
|
||||
return
|
||||
}
|
||||
m.historyMu.Lock()
|
||||
if m.historyFirstPeer != "" && m.historyFirstPeer != peerID {
|
||||
m.historyMu.Unlock()
|
||||
return // only request from the first peer
|
||||
}
|
||||
m.historyFirstPeer = peerID
|
||||
m.historyMu.Unlock()
|
||||
|
||||
rooms, err := m.Store.Rooms()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// Always include "general" even if not explicitly created.
|
||||
roomSet := map[string]bool{"general": true}
|
||||
for _, r := range rooms {
|
||||
roomSet[r] = true
|
||||
}
|
||||
|
||||
m.historyMu.Lock()
|
||||
var toRequest []string
|
||||
for r := range roomSet {
|
||||
if !m.historyRequested[r] {
|
||||
m.historyRequested[r] = true
|
||||
toRequest = append(toRequest, r)
|
||||
}
|
||||
}
|
||||
m.historyMu.Unlock()
|
||||
|
||||
for _, room := range toRequest {
|
||||
req, err := json.Marshal(proto.PeerMessage{
|
||||
Type: proto.MsgHistoryRequest,
|
||||
Room: room,
|
||||
Limit: 200,
|
||||
})
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
m.SendTo(peerID, req)
|
||||
log.Printf("mesh: sent history_request room=%s to %s", room, peerID.Short())
|
||||
}
|
||||
}
|
||||
|
||||
// HandleHistoryRequest responds to a history_request from a peer.
|
||||
func (m *Mesh) HandleHistoryRequest(from proto.PeerID, room string, sinceMs int64, limit int) {
|
||||
if m.Store == nil {
|
||||
return
|
||||
}
|
||||
msgs, err := m.Store.RecentMessagesSince(room, sinceMs, limit)
|
||||
if err != nil {
|
||||
log.Printf("mesh: history_request from %s room=%s: %v", from.Short(), room, err)
|
||||
return
|
||||
}
|
||||
|
||||
// Look up aliases for from_peer values.
|
||||
entries := make([]proto.HistoryEntry, 0, len(msgs))
|
||||
for _, msg := range msgs {
|
||||
entries = append(entries, proto.HistoryEntry{
|
||||
Mid: msg.Mid,
|
||||
From: string(msg.From),
|
||||
FromAlias: m.Store.PeerAlias(msg.From),
|
||||
Text: msg.Text,
|
||||
Ts: msg.Ts,
|
||||
})
|
||||
}
|
||||
|
||||
chunk, err := json.Marshal(proto.PeerMessage{
|
||||
Type: proto.MsgHistoryChunk,
|
||||
Room: room,
|
||||
History: entries,
|
||||
HistoryDone: true,
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
m.SendTo(from, chunk)
|
||||
log.Printf("mesh: sent history_chunk room=%s to %s: %d msgs", room, from.Short(), len(entries))
|
||||
}
|
||||
|
||||
// HandleHistoryChunk saves received history messages and emits history_loaded.
|
||||
func (m *Mesh) HandleHistoryChunk(room string, entries []proto.HistoryEntry) {
|
||||
if m.Store == nil || len(entries) == 0 {
|
||||
return
|
||||
}
|
||||
var saved []proto.ChatMessage
|
||||
for _, e := range entries {
|
||||
msg := &proto.ChatMessage{
|
||||
Mid: e.Mid,
|
||||
MsgID: e.Mid, // mid is already content-addressed for gossipped messages
|
||||
From: proto.PeerID(e.From),
|
||||
Room: room,
|
||||
Text: e.Text,
|
||||
Ts: e.Ts,
|
||||
}
|
||||
if err := m.Store.SaveMessage(msg); err != nil {
|
||||
continue
|
||||
}
|
||||
saved = append(saved, *msg)
|
||||
}
|
||||
if len(saved) == 0 {
|
||||
return
|
||||
}
|
||||
m.emit(proto.IpcMessage{
|
||||
Type: proto.EvtHistoryLoaded,
|
||||
Room: room,
|
||||
Messages: saved,
|
||||
})
|
||||
log.Printf("mesh: history_chunk room=%s: %d/%d new messages", room, len(saved), len(entries))
|
||||
}
|
||||
|
||||
// Emit sends an event to all IPC subscribers (exported for ipc/nat packages).
|
||||
func (m *Mesh) Emit(msg proto.IpcMessage) {
|
||||
m.emit(msg)
|
||||
|
||||
@@ -197,6 +197,8 @@ func handleDCMessage(data []byte, from proto.PeerID, localID *crypto.Identity, m
|
||||
})
|
||||
// Tell the new peer about everyone we can currently see.
|
||||
go m.sendGossipTo(from)
|
||||
// Request message history from this peer (EXT-007).
|
||||
go m.RequestHistoryFrom(from)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -212,11 +214,12 @@ func dispatchPeerMessage(msg proto.PeerMessage, from proto.PeerID, m *Mesh) {
|
||||
switch msg.Type {
|
||||
case proto.MsgChat:
|
||||
chat := &proto.ChatMessage{
|
||||
Mid: midOrRandom(msg.Mid),
|
||||
From: from,
|
||||
Room: msg.Room,
|
||||
Text: msg.Text,
|
||||
Ts: msg.Ts,
|
||||
Mid: midOrRandom(msg.Mid),
|
||||
MsgID: proto.ComputeMsgID(from, msg.Room, msg.Ts, msg.Text),
|
||||
From: from,
|
||||
Room: msg.Room,
|
||||
Text: msg.Text,
|
||||
Ts: msg.Ts,
|
||||
}
|
||||
m.SaveMessage(chat)
|
||||
m.Emit(proto.IpcMessage{Type: proto.EvtMessageReceived, Message: chat})
|
||||
@@ -298,6 +301,12 @@ func dispatchPeerMessage(msg proto.PeerMessage, from proto.PeerID, m *Mesh) {
|
||||
}
|
||||
}
|
||||
log.Printf("mesh: gossip from %s: %d hints, %d new", from.Short(), len(msg.Gossip.Peers), newPeers)
|
||||
case proto.MsgHistoryRequest:
|
||||
go m.HandleHistoryRequest(from, msg.Room, msg.Since, msg.Limit)
|
||||
|
||||
case proto.MsgHistoryChunk:
|
||||
go m.HandleHistoryChunk(msg.Room, msg.History)
|
||||
|
||||
case proto.MsgPing:
|
||||
log.Printf("mesh: ping from %s", from.Short())
|
||||
case proto.MsgPong:
|
||||
|
||||
@@ -91,6 +91,47 @@ func writePartialMeta(path string, t *inboundTransfer) {
|
||||
os.WriteFile(path, data, 0o644) //nolint:errcheck
|
||||
}
|
||||
|
||||
// ScanResumable scans the download directory for .tmp.meta sidecars left by
|
||||
// interrupted transfers and emits a resumable_transfers IPC event listing them.
|
||||
// Called once after a network is joined so the UI can show pending transfers.
|
||||
func (m *Mesh) ScanResumable() {
|
||||
if m.DownloadDir == "" {
|
||||
return
|
||||
}
|
||||
metas, _ := filepath.Glob(filepath.Join(m.DownloadDir, "*.tmp.meta"))
|
||||
var files []proto.ResumableFile
|
||||
for _, mp := range metas {
|
||||
data, err := os.ReadFile(mp)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
var meta partialMeta
|
||||
if err := json.Unmarshal(data, &meta); err != nil {
|
||||
continue
|
||||
}
|
||||
tp := strings.TrimSuffix(mp, ".meta")
|
||||
info, err := os.Stat(tp)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
files = append(files, proto.ResumableFile{
|
||||
Name: meta.Name,
|
||||
SHA256: meta.SHA256,
|
||||
From: meta.From,
|
||||
Size: meta.Size,
|
||||
Offset: info.Size(),
|
||||
})
|
||||
}
|
||||
if len(files) == 0 {
|
||||
return
|
||||
}
|
||||
m.emit(proto.IpcMessage{
|
||||
Type: proto.EvtResumableTransfers,
|
||||
ResumableFiles: files,
|
||||
})
|
||||
log.Printf("transfer: %d resumable transfer(s) found in %s", len(files), m.DownloadDir)
|
||||
}
|
||||
|
||||
// OfferFile reads filename from ShareDir, computes its SHA-256, and sends a
|
||||
// file-offer to peerID over the existing "yaw" DataChannel.
|
||||
func (m *Mesh) OfferFile(peerID proto.PeerID, filename string) error {
|
||||
|
||||
@@ -162,6 +162,8 @@ func (mgr *Manager) Join(name, shareDir string) (string, error) {
|
||||
}()
|
||||
}
|
||||
|
||||
go m.ScanResumable()
|
||||
|
||||
mgr.emit(proto.IpcMessage{
|
||||
Type: proto.EvtNetworkJoined,
|
||||
NetworkID: netID,
|
||||
@@ -249,6 +251,8 @@ func (mgr *Manager) JoinByHash(netHash64, shareDir string) (string, error) {
|
||||
}()
|
||||
}
|
||||
|
||||
go m.ScanResumable()
|
||||
|
||||
mgr.emit(proto.IpcMessage{
|
||||
Type: proto.EvtNetworkJoined,
|
||||
NetworkID: netID,
|
||||
|
||||
@@ -3,7 +3,11 @@
|
||||
// Binary data (keys, signatures) is hex-encoded; signaling boxes are base64.
|
||||
package proto
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ── Identity ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -43,8 +47,10 @@ const (
|
||||
MsgFileAccept MsgType = "file-accept"
|
||||
MsgFileCancel MsgType = "file-cancel"
|
||||
MsgFileDone MsgType = "file-done"
|
||||
MsgPing MsgType = "ping"
|
||||
MsgPong MsgType = "pong"
|
||||
MsgPing MsgType = "ping"
|
||||
MsgPong MsgType = "pong"
|
||||
MsgHistoryRequest MsgType = "history_request"
|
||||
MsgHistoryChunk MsgType = "history_chunk"
|
||||
)
|
||||
|
||||
// PmMessage is a private message sent directly over a single peer link (§8 "pm").
|
||||
@@ -83,17 +89,52 @@ type PeerMessage struct {
|
||||
Reason string `json:"reason,omitempty"` // file-cancel
|
||||
|
||||
Seq *uint64 `json:"seq,omitempty"` // ping/pong
|
||||
|
||||
// history_request fields
|
||||
Since int64 `json:"since,omitempty"` // Unix ms; 0 = no lower bound
|
||||
Limit int `json:"limit,omitempty"`
|
||||
|
||||
// history_chunk fields
|
||||
History []HistoryEntry `json:"history,omitempty"`
|
||||
HistoryDone bool `json:"history_done,omitempty"`
|
||||
}
|
||||
|
||||
// ResumableFile describes a partially-downloaded file found on daemon startup.
|
||||
type ResumableFile struct {
|
||||
Name string `json:"name"`
|
||||
SHA256 string `json:"sha256"`
|
||||
From string `json:"from"` // peer ID hex
|
||||
Size int64 `json:"size"`
|
||||
Offset int64 `json:"offset"` // bytes already received
|
||||
}
|
||||
|
||||
// HistoryEntry is one message in a history_chunk response.
|
||||
type HistoryEntry struct {
|
||||
Mid string `json:"mid"`
|
||||
From string `json:"from"` // peer ID hex
|
||||
FromAlias string `json:"from_alias"` // advisory
|
||||
Text string `json:"text"`
|
||||
Ts int64 `json:"ts"` // Unix ms
|
||||
}
|
||||
|
||||
// ChatMessage is a group chat message (wire type "chat", §8).
|
||||
// Also used internally for persisting PMs after they are received.
|
||||
type ChatMessage struct {
|
||||
Mid string `json:"mid,omitempty"` // optional dedup id (required when relay hops > 0)
|
||||
From PeerID `json:"from,omitempty"` // set by receiver from DC context; not on wire for pm
|
||||
To *PeerID `json:"to,omitempty"` // internal only — not transmitted; set for DMs
|
||||
Room string `json:"room"`
|
||||
Text string `json:"text"`
|
||||
Ts int64 `json:"ts"` // Unix milliseconds
|
||||
Mid string `json:"mid,omitempty"` // optional dedup id (required when relay hops > 0)
|
||||
MsgID string `json:"msg_id,omitempty"` // EXT-007: content-addressed gossip ID
|
||||
From PeerID `json:"from,omitempty"` // set by receiver from DC context; not on wire for pm
|
||||
To *PeerID `json:"to,omitempty"` // internal only — not transmitted; set for DMs
|
||||
Room string `json:"room"`
|
||||
Text string `json:"text"`
|
||||
Ts int64 `json:"ts"` // Unix milliseconds
|
||||
}
|
||||
|
||||
// ComputeMsgID returns the EXT-007 content-addressed ID for a message.
|
||||
// sha256(fromID \x00 room \x00 ts_decimal \x00 text)
|
||||
func ComputeMsgID(fromID PeerID, room string, ts int64, text string) string {
|
||||
h := sha256.New()
|
||||
fmt.Fprintf(h, "%s\x00%s\x00%d\x00%s", string(fromID), room, ts, text)
|
||||
return fmt.Sprintf("sha256:%x", h.Sum(nil))
|
||||
}
|
||||
|
||||
// PeerGossip shares known peer addresses.
|
||||
@@ -259,6 +300,8 @@ const (
|
||||
EvtIdentityImported IpcMsgType = "identity_imported"
|
||||
EvtSharesList IpcMsgType = "shares_list"
|
||||
EvtRoomCreated IpcMsgType = "room_created" // field: room (name)
|
||||
EvtHistoryLoaded IpcMsgType = "history_loaded" // fields: room, messages
|
||||
EvtResumableTransfers IpcMsgType = "resumable_transfers" // field: resumable_files
|
||||
)
|
||||
|
||||
// NetworkInfo summarises one joined network for state_snapshot and network_joined events.
|
||||
@@ -307,12 +350,15 @@ type IpcMessage struct {
|
||||
MasterID string `json:"master_id,omitempty"` // daemon's master public key hex
|
||||
LocalPeer *PeerInfo `json:"local_peer,omitempty"`
|
||||
ConnectedPeers []PeerInfo `json:"connected_peers,omitempty"`
|
||||
KnownPeers []PeerInfo `json:"known_peers,omitempty"` // historically seen, not currently connected
|
||||
Rooms []string `json:"rooms,omitempty"`
|
||||
// multi-network: all joined networks (additive)
|
||||
Networks []NetworkInfo `json:"networks,omitempty"`
|
||||
ErrorMessage string `json:"error_message,omitempty"`
|
||||
InviteGenerated string `json:"invite,omitempty"`
|
||||
Files []FileEntry `json:"files,omitempty"`
|
||||
Files []FileEntry `json:"files,omitempty"`
|
||||
Messages []ChatMessage `json:"messages,omitempty"` // history_loaded
|
||||
ResumableFiles []ResumableFile `json:"resumable_files,omitempty"` // resumable_transfers
|
||||
Shares []ShareEntry `json:"shares,omitempty"`
|
||||
ShareNetworks []string `json:"network_ids,omitempty"` // for add_share command: scope to specific network IDs, or ["*"] for global
|
||||
// export_identity / import_identity
|
||||
|
||||
@@ -5,6 +5,7 @@ package store
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
@@ -35,6 +36,14 @@ CREATE TABLE IF NOT EXISTS rooms (
|
||||
);
|
||||
`
|
||||
|
||||
// migrations run after the base schema. ALTER TABLE ADD COLUMN fails with
|
||||
// "duplicate column name" on subsequent opens — we swallow that error.
|
||||
var migrations = []string{
|
||||
// EXT-007: canonical message ID for history dedup (NULL for pre-feature messages).
|
||||
`ALTER TABLE messages ADD COLUMN msg_id TEXT`,
|
||||
`CREATE UNIQUE INDEX IF NOT EXISTS idx_messages_msg_id ON messages (msg_id) WHERE msg_id IS NOT NULL`,
|
||||
}
|
||||
|
||||
// Store is a local SQLite-backed message and peer store.
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
@@ -51,6 +60,12 @@ func Open(path string) (*Store, error) {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("migrate db: %w", err)
|
||||
}
|
||||
for _, m := range migrations {
|
||||
if _, err := db.Exec(m); err != nil && !strings.Contains(err.Error(), "duplicate column") {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("migration %q: %w", m, err)
|
||||
}
|
||||
}
|
||||
return &Store{db: db}, nil
|
||||
}
|
||||
|
||||
@@ -64,9 +79,9 @@ func (s *Store) Close() error {
|
||||
func (s *Store) SaveMessage(msg *proto.ChatMessage) error {
|
||||
sentAt := time.UnixMilli(msg.Ts).UTC()
|
||||
_, err := s.db.Exec(
|
||||
`INSERT OR IGNORE INTO messages (mid, room, from_peer, body, sent_at)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
msg.Mid, msg.Room, string(msg.From), msg.Text, sentAt,
|
||||
`INSERT OR IGNORE INTO messages (mid, msg_id, room, from_peer, body, sent_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
msg.Mid, nullableString(msg.MsgID), msg.Room, string(msg.From), msg.Text, sentAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -91,14 +106,39 @@ func (s *Store) PeerAlias(peerID proto.PeerID) string {
|
||||
|
||||
// RecentMessages returns up to limit messages for a room, oldest first.
|
||||
func (s *Store) RecentMessages(room string, limit int) ([]proto.ChatMessage, error) {
|
||||
rows, err := s.db.Query(
|
||||
`SELECT mid, from_peer, body, sent_at
|
||||
FROM messages
|
||||
return s.queryMessages(
|
||||
`SELECT mid, from_peer, room, body, sent_at FROM messages
|
||||
WHERE room = ?
|
||||
ORDER BY sent_at DESC
|
||||
LIMIT ?`,
|
||||
ORDER BY sent_at DESC LIMIT ?`,
|
||||
room, limit,
|
||||
)
|
||||
}
|
||||
|
||||
// RecentMessagesSince returns up to limit messages for a room with ts > sinceMs, oldest first.
|
||||
// sinceMs == 0 returns the most recent messages regardless of timestamp.
|
||||
func (s *Store) RecentMessagesSince(room string, sinceMs int64, limit int) ([]proto.ChatMessage, error) {
|
||||
if limit <= 0 || limit > 500 {
|
||||
limit = 500
|
||||
}
|
||||
if sinceMs == 0 {
|
||||
return s.queryMessages(
|
||||
`SELECT mid, from_peer, room, body, sent_at FROM messages
|
||||
WHERE room = ?
|
||||
ORDER BY sent_at DESC LIMIT ?`,
|
||||
room, limit,
|
||||
)
|
||||
}
|
||||
since := time.UnixMilli(sinceMs).UTC()
|
||||
return s.queryMessages(
|
||||
`SELECT mid, from_peer, room, body, sent_at FROM messages
|
||||
WHERE room = ? AND sent_at > ?
|
||||
ORDER BY sent_at DESC LIMIT ?`,
|
||||
room, since, limit,
|
||||
)
|
||||
}
|
||||
|
||||
func (s *Store) queryMessages(q string, args ...any) ([]proto.ChatMessage, error) {
|
||||
rows, err := s.db.Query(q, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -109,11 +149,10 @@ func (s *Store) RecentMessages(room string, limit int) ([]proto.ChatMessage, err
|
||||
var m proto.ChatMessage
|
||||
var from string
|
||||
var sentAt time.Time
|
||||
if err := rows.Scan(&m.Mid, &from, &m.Text, &sentAt); err != nil {
|
||||
if err := rows.Scan(&m.Mid, &from, &m.Room, &m.Text, &sentAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m.From = proto.PeerID(from)
|
||||
m.Room = room
|
||||
m.Ts = sentAt.UnixMilli()
|
||||
msgs = append(msgs, m)
|
||||
}
|
||||
@@ -168,3 +207,10 @@ func (s *Store) KnownPeers() (map[proto.PeerID]string, error) {
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func nullableString(s string) any {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -33,6 +33,10 @@ input:focus { border-color: var(--accent); }
|
||||
.onboarding-section { width: 100%; border-top: 1px solid var(--border); padding-top: 12px; }
|
||||
.join-form { display: flex; flex-direction: column; gap: 8px; width: 100%; }
|
||||
.join-label { font-size: 11px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--muted); }
|
||||
.saved-networks { display: flex; flex-direction: column; gap: 6px; width: 100%; }
|
||||
.saved-network-chips { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.network-chip { background: var(--surface); border: 1px solid var(--border); color: var(--text); border-radius: 20px; padding: 4px 14px; font-size: 13px; }
|
||||
.network-chip:hover { border-color: var(--accent); color: var(--accent); background: var(--surface); }
|
||||
button.primary { background: var(--accent); width: 100%; padding: 8px; font-size: 14px; }
|
||||
.toggle-link { background: none; color: var(--muted); font-size: 12px; padding: 4px 0; text-align: left; }
|
||||
.toggle-link:hover { color: var(--text); }
|
||||
@@ -88,7 +92,7 @@ details summary { color: var(--muted); font-size: 12px; cursor: pointer; }
|
||||
.messages { flex: 1; overflow-y: auto; padding: 8px 0; display: flex; flex-direction: column; }
|
||||
.message { display: flex; align-items: baseline; gap: 0; padding: 2px 16px; line-height: 1.5; }
|
||||
.message:hover { background: rgba(255,255,255,0.02); }
|
||||
.message-ts { color: var(--muted); font-size: 11px; white-space: nowrap; flex-shrink: 0; width: 52px; }
|
||||
.message-ts { color: var(--muted); font-size: 11px; white-space: nowrap; flex-shrink: 0; width: 72px; }
|
||||
.message-alias { font-weight: 600; font-size: 13px; text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex-shrink: 0; width: 90px; padding-right: 10px; }
|
||||
.message.mine .message-alias { color: var(--accent); }
|
||||
.message-text { word-break: break-word; font-size: 14px; color: var(--text); }
|
||||
@@ -158,3 +162,5 @@ details summary { color: var(--muted); font-size: 12px; cursor: pointer; }
|
||||
.file-entry-dir { cursor: pointer; }
|
||||
.file-entry-dir:hover { background: rgba(255,255,255,0.04); }
|
||||
.file-entry-icon { font-size: 12px; flex-shrink: 0; }
|
||||
.history-divider { display: flex; align-items: center; gap: 8px; margin: 10px 0 6px; color: var(--muted); font-size: 11px; }
|
||||
.history-divider::before, .history-divider::after { content: ''; flex: 1; height: 1px; background: var(--border); }
|
||||
|
||||
@@ -1,11 +1,34 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useWaste } from '../store'
|
||||
|
||||
const today = new Date()
|
||||
today.setHours(0, 0, 0, 0)
|
||||
const todayMs = today.getTime()
|
||||
|
||||
function formatTs(ts: number): string {
|
||||
const d = new Date(ts)
|
||||
const time = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })
|
||||
if (ts >= todayMs) return time
|
||||
return d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' + time
|
||||
}
|
||||
|
||||
export function MessagePane() {
|
||||
const { messages, activeRoom, activeNetworkId, localPeer, connectedPeers, send } = useWaste()
|
||||
const { messages, historyCutoff, activeRoom, activeNetworkId, localPeer, connectedPeers, knownPeers, send } = useWaste()
|
||||
const [draft, setDraft] = useState('')
|
||||
const bottomRef = useRef<HTMLDivElement>(null)
|
||||
const roomMessages = messages[activeRoom] ?? []
|
||||
const msgKey = activeNetworkId ? `${activeNetworkId}:${activeRoom}` : activeRoom
|
||||
const roomMessages = messages[msgKey] ?? []
|
||||
const cutoff = historyCutoff[msgKey] ?? 0
|
||||
|
||||
// Find the index of the first live message (ts > cutoff).
|
||||
// The divider appears just before this index, or at the top if all are history.
|
||||
const firstLiveIdx = cutoff > 0
|
||||
? roomMessages.findIndex(m => m.ts > cutoff)
|
||||
: -1
|
||||
// If all messages are history (no live yet), put divider at the start.
|
||||
const dividerIdx = cutoff > 0
|
||||
? (firstLiveIdx === -1 ? 0 : firstLiveIdx)
|
||||
: -1
|
||||
|
||||
useEffect(() => {
|
||||
bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
|
||||
@@ -30,7 +53,9 @@ export function MessagePane() {
|
||||
|
||||
function aliasFor(fromId: string) {
|
||||
if (fromId === localPeer?.id) return localPeer.alias
|
||||
return connectedPeers.find(p => p.id === fromId)?.alias ?? fromId.slice(0, 8)
|
||||
return connectedPeers.find(p => p.id === fromId)?.alias
|
||||
?? knownPeers[fromId]
|
||||
?? fromId.slice(0, 8)
|
||||
}
|
||||
|
||||
const roomLabel = activeRoom.startsWith('dm:')
|
||||
@@ -42,15 +67,23 @@ export function MessagePane() {
|
||||
<div className="message-pane-header">{roomLabel}</div>
|
||||
|
||||
<div className="messages">
|
||||
{dividerIdx === 0 && (
|
||||
<div className="history-divider"><span>earlier messages</span></div>
|
||||
)}
|
||||
{roomMessages.map((msg, i) => {
|
||||
const mine = msg.from === localPeer?.id
|
||||
const alias = aliasFor(msg.from)
|
||||
const time = new Date(msg.ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })
|
||||
const alias = aliasFor(String(msg.from))
|
||||
const ts = formatTs(msg.ts)
|
||||
return (
|
||||
<div key={msg.mid ?? i} className={`message ${mine ? 'mine' : ''}`}>
|
||||
<span className="message-ts">{time}</span>
|
||||
<span className="message-alias">{alias}</span>
|
||||
<span className="message-text">{msg.text}</span>
|
||||
<div key={msg.mid ?? i}>
|
||||
{i === dividerIdx && dividerIdx > 0 && (
|
||||
<div className="history-divider"><span>earlier messages</span></div>
|
||||
)}
|
||||
<div className={`message ${mine ? 'mine' : ''}`}>
|
||||
<span className="message-ts">{ts}</span>
|
||||
<span className="message-alias">{alias}</span>
|
||||
<span className="message-text">{msg.text}</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
@@ -32,16 +32,25 @@ export function Sidebar() {
|
||||
networks, activeNetworkId, activeRoom,
|
||||
connectedPeers, peerStatus,
|
||||
setActiveRoom, setActiveNetwork, messages, browseFiles, sendFileTo, adapterMode,
|
||||
customRooms, createRoom, logout,
|
||||
customRooms, createRoom, logout, send,
|
||||
} = useWaste()
|
||||
const [addingRoom, setAddingRoom] = useState(false)
|
||||
const [newRoomName, setNewRoomName] = useState('')
|
||||
const [addingNetwork, setAddingNetwork] = useState(false)
|
||||
const [newNetName, setNewNetName] = useState('')
|
||||
const [newNetAnchor, setNewNetAnchor] = useState('')
|
||||
|
||||
const netCustomRooms = activeNetworkId ? (customRooms[activeNetworkId] ?? []) : []
|
||||
const rooms = ['general', ...netCustomRooms]
|
||||
Object.keys(messages).forEach(r => {
|
||||
if (r.startsWith('dm:') && !rooms.includes(r)) rooms.push(r)
|
||||
})
|
||||
if (activeNetworkId) {
|
||||
const prefix = `${activeNetworkId}:dm:`
|
||||
Object.keys(messages).forEach(k => {
|
||||
if (k.startsWith(prefix)) {
|
||||
const r = k.slice(activeNetworkId.length + 1)
|
||||
if (!rooms.includes(r)) rooms.push(r)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function submitNewRoom(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
@@ -50,6 +59,25 @@ export function Sidebar() {
|
||||
setAddingRoom(false)
|
||||
}
|
||||
|
||||
function submitNewNetwork(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
const name = newNetName.trim()
|
||||
if (!name) return
|
||||
if (adapterMode === 'browser') {
|
||||
// Persist to saved networks list in localStorage.
|
||||
const anchor = newNetAnchor.trim() || localStorage.getItem('waste_anchor_url') || ''
|
||||
const saved: Array<{name: string; anchor: string}> = JSON.parse(localStorage.getItem('waste_saved_networks') ?? '[]')
|
||||
if (!saved.some(n => n.name === name && n.anchor === anchor)) {
|
||||
saved.push({ name, anchor })
|
||||
localStorage.setItem('waste_saved_networks', JSON.stringify(saved))
|
||||
}
|
||||
}
|
||||
send({ type: 'join_network', network_name: name })
|
||||
setNewNetName('')
|
||||
setNewNetAnchor('')
|
||||
setAddingNetwork(false)
|
||||
}
|
||||
|
||||
const displayAlias = localPeer?.alias ?? masterAlias ?? ''
|
||||
const displayId = localPeer?.id ?? masterId ?? ''
|
||||
const card = displayId ? makeYawCard(displayId, displayAlias) : null
|
||||
@@ -95,9 +123,12 @@ export function Sidebar() {
|
||||
<div className="sidebar-section">
|
||||
<div className="sidebar-label-row">
|
||||
<span className="sidebar-label">Networks</span>
|
||||
{activeNetworkId && (
|
||||
<button className="sidebar-add" onClick={copyHangLink} title="Copy hang link (pre-fills join form, no invite required)">🔗</button>
|
||||
)}
|
||||
<span style={{ display: 'flex', gap: 2 }}>
|
||||
{activeNetworkId && (
|
||||
<button className="sidebar-add" onClick={copyHangLink} title="Copy hang link">🔗</button>
|
||||
)}
|
||||
<button className="sidebar-add" onClick={() => setAddingNetwork(v => !v)} title="Join network">+</button>
|
||||
</span>
|
||||
</div>
|
||||
{networks.map(n => (
|
||||
<button
|
||||
@@ -108,6 +139,29 @@ export function Sidebar() {
|
||||
{n.network_name}
|
||||
</button>
|
||||
))}
|
||||
{addingNetwork && (
|
||||
<form className="sidebar-new-room" onSubmit={submitNewNetwork}>
|
||||
<input
|
||||
autoFocus
|
||||
value={newNetName}
|
||||
onChange={e => setNewNetName(e.target.value)}
|
||||
placeholder="network name"
|
||||
onKeyDown={e => e.key === 'Escape' && (setAddingNetwork(false), setNewNetName(''))}
|
||||
/>
|
||||
{adapterMode === 'browser' && (
|
||||
<input
|
||||
value={newNetAnchor}
|
||||
onChange={e => setNewNetAnchor(e.target.value)}
|
||||
placeholder="anchor URL (blank = current)"
|
||||
className="mono"
|
||||
style={{ fontSize: '0.75rem', marginTop: 4 }}
|
||||
/>
|
||||
)}
|
||||
<button type="submit" disabled={!newNetName.trim()} style={{ marginTop: 4, width: '100%', fontSize: '12px', padding: '3px 8px' }}>
|
||||
Join
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="sidebar-section">
|
||||
|
||||
@@ -7,12 +7,13 @@ function fmt(bytes: number): string {
|
||||
}
|
||||
|
||||
export function Transfers() {
|
||||
const { pendingOffers, fileProgress, acceptOffer, rejectOffer, cancelTransfer, connectedPeers } = useWaste()
|
||||
const { pendingOffers, fileProgress, resumableFiles, acceptOffer, rejectOffer, cancelTransfer, connectedPeers } = useWaste()
|
||||
|
||||
const hasPending = Object.keys(pendingOffers).length > 0
|
||||
const hasActive = Object.keys(fileProgress).length > 0
|
||||
const hasResumable = Object.keys(resumableFiles).length > 0
|
||||
|
||||
if (!hasPending && !hasActive) return null
|
||||
if (!hasPending && !hasActive && !hasResumable) return null
|
||||
|
||||
function alias(peerId: string) {
|
||||
return connectedPeers.find(p => p.id === peerId)?.alias ?? peerId.slice(0, 8)
|
||||
@@ -22,6 +23,24 @@ export function Transfers() {
|
||||
<div className="sidebar-section">
|
||||
<span className="sidebar-label">Transfers</span>
|
||||
|
||||
{hasResumable && (
|
||||
<>
|
||||
<span className="sidebar-label" style={{ fontSize: 10, opacity: 0.6 }}>resumable</span>
|
||||
{Object.entries(resumableFiles).map(([sha256, f]) => {
|
||||
const pct = f.size > 0 ? Math.round((f.offset / f.size) * 100) : 0
|
||||
return (
|
||||
<div key={sha256} className="transfer-row">
|
||||
<span className="transfer-name" title={f.name}>{f.name}</span>
|
||||
<span className="transfer-meta">{fmt(f.offset)} / {fmt(f.size)} · {alias(f.from)} · will resume on reconnect</span>
|
||||
<div className="transfer-progress">
|
||||
<div className="transfer-progress-bar" style={{ width: `${pct}%`, opacity: 0.5 }} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
|
||||
{Object.entries(pendingOffers).map(([xid, offer]) => (
|
||||
<div key={xid} className="transfer-row">
|
||||
<span className="transfer-name" title={offer.name}>{offer.name}</span>
|
||||
|
||||
@@ -72,8 +72,15 @@ export function Onboarding({ status }: Props) {
|
||||
if (adapterMode !== 'browser' || status !== 'connected') return
|
||||
const { network: n, netHash: nh } = parseInviteParams()
|
||||
if (n || nh) return // explicit invite — don't auto-join, show form
|
||||
const savedNetwork = localStorage.getItem('waste_last_network')
|
||||
if (savedNetwork) doJoin(savedNetwork, '')
|
||||
// Rejoin all saved networks.
|
||||
const saved: Array<{name: string; anchor: string}> = JSON.parse(localStorage.getItem('waste_saved_networks') ?? '[]')
|
||||
if (saved.length > 0) {
|
||||
saved.forEach(s => doJoin(s.name, ''))
|
||||
} else {
|
||||
// Legacy single-network fallback.
|
||||
const savedNetwork = localStorage.getItem('waste_last_network')
|
||||
if (savedNetwork) doJoin(savedNetwork, '')
|
||||
}
|
||||
}, [adapterMode, status]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
function joinNetwork(e: React.FormEvent) {
|
||||
@@ -87,8 +94,16 @@ export function Onboarding({ status }: Props) {
|
||||
if (adapterMode === 'browser') {
|
||||
localStorage.setItem('waste_anchor_url', anchorUrl)
|
||||
if (nick.trim()) localStorage.setItem('waste_nick', nick.trim())
|
||||
if (name) localStorage.setItem('waste_last_network', name)
|
||||
else localStorage.removeItem('waste_last_network')
|
||||
if (name) {
|
||||
// Persist to saved networks list.
|
||||
const saved: Array<{name: string; anchor: string}> = JSON.parse(localStorage.getItem('waste_saved_networks') ?? '[]')
|
||||
if (!saved.some(n => n.name === name)) {
|
||||
saved.push({ name, anchor: anchorUrl })
|
||||
localStorage.setItem('waste_saved_networks', JSON.stringify(saved))
|
||||
}
|
||||
// Keep legacy key for backward compat.
|
||||
localStorage.setItem('waste_last_network', name)
|
||||
}
|
||||
}
|
||||
|
||||
if (hash.length === 64 && !name) {
|
||||
@@ -121,6 +136,7 @@ export function Onboarding({ status }: Props) {
|
||||
}
|
||||
|
||||
const shortId = masterId ? masterId.slice(0, 16).replace(/(.{4})/g, '$1 ').trim() : null
|
||||
const savedNetworks: Array<{name: string; anchor: string}> = JSON.parse(localStorage.getItem('waste_saved_networks') ?? '[]')
|
||||
|
||||
// ── disconnected / connecting ────────────────────────────────────────────────
|
||||
if (status !== 'connected') {
|
||||
@@ -159,8 +175,21 @@ export function Onboarding({ status }: Props) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{adapterMode === 'browser' && savedNetworks.length > 0 && (
|
||||
<div className="saved-networks">
|
||||
<span className="join-label">Saved networks</span>
|
||||
<div className="saved-network-chips">
|
||||
{savedNetworks.map(n => (
|
||||
<button key={n.name} className="network-chip" type="button" onClick={() => doJoin(n.name, '')}>
|
||||
{n.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={joinNetwork} className="join-form">
|
||||
<label className="join-label">Join a network</label>
|
||||
<label className="join-label">{savedNetworks.length > 0 ? 'Join another network' : 'Join a network'}</label>
|
||||
|
||||
{adapterMode === 'browser' && (
|
||||
<input
|
||||
|
||||
@@ -29,9 +29,12 @@ interface WasteState {
|
||||
|
||||
// peers
|
||||
connectedPeers: PeerInfo[]
|
||||
knownPeers: Record<string, string> // id → alias for historical peers
|
||||
|
||||
// chat — keyed by room
|
||||
messages: Record<string, ChatMessage[]>
|
||||
// rooms for which we have received history: room → ts of last history message
|
||||
historyCutoff: Record<string, number>
|
||||
activeRoom: string
|
||||
// user-created rooms, keyed by networkId
|
||||
customRooms: Record<string, string[]>
|
||||
@@ -53,6 +56,8 @@ interface WasteState {
|
||||
pendingOffers: Record<string, { peerId: string; name: string; size: number }>
|
||||
// active in-progress transfers: xid → progress
|
||||
fileProgress: Record<string, { peerId: string; name: string; received: number; total: number }>
|
||||
// partial downloads found on daemon startup: sha256 → info
|
||||
resumableFiles: Record<string, { name: string; from: string; size: number; offset: number }>
|
||||
|
||||
// actions
|
||||
connect: (url: string) => void
|
||||
@@ -83,7 +88,9 @@ export const useWaste = create<WasteState>((set, get) => ({
|
||||
networks: [],
|
||||
activeNetworkId: null,
|
||||
connectedPeers: [],
|
||||
knownPeers: {},
|
||||
messages: {},
|
||||
historyCutoff: {},
|
||||
activeRoom: 'general',
|
||||
customRooms: {},
|
||||
fileLists: {},
|
||||
@@ -93,6 +100,7 @@ export const useWaste = create<WasteState>((set, get) => ({
|
||||
sharedFilesByNetwork: {},
|
||||
pendingOffers: {},
|
||||
fileProgress: {},
|
||||
resumableFiles: {},
|
||||
|
||||
connect(url: string) {
|
||||
const adapter = new DaemonAdapter(url)
|
||||
@@ -209,6 +217,8 @@ export const useWaste = create<WasteState>((set, get) => ({
|
||||
switch (msg.type) {
|
||||
case 'state_snapshot': {
|
||||
const networks = msg.networks ?? []
|
||||
const knownPeers: Record<string, string> = {}
|
||||
for (const p of msg.known_peers ?? []) knownPeers[p.id] = p.alias
|
||||
set({
|
||||
masterAlias: msg.master_alias ?? null,
|
||||
masterId: msg.master_id ?? null,
|
||||
@@ -216,6 +226,7 @@ export const useWaste = create<WasteState>((set, get) => ({
|
||||
networks,
|
||||
connectedPeers: msg.connected_peers ?? [],
|
||||
activeNetworkId: networks[0]?.network_id ?? null,
|
||||
knownPeers,
|
||||
})
|
||||
break
|
||||
}
|
||||
@@ -272,14 +283,14 @@ export const useWaste = create<WasteState>((set, get) => ({
|
||||
case 'message_received': {
|
||||
if (msg.message) {
|
||||
const m = msg.message
|
||||
const room = m.room
|
||||
const key = `${msg.network_id}:${m.room}`
|
||||
const fromId = String(m.from)
|
||||
set(s => {
|
||||
const existing = s.messages[room] ?? []
|
||||
const existing = s.messages[key] ?? []
|
||||
if (m.mid && existing.some(e => e.mid === m.mid)) return s
|
||||
const prev = s.peerStatus[fromId] ?? {}
|
||||
return {
|
||||
messages: { ...s.messages, [room]: [...existing, m] },
|
||||
messages: { ...s.messages, [key]: [...existing, m] },
|
||||
peerStatus: { ...s.peerStatus, [fromId]: { ...prev, lastSeen: m.ts } },
|
||||
}
|
||||
})
|
||||
@@ -341,10 +352,13 @@ export const useWaste = create<WasteState>((set, get) => ({
|
||||
break
|
||||
}
|
||||
case 'file_complete': {
|
||||
if (msg.path && msg.offer?.name) {
|
||||
// clear progress entry
|
||||
const xid = msg.offer.xid
|
||||
// Always clear progress — transfer_id is the xid in daemon mode; offer.xid in browser mode.
|
||||
const xid = msg.transfer_id ?? msg.offer?.xid
|
||||
if (xid) {
|
||||
set(s => { const fp = { ...s.fileProgress }; delete fp[xid]; return { fileProgress: fp } })
|
||||
}
|
||||
// Browser mode: trigger download via anchor click.
|
||||
if (msg.path && msg.offer?.name) {
|
||||
const a = document.createElement('a')
|
||||
a.href = msg.path
|
||||
a.download = msg.offer.name
|
||||
@@ -352,6 +366,33 @@ export const useWaste = create<WasteState>((set, get) => ({
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'resumable_transfers': {
|
||||
const files = (msg.resumable_files ?? []) as Array<{ name: string; sha256: string; from: string; size: number; offset: number }>
|
||||
if (files.length === 0) break
|
||||
const byHash: Record<string, { name: string; from: string; size: number; offset: number }> = {}
|
||||
for (const f of files) byHash[f.sha256] = { name: f.name, from: f.from, size: f.size, offset: f.offset }
|
||||
set(s => ({ resumableFiles: { ...s.resumableFiles, ...byHash } }))
|
||||
break
|
||||
}
|
||||
case 'history_loaded': {
|
||||
const room = msg.room
|
||||
const incoming = (msg.messages ?? []) as ChatMessage[]
|
||||
if (!room || incoming.length === 0) break
|
||||
const key = `${msg.network_id}:${room}`
|
||||
set(s => {
|
||||
const existing = s.messages[key] ?? []
|
||||
const existingMids = new Set(existing.map(m => m.mid).filter(Boolean))
|
||||
const fresh = incoming.filter(m => !m.mid || !existingMids.has(m.mid))
|
||||
if (fresh.length === 0) return s
|
||||
const merged = [...fresh, ...existing].sort((a, b) => a.ts - b.ts)
|
||||
const cutoff = fresh[fresh.length - 1]?.ts ?? 0
|
||||
return {
|
||||
messages: { ...s.messages, [key]: merged },
|
||||
historyCutoff: { ...s.historyCutoff, [key]: cutoff },
|
||||
}
|
||||
})
|
||||
break
|
||||
}
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -82,6 +82,10 @@ export type IpcMsgType =
|
||||
| 'shares_list'
|
||||
| 'peer_status'
|
||||
| 'error'
|
||||
| 'history_loaded'
|
||||
| 'room_created'
|
||||
| 'create_room'
|
||||
| 'resumable_transfers'
|
||||
|
||||
export interface IpcMessage {
|
||||
type: IpcMsgType
|
||||
@@ -113,6 +117,7 @@ export interface IpcMessage {
|
||||
master_id?: string
|
||||
local_peer?: PeerInfo
|
||||
connected_peers?: PeerInfo[]
|
||||
known_peers?: PeerInfo[]
|
||||
rooms?: string[]
|
||||
networks?: NetworkInfo[]
|
||||
error_message?: string
|
||||
@@ -124,4 +129,8 @@ export interface IpcMessage {
|
||||
conn_state?: PeerConnState
|
||||
candidate_type?: CandidateType
|
||||
remote_address?: string
|
||||
// history_loaded
|
||||
messages?: ChatMessage[]
|
||||
// resumable_transfers
|
||||
resumable_files?: Array<{ name: string; sha256: string; from: string; size: number; offset: number }>
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user