Compare commits
14 Commits
v0.1.1
...
851cfdc7e9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
851cfdc7e9 | ||
|
|
4a7a95fe9d | ||
|
|
32a6f46481 | ||
|
|
1d9c9d1524 | ||
|
|
f5fb0862ff | ||
|
|
dab5387cbd | ||
|
|
1d9827beb0 | ||
|
|
fcbd84f873 | ||
|
|
cef9374416 | ||
|
|
9ad3c96d43 | ||
|
|
48400440dd | ||
|
|
0e812a2479 | ||
|
|
f319721e01 | ||
|
|
9de625d617 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -21,6 +21,7 @@ build-daemon.sh
|
|||||||
deploy-web.sh
|
deploy-web.sh
|
||||||
deploy-daemon.sh
|
deploy-daemon.sh
|
||||||
serve-web.sh
|
serve-web.sh
|
||||||
|
push.sh
|
||||||
web/public/config.js
|
web/public/config.js
|
||||||
cmd/app/frontend/dist/*
|
cmd/app/frontend/dist/*
|
||||||
!cmd/app/frontend/dist/.gitkeep
|
!cmd/app/frontend/dist/.gitkeep
|
||||||
|
|||||||
21
FUTURE.md
21
FUTURE.md
@@ -91,10 +91,10 @@ DM rooms (`dm:<peerId>`) appear automatically in both interfaces when messages a
|
|||||||
- Live progress bar per active transfer
|
- Live progress bar per active transfer
|
||||||
- Push (📎) sends directly to a peer without them needing to share a folder
|
- 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
|
### 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,23 @@ 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 | 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 | 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 | 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 |
|
||||||
|
| 🔜 planned | Push notifications (PWA Web Push + service worker) |
|
||||||
|
| 🔜 planned | Message reactions (emoji, full-stack gossip) |
|
||||||
|
| 🔜 planned | Link rendering + image preview in messages |
|
||||||
|
|
||||||
|
### Push Notifications (planned)
|
||||||
|
The web UI is already a PWA (installable, has manifest). The missing half is a service worker + Web Push subscription:
|
||||||
|
|
||||||
|
1. **Service worker** — intercepts `push` events and shows OS notifications via `showNotification()`.
|
||||||
|
2. **VAPID key pair** — generated once by the daemon (`-vapid-key` flag); the public key is served to the browser so it can subscribe.
|
||||||
|
3. **Subscription persistence** — the browser's `PushSubscription` JSON is sent to the daemon over IPC (`register_push` command). The daemon stores it per-network-per-peer.
|
||||||
|
4. **Daemon relay** — when a `message_received` event fires with no active IPC WebSocket connection, the daemon POSTs a Web Push notification to the stored subscription endpoint.
|
||||||
|
|
||||||
|
This keeps the architecture clean: the daemon already runs in the background; it becomes the notification relay. No third-party push server is required for self-hosted setups (coturn already in use for TURN; a lightweight Web Push POST is similar).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,154 +0,0 @@
|
|||||||
# Proposal: P2P Message History Gossip
|
|
||||||
|
|
||||||
## Goals
|
|
||||||
|
|
||||||
- New peers joining a network can retrieve recent message history from existing peers
|
|
||||||
- No central storage — history lives only in peer daemons (SQLite)
|
|
||||||
- No new trust requirements — history is shared only over already-established encrypted DataChannels
|
|
||||||
- No duplicates in the local store or UI
|
|
||||||
- No conflicts — history gossip is append-only and idempotent
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Privacy Model
|
|
||||||
|
|
||||||
History is shared **peer-to-peer over the encrypted mesh**, never via the anchor. The anchor remains dumb — it sees only signaling blobs. A peer only receives history from peers they have successfully completed a YAW/2 handshake with, so the same trust boundary as live messages applies.
|
|
||||||
|
|
||||||
A peer can choose not to share history by ignoring `history_request` messages — the protocol is advisory, not mandatory.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Wire Protocol
|
|
||||||
|
|
||||||
Two new YAW/2 extension messages (added to EXTENSIONS.md):
|
|
||||||
|
|
||||||
### `history_request`
|
|
||||||
|
|
||||||
Sent by a newly-connected peer to one or more existing peers shortly after the handshake completes.
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"type": "history_request",
|
|
||||||
"room": "general",
|
|
||||||
"since": "2026-01-01T00:00:00Z",
|
|
||||||
"limit": 200
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
| Field | Type | Description |
|
|
||||||
|---------|-----------------|----------------------------------------------------------|
|
|
||||||
| `room` | string | Room name to request history for. One request per room. |
|
|
||||||
| `since` | ISO 8601 or "" | Only return messages newer than this timestamp. Empty = return up to `limit` most recent. |
|
|
||||||
| `limit` | int (max 500) | Maximum number of messages to return. Responder may return fewer. |
|
|
||||||
|
|
||||||
### `history_chunk`
|
|
||||||
|
|
||||||
Response from an existing peer. May be sent in multiple chunks if `limit` is large.
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"type": "history_chunk",
|
|
||||||
"room": "general",
|
|
||||||
"messages": [
|
|
||||||
{
|
|
||||||
"id": "sha256:<hex>",
|
|
||||||
"from": "<peer-alias>",
|
|
||||||
"from_id": "<hex-pubkey>",
|
|
||||||
"body": "hello",
|
|
||||||
"ts": "2026-06-01T12:00:00Z",
|
|
||||||
"room": "general"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"done": true
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
| Field | Type | Description |
|
|
||||||
|------------|---------|----------------------------------------------------------|
|
|
||||||
| `messages` | array | Ordered oldest-first. |
|
|
||||||
| `done` | bool | `true` on the final chunk. Receiver may display after this. |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Message Identity and Deduplication
|
|
||||||
|
|
||||||
Each message has a **content-addressed ID**:
|
|
||||||
|
|
||||||
```
|
|
||||||
id = "sha256:" + hex(SHA-256(from_id || room || ts || body))
|
|
||||||
```
|
|
||||||
|
|
||||||
- Computed by the original sender and included in every live message going forward
|
|
||||||
- The SQLite `messages` table gains an `id TEXT UNIQUE` column
|
|
||||||
- On insert, use `INSERT OR IGNORE` — receiving the same message twice (live or via gossip) is a no-op
|
|
||||||
- The UI sorts by `ts`, so late-arriving history slots in correctly without reordering visible messages
|
|
||||||
|
|
||||||
Legacy messages (before this feature) have no `id`. They are assigned a local-only ID on migration and are never gossipped (they have no canonical ID the receiver could deduplicate against).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Daemon-Side Implementation
|
|
||||||
|
|
||||||
### SQLite schema change
|
|
||||||
|
|
||||||
```sql
|
|
||||||
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;
|
|
||||||
```
|
|
||||||
|
|
||||||
### Handling `history_request`
|
|
||||||
|
|
||||||
```
|
|
||||||
peer sends history_request{room, since, limit}
|
|
||||||
→ query SQLite: SELECT * FROM messages WHERE room=? AND ts>? ORDER BY ts ASC LIMIT ?
|
|
||||||
→ send history_chunk{room, messages, done:true}
|
|
||||||
```
|
|
||||||
|
|
||||||
Responder enforces:
|
|
||||||
- `limit` capped at 500
|
|
||||||
- Only messages the responder itself received or sent (no re-gossipping of gossipped history to avoid amplification)
|
|
||||||
- Rate limit: one `history_request` per peer per room per 60 seconds
|
|
||||||
|
|
||||||
### Handling `history_chunk`
|
|
||||||
|
|
||||||
```
|
|
||||||
for each message in chunk:
|
|
||||||
INSERT OR IGNORE INTO messages (msg_id, room, from_alias, from_id, body, ts) VALUES (...)
|
|
||||||
emit IPC event: history_loaded{room, count}
|
|
||||||
```
|
|
||||||
|
|
||||||
### When to request
|
|
||||||
|
|
||||||
- After handshake completes with the **first** peer in a network (only ask one peer — avoids fan-out)
|
|
||||||
- Request rooms the local peer knows about (from its own SQLite `rooms` table)
|
|
||||||
- If no rooms known yet: request `"general"` only; discover others from incoming live messages
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## IPC / UI Integration
|
|
||||||
|
|
||||||
New IPC event emitted after history is loaded:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{ "type": "history_loaded", "network_id": "...", "room": "general", "count": 47 }
|
|
||||||
```
|
|
||||||
|
|
||||||
The web UI and TUI insert a visual separator above the first gossipped message:
|
|
||||||
|
|
||||||
```
|
|
||||||
── 47 earlier messages ─────────────────────────────
|
|
||||||
[12:03] alice: hey
|
|
||||||
[12:04] bob: yo
|
|
||||||
── live ─────────────────────────────────────────────
|
|
||||||
[14:22] you joined
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## What This Does Not Do
|
|
||||||
|
|
||||||
- **No conflict resolution** — messages are immutable append-only records; there is nothing to conflict
|
|
||||||
- **No ordering guarantee beyond timestamp** — if two peers sent messages at the same millisecond, both are stored; the UI sorts by `ts` then `msg_id` for a stable tiebreak
|
|
||||||
- **No full sync** — gossip is bounded by `limit` and `since`; it is not a replication protocol
|
|
||||||
- **No anchor involvement** — the anchor never sees history
|
|
||||||
- **No history from peers who were offline** — if no peer with history is online when you join, you get nothing (acceptable given the trust model)
|
|
||||||
@@ -383,7 +383,7 @@ func (m model) refreshViewport() model {
|
|||||||
w := m.vpContentWidth()
|
w := m.vpContentWidth()
|
||||||
var sb strings.Builder
|
var sb strings.Builder
|
||||||
for _, e := range m.messages[room] {
|
for _, e := range m.messages[room] {
|
||||||
ts := styleMsgTime.Render(e.at.Format("15:04"))
|
ts := styleMsgTime.Render(formatMsgTime(e.at))
|
||||||
var from string
|
var from string
|
||||||
if e.fromMe {
|
if e.fromMe {
|
||||||
from = styleMsgMe.Render(e.from)
|
from = styleMsgMe.Render(e.from)
|
||||||
@@ -614,6 +614,17 @@ func filterIDs(ids []proto.PeerID, remove proto.PeerID) []proto.PeerID {
|
|||||||
return out
|
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 {
|
func min(a, b int) int {
|
||||||
if a < b {
|
if a < b {
|
||||||
return a
|
return a
|
||||||
|
|||||||
@@ -127,6 +127,8 @@ func handleClient(conn net.Conn, mgr *netmgr.Manager) {
|
|||||||
|
|
||||||
// Send initial state snapshot.
|
// Send initial state snapshot.
|
||||||
send(stateSnapshot(mgr))
|
send(stateSnapshot(mgr))
|
||||||
|
// Send stored history for each room so the UI is populated on connect.
|
||||||
|
sendStoredHistory(mgr, send)
|
||||||
|
|
||||||
scanner := bufio.NewScanner(conn)
|
scanner := bufio.NewScanner(conn)
|
||||||
for scanner.Scan() {
|
for scanner.Scan() {
|
||||||
@@ -242,6 +244,34 @@ func handleClient(conn net.Conn, mgr *netmgr.Manager) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case proto.CmdSendReaction:
|
||||||
|
n := mgr.Resolve(cmd.NetworkID)
|
||||||
|
if n == nil {
|
||||||
|
send(errMsg("send_reaction: not joined to any network"))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if cmd.ReactionMID == "" || cmd.ReactionEmoji == "" {
|
||||||
|
send(errMsg("send_reaction: reaction_mid and reaction_emoji are required"))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
wire, err := json.Marshal(proto.PeerMessage{
|
||||||
|
Type: proto.MsgReaction,
|
||||||
|
ReactionMID: cmd.ReactionMID,
|
||||||
|
ReactionEmoji: cmd.ReactionEmoji,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
n.Mesh.Broadcast(wire)
|
||||||
|
n.Mesh.SaveReaction(cmd.ReactionMID, cmd.ReactionEmoji, string(n.Identity.PeerID()))
|
||||||
|
n.Mesh.Emit(proto.IpcMessage{
|
||||||
|
Type: proto.EvtReaction,
|
||||||
|
NetworkID: n.ID,
|
||||||
|
PeerID: ptr(n.Identity.PeerID()),
|
||||||
|
ReactionMID: cmd.ReactionMID,
|
||||||
|
ReactionEmoji: cmd.ReactionEmoji,
|
||||||
|
})
|
||||||
|
|
||||||
case proto.CmdCreateRoom:
|
case proto.CmdCreateRoom:
|
||||||
n := mgr.Resolve(cmd.NetworkID)
|
n := mgr.Resolve(cmd.NetworkID)
|
||||||
if n == nil {
|
if n == nil {
|
||||||
@@ -457,11 +487,74 @@ func stateSnapshot(mgr *netmgr.Manager) proto.IpcMessage {
|
|||||||
msg.Rooms = append(msg.Rooms, r)
|
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
|
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,
|
||||||
|
})
|
||||||
|
// Send stored reactions for this room's messages.
|
||||||
|
rxns, err := n.Store.ReactionsForRoom(room)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for mid, byEmoji := range rxns {
|
||||||
|
for emoji, fromPeers := range byEmoji {
|
||||||
|
for _, fromPeer := range fromPeers {
|
||||||
|
pid := proto.PeerID(fromPeer)
|
||||||
|
send(proto.IpcMessage{
|
||||||
|
Type: proto.EvtReaction,
|
||||||
|
NetworkID: n.ID,
|
||||||
|
PeerID: &pid,
|
||||||
|
ReactionMID: mid,
|
||||||
|
ReactionEmoji: emoji,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func errMsg(s string) proto.IpcMessage {
|
func errMsg(s string) proto.IpcMessage {
|
||||||
return proto.IpcMessage{Type: proto.EvtError, ErrorMessage: s}
|
return proto.IpcMessage{Type: proto.EvtError, ErrorMessage: s}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -146,6 +146,17 @@ func (m *Mesh) AddPeer(conn *PeerConn) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SaveReaction persists a reaction if a store is configured.
|
||||||
|
// Duplicate (mid, emoji, fromPeer) triples are silently dropped.
|
||||||
|
func (m *Mesh) SaveReaction(mid, emoji, fromPeer string) {
|
||||||
|
if m.Store == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := m.Store.SaveReaction(mid, emoji, fromPeer); err != nil {
|
||||||
|
log.Printf("mesh: store reaction %s/%s: %v", mid, emoji, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// SaveMessage persists a chat message if a store is configured.
|
// SaveMessage persists a chat message if a store is configured.
|
||||||
// Duplicate mids are silently dropped.
|
// Duplicate mids are silently dropped.
|
||||||
func (m *Mesh) SaveMessage(msg *proto.ChatMessage) {
|
func (m *Mesh) SaveMessage(msg *proto.ChatMessage) {
|
||||||
|
|||||||
@@ -307,6 +307,18 @@ func dispatchPeerMessage(msg proto.PeerMessage, from proto.PeerID, m *Mesh) {
|
|||||||
case proto.MsgHistoryChunk:
|
case proto.MsgHistoryChunk:
|
||||||
go m.HandleHistoryChunk(msg.Room, msg.History)
|
go m.HandleHistoryChunk(msg.Room, msg.History)
|
||||||
|
|
||||||
|
case proto.MsgReaction:
|
||||||
|
if msg.ReactionMID == "" || msg.ReactionEmoji == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
m.SaveReaction(msg.ReactionMID, msg.ReactionEmoji, string(from))
|
||||||
|
m.emit(proto.IpcMessage{
|
||||||
|
Type: proto.EvtReaction,
|
||||||
|
PeerID: peerIDPtr(from),
|
||||||
|
ReactionMID: msg.ReactionMID,
|
||||||
|
ReactionEmoji: msg.ReactionEmoji,
|
||||||
|
})
|
||||||
|
|
||||||
case proto.MsgPing:
|
case proto.MsgPing:
|
||||||
log.Printf("mesh: ping from %s", from.Short())
|
log.Printf("mesh: ping from %s", from.Short())
|
||||||
case proto.MsgPong:
|
case proto.MsgPong:
|
||||||
|
|||||||
@@ -91,6 +91,47 @@ func writePartialMeta(path string, t *inboundTransfer) {
|
|||||||
os.WriteFile(path, data, 0o644) //nolint:errcheck
|
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
|
// OfferFile reads filename from ShareDir, computes its SHA-256, and sends a
|
||||||
// file-offer to peerID over the existing "yaw" DataChannel.
|
// file-offer to peerID over the existing "yaw" DataChannel.
|
||||||
func (m *Mesh) OfferFile(peerID proto.PeerID, filename string) error {
|
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{
|
mgr.emit(proto.IpcMessage{
|
||||||
Type: proto.EvtNetworkJoined,
|
Type: proto.EvtNetworkJoined,
|
||||||
NetworkID: netID,
|
NetworkID: netID,
|
||||||
@@ -249,6 +251,8 @@ func (mgr *Manager) JoinByHash(netHash64, shareDir string) (string, error) {
|
|||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
go m.ScanResumable()
|
||||||
|
|
||||||
mgr.emit(proto.IpcMessage{
|
mgr.emit(proto.IpcMessage{
|
||||||
Type: proto.EvtNetworkJoined,
|
Type: proto.EvtNetworkJoined,
|
||||||
NetworkID: netID,
|
NetworkID: netID,
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ const (
|
|||||||
MsgPong MsgType = "pong"
|
MsgPong MsgType = "pong"
|
||||||
MsgHistoryRequest MsgType = "history_request"
|
MsgHistoryRequest MsgType = "history_request"
|
||||||
MsgHistoryChunk MsgType = "history_chunk"
|
MsgHistoryChunk MsgType = "history_chunk"
|
||||||
|
MsgReaction MsgType = "reaction"
|
||||||
)
|
)
|
||||||
|
|
||||||
// PmMessage is a private message sent directly over a single peer link (§8 "pm").
|
// PmMessage is a private message sent directly over a single peer link (§8 "pm").
|
||||||
@@ -97,6 +98,19 @@ type PeerMessage struct {
|
|||||||
// history_chunk fields
|
// history_chunk fields
|
||||||
History []HistoryEntry `json:"history,omitempty"`
|
History []HistoryEntry `json:"history,omitempty"`
|
||||||
HistoryDone bool `json:"history_done,omitempty"`
|
HistoryDone bool `json:"history_done,omitempty"`
|
||||||
|
|
||||||
|
// reaction fields
|
||||||
|
ReactionMID string `json:"reaction_mid,omitempty"`
|
||||||
|
ReactionEmoji string `json:"reaction_emoji,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.
|
// HistoryEntry is one message in a history_chunk response.
|
||||||
@@ -271,6 +285,7 @@ const (
|
|||||||
CmdListShares IpcMsgType = "list_shares" // returns shares_list event
|
CmdListShares IpcMsgType = "list_shares" // returns shares_list event
|
||||||
CmdCreateRoom IpcMsgType = "create_room" // field: room (name)
|
CmdCreateRoom IpcMsgType = "create_room" // field: room (name)
|
||||||
CmdSetDownloadDir IpcMsgType = "set_download_dir" // set per-network download directory at runtime; fields: network_id, path
|
CmdSetDownloadDir IpcMsgType = "set_download_dir" // set per-network download directory at runtime; fields: network_id, path
|
||||||
|
CmdSendReaction IpcMsgType = "send_reaction" // fields: network_id, reaction_mid, reaction_emoji
|
||||||
|
|
||||||
// Events (daemon → UI)
|
// Events (daemon → UI)
|
||||||
EvtMessageReceived IpcMsgType = "message_received"
|
EvtMessageReceived IpcMsgType = "message_received"
|
||||||
@@ -292,6 +307,8 @@ const (
|
|||||||
EvtSharesList IpcMsgType = "shares_list"
|
EvtSharesList IpcMsgType = "shares_list"
|
||||||
EvtRoomCreated IpcMsgType = "room_created" // field: room (name)
|
EvtRoomCreated IpcMsgType = "room_created" // field: room (name)
|
||||||
EvtHistoryLoaded IpcMsgType = "history_loaded" // fields: room, messages
|
EvtHistoryLoaded IpcMsgType = "history_loaded" // fields: room, messages
|
||||||
|
EvtResumableTransfers IpcMsgType = "resumable_transfers" // field: resumable_files
|
||||||
|
EvtReaction IpcMsgType = "reaction" // fields: reaction_mid, reaction_emoji, peer_id
|
||||||
)
|
)
|
||||||
|
|
||||||
// NetworkInfo summarises one joined network for state_snapshot and network_joined events.
|
// NetworkInfo summarises one joined network for state_snapshot and network_joined events.
|
||||||
@@ -340,6 +357,7 @@ type IpcMessage struct {
|
|||||||
MasterID string `json:"master_id,omitempty"` // daemon's master public key hex
|
MasterID string `json:"master_id,omitempty"` // daemon's master public key hex
|
||||||
LocalPeer *PeerInfo `json:"local_peer,omitempty"`
|
LocalPeer *PeerInfo `json:"local_peer,omitempty"`
|
||||||
ConnectedPeers []PeerInfo `json:"connected_peers,omitempty"`
|
ConnectedPeers []PeerInfo `json:"connected_peers,omitempty"`
|
||||||
|
KnownPeers []PeerInfo `json:"known_peers,omitempty"` // historically seen, not currently connected
|
||||||
Rooms []string `json:"rooms,omitempty"`
|
Rooms []string `json:"rooms,omitempty"`
|
||||||
// multi-network: all joined networks (additive)
|
// multi-network: all joined networks (additive)
|
||||||
Networks []NetworkInfo `json:"networks,omitempty"`
|
Networks []NetworkInfo `json:"networks,omitempty"`
|
||||||
@@ -347,6 +365,9 @@ type IpcMessage struct {
|
|||||||
InviteGenerated string `json:"invite,omitempty"`
|
InviteGenerated string `json:"invite,omitempty"`
|
||||||
Files []FileEntry `json:"files,omitempty"`
|
Files []FileEntry `json:"files,omitempty"`
|
||||||
Messages []ChatMessage `json:"messages,omitempty"` // history_loaded
|
Messages []ChatMessage `json:"messages,omitempty"` // history_loaded
|
||||||
|
ResumableFiles []ResumableFile `json:"resumable_files,omitempty"` // resumable_transfers
|
||||||
|
ReactionMID string `json:"reaction_mid,omitempty"` // reaction
|
||||||
|
ReactionEmoji string `json:"reaction_emoji,omitempty"` // reaction
|
||||||
Shares []ShareEntry `json:"shares,omitempty"`
|
Shares []ShareEntry `json:"shares,omitempty"`
|
||||||
ShareNetworks []string `json:"network_ids,omitempty"` // for add_share command: scope to specific network IDs, or ["*"] for global
|
ShareNetworks []string `json:"network_ids,omitempty"` // for add_share command: scope to specific network IDs, or ["*"] for global
|
||||||
// export_identity / import_identity
|
// export_identity / import_identity
|
||||||
|
|||||||
@@ -38,10 +38,19 @@ CREATE TABLE IF NOT EXISTS rooms (
|
|||||||
|
|
||||||
// migrations run after the base schema. ALTER TABLE ADD COLUMN fails with
|
// migrations run after the base schema. ALTER TABLE ADD COLUMN fails with
|
||||||
// "duplicate column name" on subsequent opens — we swallow that error.
|
// "duplicate column name" on subsequent opens — we swallow that error.
|
||||||
|
// CREATE TABLE IF NOT EXISTS and CREATE INDEX IF NOT EXISTS are idempotent.
|
||||||
var migrations = []string{
|
var migrations = []string{
|
||||||
// EXT-007: canonical message ID for history dedup (NULL for pre-feature messages).
|
// EXT-007: canonical message ID for history dedup (NULL for pre-feature messages).
|
||||||
`ALTER TABLE messages ADD COLUMN msg_id TEXT`,
|
`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`,
|
`CREATE UNIQUE INDEX IF NOT EXISTS idx_messages_msg_id ON messages (msg_id) WHERE msg_id IS NOT NULL`,
|
||||||
|
// Reactions: (mid, emoji, from_peer) triple is the unique dedup key.
|
||||||
|
`CREATE TABLE IF NOT EXISTS reactions (
|
||||||
|
mid TEXT NOT NULL,
|
||||||
|
emoji TEXT NOT NULL,
|
||||||
|
from_peer TEXT NOT NULL,
|
||||||
|
reacted_at DATETIME NOT NULL,
|
||||||
|
PRIMARY KEY (mid, emoji, from_peer)
|
||||||
|
)`,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Store is a local SQLite-backed message and peer store.
|
// Store is a local SQLite-backed message and peer store.
|
||||||
@@ -107,7 +116,7 @@ func (s *Store) PeerAlias(peerID proto.PeerID) string {
|
|||||||
// RecentMessages returns up to limit messages for a room, oldest first.
|
// RecentMessages returns up to limit messages for a room, oldest first.
|
||||||
func (s *Store) RecentMessages(room string, limit int) ([]proto.ChatMessage, error) {
|
func (s *Store) RecentMessages(room string, limit int) ([]proto.ChatMessage, error) {
|
||||||
return s.queryMessages(
|
return s.queryMessages(
|
||||||
`SELECT mid, from_peer, body, sent_at FROM messages
|
`SELECT mid, from_peer, room, body, sent_at FROM messages
|
||||||
WHERE room = ?
|
WHERE room = ?
|
||||||
ORDER BY sent_at DESC LIMIT ?`,
|
ORDER BY sent_at DESC LIMIT ?`,
|
||||||
room, limit,
|
room, limit,
|
||||||
@@ -115,15 +124,23 @@ func (s *Store) RecentMessages(room string, limit int) ([]proto.ChatMessage, err
|
|||||||
}
|
}
|
||||||
|
|
||||||
// RecentMessagesSince returns up to limit messages for a room with ts > sinceMs, oldest first.
|
// RecentMessagesSince returns up to limit messages for a room with ts > sinceMs, oldest first.
|
||||||
// Only messages that have a msg_id (i.e. gossip-safe) are returned.
|
// sinceMs == 0 returns the most recent messages regardless of timestamp.
|
||||||
func (s *Store) RecentMessagesSince(room string, sinceMs int64, limit int) ([]proto.ChatMessage, error) {
|
func (s *Store) RecentMessagesSince(room string, sinceMs int64, limit int) ([]proto.ChatMessage, error) {
|
||||||
if limit <= 0 || limit > 500 {
|
if limit <= 0 || limit > 500 {
|
||||||
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()
|
since := time.UnixMilli(sinceMs).UTC()
|
||||||
return s.queryMessages(
|
return s.queryMessages(
|
||||||
`SELECT mid, from_peer, body, sent_at FROM messages
|
`SELECT mid, from_peer, room, body, sent_at FROM messages
|
||||||
WHERE room = ? AND sent_at > ? AND msg_id IS NOT NULL
|
WHERE room = ? AND sent_at > ?
|
||||||
ORDER BY sent_at DESC LIMIT ?`,
|
ORDER BY sent_at DESC LIMIT ?`,
|
||||||
room, since, limit,
|
room, since, limit,
|
||||||
)
|
)
|
||||||
@@ -141,7 +158,7 @@ func (s *Store) queryMessages(q string, args ...any) ([]proto.ChatMessage, error
|
|||||||
var m proto.ChatMessage
|
var m proto.ChatMessage
|
||||||
var from string
|
var from string
|
||||||
var sentAt time.Time
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
m.From = proto.PeerID(from)
|
m.From = proto.PeerID(from)
|
||||||
@@ -200,6 +217,43 @@ func (s *Store) KnownPeers() (map[proto.PeerID]string, error) {
|
|||||||
return out, rows.Err()
|
return out, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SaveReaction persists a reaction. Duplicate (mid, emoji, from_peer) triples are silently ignored.
|
||||||
|
func (s *Store) SaveReaction(mid, emoji, fromPeer string) error {
|
||||||
|
_, err := s.db.Exec(
|
||||||
|
`INSERT OR IGNORE INTO reactions (mid, emoji, from_peer, reacted_at) VALUES (?, ?, ?, ?)`,
|
||||||
|
mid, emoji, fromPeer, time.Now().UTC(),
|
||||||
|
)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReactionsForRoom returns all reactions for messages in a given room.
|
||||||
|
// Result: mid → emoji → []fromPeer (ordered by reaction time).
|
||||||
|
func (s *Store) ReactionsForRoom(room string) (map[string]map[string][]string, error) {
|
||||||
|
rows, err := s.db.Query(`
|
||||||
|
SELECT r.mid, r.emoji, r.from_peer
|
||||||
|
FROM reactions r
|
||||||
|
JOIN messages m ON m.mid = r.mid
|
||||||
|
WHERE m.room = ?
|
||||||
|
ORDER BY r.reacted_at
|
||||||
|
`, room)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := make(map[string]map[string][]string)
|
||||||
|
for rows.Next() {
|
||||||
|
var mid, emoji, from string
|
||||||
|
if err := rows.Scan(&mid, &emoji, &from); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if out[mid] == nil {
|
||||||
|
out[mid] = make(map[string][]string)
|
||||||
|
}
|
||||||
|
out[mid][emoji] = append(out[mid][emoji], from)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
func nullableString(s string) any {
|
func nullableString(s string) any {
|
||||||
if s == "" {
|
if s == "" {
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -33,6 +33,10 @@ input:focus { border-color: var(--accent); }
|
|||||||
.onboarding-section { width: 100%; border-top: 1px solid var(--border); padding-top: 12px; }
|
.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-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); }
|
.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; }
|
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 { background: none; color: var(--muted); font-size: 12px; padding: 4px 0; text-align: left; }
|
||||||
.toggle-link:hover { color: var(--text); }
|
.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; }
|
.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 { display: flex; align-items: baseline; gap: 0; padding: 2px 16px; line-height: 1.5; }
|
||||||
.message:hover { background: rgba(255,255,255,0.02); }
|
.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-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.mine .message-alias { color: var(--accent); }
|
||||||
.message-text { word-break: break-word; font-size: 14px; color: var(--text); }
|
.message-text { word-break: break-word; font-size: 14px; color: var(--text); }
|
||||||
@@ -158,3 +162,86 @@ details summary { color: var(--muted); font-size: 12px; cursor: pointer; }
|
|||||||
.file-entry-dir { cursor: pointer; }
|
.file-entry-dir { cursor: pointer; }
|
||||||
.file-entry-dir:hover { background: rgba(255,255,255,0.04); }
|
.file-entry-dir:hover { background: rgba(255,255,255,0.04); }
|
||||||
.file-entry-icon { font-size: 12px; flex-shrink: 0; }
|
.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); }
|
||||||
|
|
||||||
|
/* ── message links + image preview ── */
|
||||||
|
.msg-link { color: var(--accent); text-decoration: underline; word-break: break-all; }
|
||||||
|
.msg-link:hover { opacity: 0.8; }
|
||||||
|
.message-text { display: flex; flex-direction: column; gap: 4px; }
|
||||||
|
.msg-image-preview { max-width: 320px; max-height: 200px; border-radius: 6px; border: 1px solid var(--border); margin-top: 4px; object-fit: contain; display: block; }
|
||||||
|
|
||||||
|
/* ── reactions ── */
|
||||||
|
.message-wrapper { display: flex; flex-direction: column; padding: 0; }
|
||||||
|
.message-wrapper .message { padding: 2px 16px; }
|
||||||
|
.reaction-add { background: none; color: var(--muted); font-size: 13px; padding: 0 4px; line-height: 1; opacity: 0; transition: opacity 0.1s; margin-left: 4px; flex-shrink: 0; }
|
||||||
|
.message-wrapper:hover .reaction-add { opacity: 1; }
|
||||||
|
.reaction-add:hover { color: var(--accent); background: none; }
|
||||||
|
.reaction-picker { display: flex; gap: 4px; padding: 4px 16px 2px; }
|
||||||
|
.reaction-picker-btn { background: var(--surface); border: 1px solid var(--border); border-radius: 6px; font-size: 18px; padding: 2px 6px; line-height: 1.4; cursor: pointer; }
|
||||||
|
.reaction-picker-btn:hover { border-color: var(--accent); background: rgba(124,106,247,0.12); }
|
||||||
|
.reaction-bar { display: flex; flex-wrap: wrap; gap: 4px; padding: 2px 16px 4px; }
|
||||||
|
.reaction-chip { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; font-size: 13px; padding: 1px 8px; cursor: pointer; color: var(--text); }
|
||||||
|
.reaction-chip:hover { border-color: var(--accent); background: rgba(124,106,247,0.1); }
|
||||||
|
.reaction-chip.mine { border-color: var(--accent); background: rgba(124,106,247,0.18); }
|
||||||
|
|
||||||
|
/* ── mobile hamburger / close buttons ── */
|
||||||
|
.menu-btn-mobile { display: none; background: none; color: var(--muted); font-size: 18px; padding: 0 8px 0 0; line-height: 1; }
|
||||||
|
.menu-btn-mobile:hover { color: var(--text); background: none; }
|
||||||
|
.sidebar-close-mobile { display: none; background: none; color: var(--muted); font-size: 14px; padding: 2px 4px; }
|
||||||
|
.sidebar-close-mobile:hover { color: var(--text); background: none; }
|
||||||
|
|
||||||
|
/* ── responsive layout ── */
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
:root { --sidebar-w: 80vw; }
|
||||||
|
|
||||||
|
.chat-layout {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* sidebar slides in over the top */
|
||||||
|
.sidebar {
|
||||||
|
position: fixed;
|
||||||
|
top: 0; left: 0;
|
||||||
|
width: var(--sidebar-w);
|
||||||
|
height: 100%;
|
||||||
|
z-index: 100;
|
||||||
|
transform: translateX(-100%);
|
||||||
|
transition: transform 0.22s ease;
|
||||||
|
box-shadow: 4px 0 24px rgba(0,0,0,0.5);
|
||||||
|
}
|
||||||
|
.chat-layout.sidebar-open .sidebar {
|
||||||
|
transform: translateX(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* dim overlay behind open sidebar */
|
||||||
|
.chat-layout.sidebar-open::before {
|
||||||
|
content: '';
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
background: rgba(0,0,0,0.45);
|
||||||
|
z-index: 99;
|
||||||
|
}
|
||||||
|
|
||||||
|
.menu-btn-mobile { display: inline-block; }
|
||||||
|
.sidebar-close-mobile { display: inline-block; }
|
||||||
|
|
||||||
|
/* message pane fills full width */
|
||||||
|
.chat-layout > .message-pane { grid-column: 1; }
|
||||||
|
|
||||||
|
/* file browser stacks below on mobile */
|
||||||
|
.chat-layout.has-file-browser { grid-template-columns: 1fr; }
|
||||||
|
.chat-layout.has-file-browser > .file-browser { border-left: none; border-top: 1px solid var(--border); max-height: 40vh; overflow-y: auto; }
|
||||||
|
|
||||||
|
/* slightly larger tap targets */
|
||||||
|
.sidebar-item { padding: 8px 12px; font-size: 14px; }
|
||||||
|
.peer-row { padding: 6px 12px; }
|
||||||
|
.peer-row-actions { opacity: 1; }
|
||||||
|
.peer-action { font-size: 18px; padding: 2px 6px; }
|
||||||
|
|
||||||
|
/* message layout: stack alias above text on very narrow screens */
|
||||||
|
.message { flex-wrap: wrap; }
|
||||||
|
.message-ts { width: auto; min-width: 56px; }
|
||||||
|
.message-alias { width: auto; }
|
||||||
|
}
|
||||||
|
|||||||
@@ -433,9 +433,17 @@ class PeerConn {
|
|||||||
nick: m['nick'] as string || '', caps: m['caps'] || []
|
nick: m['nick'] as string || '', caps: m['caps'] || []
|
||||||
})
|
})
|
||||||
} else if (m['type'] === 'chat') {
|
} else if (m['type'] === 'chat') {
|
||||||
|
const ts = (m['ts'] as number) || Date.now()
|
||||||
this.on('chat', {
|
this.on('chat', {
|
||||||
peer: this.peerId, room: m['room'] as string || 'general',
|
peer: this.peerId, room: m['room'] as string || 'general',
|
||||||
text: m['text'] as string, ts: m['ts'] as number || Date.now()
|
text: m['text'] as string, ts,
|
||||||
|
mid: (m['mid'] as string) || `${this.peerId}-${ts}`,
|
||||||
|
})
|
||||||
|
} else if (m['type'] === 'reaction') {
|
||||||
|
this.on('reaction', {
|
||||||
|
peer: this.peerId,
|
||||||
|
mid: m['reaction_mid'] as string,
|
||||||
|
emoji: m['reaction_emoji'] as string,
|
||||||
})
|
})
|
||||||
} else if (m['type'] === 'pm') {
|
} else if (m['type'] === 'pm') {
|
||||||
this.on('pm', { peer: this.peerId, text: m['text'] as string, ts: m['ts'] as number || Date.now() })
|
this.on('pm', { peer: this.peerId, text: m['text'] as string, ts: m['ts'] as number || Date.now() })
|
||||||
@@ -556,14 +564,18 @@ class PeerConn {
|
|||||||
} catch { /* ignore */ }
|
} catch { /* ignore */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
sendChat(room: string, text: string) {
|
sendChat(room: string, text: string, mid: string) {
|
||||||
this._dc({ type: 'chat', room, text, ts: Date.now() })
|
this._dc({ type: 'chat', room, text, ts: Date.now(), mid })
|
||||||
}
|
}
|
||||||
|
|
||||||
sendPm(text: string) {
|
sendPm(text: string) {
|
||||||
this._dc({ type: 'pm', text, ts: Date.now() })
|
this._dc({ type: 'pm', text, ts: Date.now() })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sendReaction(mid: string, emoji: string) {
|
||||||
|
this._dc({ type: 'reaction', reaction_mid: mid, reaction_emoji: emoji })
|
||||||
|
}
|
||||||
|
|
||||||
private _dc(obj: object) {
|
private _dc(obj: object) {
|
||||||
if (this.dc?.readyState === 'open') this.dc.send(JSON.stringify(obj))
|
if (this.dc?.readyState === 'open') this.dc.send(JSON.stringify(obj))
|
||||||
}
|
}
|
||||||
@@ -755,9 +767,17 @@ export class BrowserAdapter {
|
|||||||
public_key: data['peer'] as string, created_at: new Date().toISOString()
|
public_key: data['peer'] as string, created_at: new Date().toISOString()
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
} else if (event === 'reaction') {
|
||||||
|
this.emit({
|
||||||
|
type: 'reaction',
|
||||||
|
network_id: this.networkId,
|
||||||
|
peer_id: data['peer'] as unknown as import('../types').PeerID,
|
||||||
|
reaction_mid: data['mid'] as string,
|
||||||
|
reaction_emoji: data['emoji'] as string,
|
||||||
|
})
|
||||||
} else if (event === 'chat') {
|
} else if (event === 'chat') {
|
||||||
const ts = (data['ts'] as number) || Date.now()
|
const ts = (data['ts'] as number) || Date.now()
|
||||||
const mid = `${data['peer']}-${ts}`
|
const mid = (data['mid'] as string) || `${data['peer']}-${ts}`
|
||||||
this.emit({
|
this.emit({
|
||||||
type: 'message_received',
|
type: 'message_received',
|
||||||
network_id: this.networkId,
|
network_id: this.networkId,
|
||||||
@@ -910,8 +930,8 @@ export class BrowserAdapter {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
// Broadcast
|
// Broadcast — include mid on the wire so recipients can reference it in reactions
|
||||||
this.peers.forEach(p => p.sendChat(room, text))
|
this.peers.forEach(p => p.sendChat(room, text, mid))
|
||||||
this.emit({
|
this.emit({
|
||||||
type: 'message_received',
|
type: 'message_received',
|
||||||
network_id: this.networkId,
|
network_id: this.networkId,
|
||||||
@@ -924,6 +944,22 @@ export class BrowserAdapter {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (msg.type === 'send_reaction') {
|
||||||
|
const mid = msg.reaction_mid
|
||||||
|
const emoji = msg.reaction_emoji
|
||||||
|
if (!mid || !emoji) return
|
||||||
|
this.peers.forEach(p => p.sendReaction(mid, emoji))
|
||||||
|
// Emit locally so the sender sees their own reaction immediately
|
||||||
|
this.emit({
|
||||||
|
type: 'reaction',
|
||||||
|
network_id: this.networkId,
|
||||||
|
peer_id: this.identity.id as unknown as import('../types').PeerID,
|
||||||
|
reaction_mid: mid,
|
||||||
|
reaction_emoji: emoji,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if (msg.type === 'export_identity') {
|
if (msg.type === 'export_identity') {
|
||||||
if (!msg.passphrase) return
|
if (!msg.passphrase) return
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1,16 +1,75 @@
|
|||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { useWaste } from '../store'
|
import { useWaste } from '../store'
|
||||||
|
|
||||||
export function MessagePane() {
|
const today = new Date()
|
||||||
const { messages, activeRoom, activeNetworkId, localPeer, connectedPeers, send } = useWaste()
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
const URL_RE = /https?:\/\/[^\s<>"']+/g
|
||||||
|
const IMAGE_EXT_RE = /\.(jpe?g|png|gif|webp|svg)(\?[^\s]*)?$/i
|
||||||
|
|
||||||
|
function renderText(text: string): React.ReactNode {
|
||||||
|
const parts: React.ReactNode[] = []
|
||||||
|
let last = 0
|
||||||
|
let m: RegExpExecArray | null
|
||||||
|
URL_RE.lastIndex = 0
|
||||||
|
while ((m = URL_RE.exec(text)) !== null) {
|
||||||
|
if (m.index > last) parts.push(text.slice(last, m.index))
|
||||||
|
const url = m[0]
|
||||||
|
const isImage = IMAGE_EXT_RE.test(url) || url.startsWith('blob:') || url.startsWith('data:image')
|
||||||
|
parts.push(
|
||||||
|
<a key={m.index} href={url} target="_blank" rel="noopener noreferrer" className="msg-link">
|
||||||
|
{url}
|
||||||
|
</a>
|
||||||
|
)
|
||||||
|
if (isImage) {
|
||||||
|
parts.push(
|
||||||
|
<img key={`img-${m.index}`} src={url} alt="" className="msg-image-preview" loading="lazy" />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
last = m.index + url.length
|
||||||
|
}
|
||||||
|
if (last < text.length) parts.push(text.slice(last))
|
||||||
|
return parts.length > 1 ? <>{parts}</> : text
|
||||||
|
}
|
||||||
|
|
||||||
|
const EMOJI_SET = ['👍', '❤️', '😂', '😮', '😢', '🙏']
|
||||||
|
|
||||||
|
export function MessagePane({ onMenuClick }: { onMenuClick: () => void }) {
|
||||||
|
const { messages, historyCutoff, activeRoom, activeNetworkId, localPeer, connectedPeers, knownPeers, reactions, sendReaction, send } = useWaste()
|
||||||
const [draft, setDraft] = useState('')
|
const [draft, setDraft] = useState('')
|
||||||
|
const [pickerMid, setPickerMid] = useState<string | null>(null)
|
||||||
const bottomRef = useRef<HTMLDivElement>(null)
|
const bottomRef = useRef<HTMLDivElement>(null)
|
||||||
const roomMessages = messages[activeRoom] ?? []
|
const msgKey = activeNetworkId ? `${activeNetworkId}:${activeRoom}` : activeRoom
|
||||||
|
const roomMessages = messages[msgKey] ?? []
|
||||||
|
const cutoff = historyCutoff[msgKey] ?? 0
|
||||||
|
|
||||||
|
const firstLiveIdx = cutoff > 0
|
||||||
|
? roomMessages.findIndex(m => m.ts > cutoff)
|
||||||
|
: -1
|
||||||
|
const dividerIdx = cutoff > 0
|
||||||
|
? (firstLiveIdx === -1 ? 0 : firstLiveIdx)
|
||||||
|
: -1
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
|
bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
|
||||||
}, [roomMessages.length])
|
}, [roomMessages.length])
|
||||||
|
|
||||||
|
// Close picker when clicking outside
|
||||||
|
useEffect(() => {
|
||||||
|
if (!pickerMid) return
|
||||||
|
const handler = () => setPickerMid(null)
|
||||||
|
document.addEventListener('click', handler)
|
||||||
|
return () => document.removeEventListener('click', handler)
|
||||||
|
}, [pickerMid])
|
||||||
|
|
||||||
function submit(e: React.FormEvent) {
|
function submit(e: React.FormEvent) {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
const text = draft.trim()
|
const text = draft.trim()
|
||||||
@@ -30,7 +89,21 @@ export function MessagePane() {
|
|||||||
|
|
||||||
function aliasFor(fromId: string) {
|
function aliasFor(fromId: string) {
|
||||||
if (fromId === localPeer?.id) return localPeer.alias
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleReaction(mid: string, emoji: string, e: React.MouseEvent) {
|
||||||
|
e.stopPropagation()
|
||||||
|
if (!activeNetworkId || !mid) return
|
||||||
|
sendReaction(activeNetworkId, mid, emoji)
|
||||||
|
setPickerMid(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
function openPicker(mid: string, e: React.MouseEvent) {
|
||||||
|
e.stopPropagation()
|
||||||
|
setPickerMid(prev => prev === mid ? null : mid)
|
||||||
}
|
}
|
||||||
|
|
||||||
const roomLabel = activeRoom.startsWith('dm:')
|
const roomLabel = activeRoom.startsWith('dm:')
|
||||||
@@ -39,18 +112,67 @@ export function MessagePane() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="message-pane">
|
<main className="message-pane">
|
||||||
<div className="message-pane-header">{roomLabel}</div>
|
<div className="message-pane-header">
|
||||||
|
<button className="menu-btn-mobile" onClick={onMenuClick} aria-label="Menu">☰</button>
|
||||||
|
{roomLabel}
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="messages">
|
<div className="messages">
|
||||||
|
{dividerIdx === 0 && (
|
||||||
|
<div className="history-divider"><span>earlier messages</span></div>
|
||||||
|
)}
|
||||||
{roomMessages.map((msg, i) => {
|
{roomMessages.map((msg, i) => {
|
||||||
const mine = msg.from === localPeer?.id
|
const mine = msg.from === localPeer?.id
|
||||||
const alias = aliasFor(msg.from)
|
const alias = aliasFor(String(msg.from))
|
||||||
const time = new Date(msg.ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })
|
const ts = formatTs(msg.ts)
|
||||||
|
const mid = msg.mid ?? ''
|
||||||
|
const msgReactions = mid ? reactions[mid] : undefined
|
||||||
|
const hasReactions = msgReactions && Object.keys(msgReactions).length > 0
|
||||||
return (
|
return (
|
||||||
<div key={msg.mid ?? i} className={`message ${mine ? 'mine' : ''}`}>
|
<div key={mid || i} className="message-wrapper">
|
||||||
<span className="message-ts">{time}</span>
|
{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-alias">{alias}</span>
|
||||||
<span className="message-text">{msg.text}</span>
|
<span className="message-text">
|
||||||
|
{renderText(msg.text)}
|
||||||
|
</span>
|
||||||
|
{mid && (
|
||||||
|
<button
|
||||||
|
className="reaction-add"
|
||||||
|
onClick={e => openPicker(mid, e)}
|
||||||
|
title="React"
|
||||||
|
>+</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{pickerMid === mid && (
|
||||||
|
<div className="reaction-picker" onClick={e => e.stopPropagation()}>
|
||||||
|
{EMOJI_SET.map(emoji => (
|
||||||
|
<button key={emoji} className="reaction-picker-btn" onClick={e => toggleReaction(mid, emoji, e)}>
|
||||||
|
{emoji}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{hasReactions && (
|
||||||
|
<div className="reaction-bar">
|
||||||
|
{Object.entries(msgReactions!).map(([emoji, fromIds]) => {
|
||||||
|
const iMine = fromIds.includes(localPeer?.id ?? '')
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={emoji}
|
||||||
|
className={`reaction-chip ${iMine ? 'mine' : ''}`}
|
||||||
|
onClick={e => toggleReaction(mid, emoji, e)}
|
||||||
|
title={fromIds.map(aliasFor).join(', ')}
|
||||||
|
>
|
||||||
|
{emoji} {fromIds.length}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -26,22 +26,31 @@ function formatTs(ts: number | undefined): string {
|
|||||||
return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })
|
return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Sidebar() {
|
export function Sidebar({ onClose }: { onClose: () => void }) {
|
||||||
const {
|
const {
|
||||||
localPeer, masterId, masterAlias,
|
localPeer, masterId, masterAlias,
|
||||||
networks, activeNetworkId, activeRoom,
|
networks, activeNetworkId, activeRoom,
|
||||||
connectedPeers, peerStatus,
|
connectedPeers, peerStatus,
|
||||||
setActiveRoom, setActiveNetwork, messages, browseFiles, sendFileTo, adapterMode,
|
setActiveRoom, setActiveNetwork, messages, browseFiles, sendFileTo, adapterMode,
|
||||||
customRooms, createRoom, logout,
|
customRooms, createRoom, logout, send,
|
||||||
} = useWaste()
|
} = useWaste()
|
||||||
const [addingRoom, setAddingRoom] = useState(false)
|
const [addingRoom, setAddingRoom] = useState(false)
|
||||||
const [newRoomName, setNewRoomName] = useState('')
|
const [newRoomName, setNewRoomName] = useState('')
|
||||||
|
const [addingNetwork, setAddingNetwork] = useState(false)
|
||||||
|
const [newNetName, setNewNetName] = useState('')
|
||||||
|
const [newNetAnchor, setNewNetAnchor] = useState('')
|
||||||
|
|
||||||
const netCustomRooms = activeNetworkId ? (customRooms[activeNetworkId] ?? []) : []
|
const netCustomRooms = activeNetworkId ? (customRooms[activeNetworkId] ?? []) : []
|
||||||
const rooms = ['general', ...netCustomRooms]
|
const rooms = ['general', ...netCustomRooms]
|
||||||
Object.keys(messages).forEach(r => {
|
if (activeNetworkId) {
|
||||||
if (r.startsWith('dm:') && !rooms.includes(r)) rooms.push(r)
|
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) {
|
function submitNewRoom(e: React.FormEvent) {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
@@ -50,6 +59,25 @@ export function Sidebar() {
|
|||||||
setAddingRoom(false)
|
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 displayAlias = localPeer?.alias ?? masterAlias ?? ''
|
||||||
const displayId = localPeer?.id ?? masterId ?? ''
|
const displayId = localPeer?.id ?? masterId ?? ''
|
||||||
const card = displayId ? makeYawCard(displayId, displayAlias) : null
|
const card = displayId ? makeYawCard(displayId, displayAlias) : null
|
||||||
@@ -90,24 +118,51 @@ export function Sidebar() {
|
|||||||
<span className="peer-id">{displayId.slice(0, 16).replace(/(.{4})/g, '$1 ').trim()}</span>
|
<span className="peer-id">{displayId.slice(0, 16).replace(/(.{4})/g, '$1 ').trim()}</span>
|
||||||
</div>
|
</div>
|
||||||
<button className="sidebar-logout" onClick={handleLogout} title="Leave network">⏻</button>
|
<button className="sidebar-logout" onClick={handleLogout} title="Leave network">⏻</button>
|
||||||
|
<button className="sidebar-close-mobile" onClick={onClose} title="Close">✕</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="sidebar-section">
|
<div className="sidebar-section">
|
||||||
<div className="sidebar-label-row">
|
<div className="sidebar-label-row">
|
||||||
<span className="sidebar-label">Networks</span>
|
<span className="sidebar-label">Networks</span>
|
||||||
|
<span style={{ display: 'flex', gap: 2 }}>
|
||||||
{activeNetworkId && (
|
{activeNetworkId && (
|
||||||
<button className="sidebar-add" onClick={copyHangLink} title="Copy hang link (pre-fills join form, no invite required)">🔗</button>
|
<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>
|
</div>
|
||||||
{networks.map(n => (
|
{networks.map(n => (
|
||||||
<button
|
<button
|
||||||
key={n.network_id}
|
key={n.network_id}
|
||||||
className={`sidebar-item ${n.network_id === activeNetworkId ? 'active' : ''}`}
|
className={`sidebar-item ${n.network_id === activeNetworkId ? 'active' : ''}`}
|
||||||
onClick={() => setActiveNetwork(n.network_id)}
|
onClick={() => { setActiveNetwork(n.network_id); onClose() }}
|
||||||
>
|
>
|
||||||
{n.network_name}
|
{n.network_name}
|
||||||
</button>
|
</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>
|
||||||
|
|
||||||
<div className="sidebar-section">
|
<div className="sidebar-section">
|
||||||
@@ -119,7 +174,7 @@ export function Sidebar() {
|
|||||||
<button
|
<button
|
||||||
key={r}
|
key={r}
|
||||||
className={`sidebar-item ${r === activeRoom ? 'active' : ''}`}
|
className={`sidebar-item ${r === activeRoom ? 'active' : ''}`}
|
||||||
onClick={() => setActiveRoom(r)}
|
onClick={() => { setActiveRoom(r); onClose() }}
|
||||||
>
|
>
|
||||||
{r.startsWith('dm:') ? `@ ${r.slice(3, 11)}…` : `# ${r}`}
|
{r.startsWith('dm:') ? `@ ${r.slice(3, 11)}…` : `# ${r}`}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -7,12 +7,13 @@ function fmt(bytes: number): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function Transfers() {
|
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 hasPending = Object.keys(pendingOffers).length > 0
|
||||||
const hasActive = Object.keys(fileProgress).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) {
|
function alias(peerId: string) {
|
||||||
return connectedPeers.find(p => p.id === peerId)?.alias ?? peerId.slice(0, 8)
|
return connectedPeers.find(p => p.id === peerId)?.alias ?? peerId.slice(0, 8)
|
||||||
@@ -22,6 +23,24 @@ export function Transfers() {
|
|||||||
<div className="sidebar-section">
|
<div className="sidebar-section">
|
||||||
<span className="sidebar-label">Transfers</span>
|
<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]) => (
|
{Object.entries(pendingOffers).map(([xid, offer]) => (
|
||||||
<div key={xid} className="transfer-row">
|
<div key={xid} className="transfer-row">
|
||||||
<span className="transfer-name" title={offer.name}>{offer.name}</span>
|
<span className="transfer-name" title={offer.name}>{offer.name}</span>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
import { Sidebar } from '../components/Sidebar'
|
import { Sidebar } from '../components/Sidebar'
|
||||||
import { MessagePane } from '../components/MessagePane'
|
import { MessagePane } from '../components/MessagePane'
|
||||||
import { FileBrowser } from '../components/FileBrowser'
|
import { FileBrowser } from '../components/FileBrowser'
|
||||||
@@ -5,10 +6,11 @@ import { useWaste } from '../store'
|
|||||||
|
|
||||||
export function Chat() {
|
export function Chat() {
|
||||||
const { activeFilePeer } = useWaste()
|
const { activeFilePeer } = useWaste()
|
||||||
|
const [sidebarOpen, setSidebarOpen] = useState(false)
|
||||||
return (
|
return (
|
||||||
<div className={`chat-layout${activeFilePeer ? ' has-file-browser' : ''}`}>
|
<div className={`chat-layout${activeFilePeer ? ' has-file-browser' : ''}${sidebarOpen ? ' sidebar-open' : ''}`}>
|
||||||
<Sidebar />
|
<Sidebar onClose={() => setSidebarOpen(false)} />
|
||||||
<MessagePane />
|
<MessagePane onMenuClick={() => setSidebarOpen(v => !v)} />
|
||||||
{activeFilePeer && <FileBrowser />}
|
{activeFilePeer && <FileBrowser />}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -72,8 +72,15 @@ export function Onboarding({ status }: Props) {
|
|||||||
if (adapterMode !== 'browser' || status !== 'connected') return
|
if (adapterMode !== 'browser' || status !== 'connected') return
|
||||||
const { network: n, netHash: nh } = parseInviteParams()
|
const { network: n, netHash: nh } = parseInviteParams()
|
||||||
if (n || nh) return // explicit invite — don't auto-join, show form
|
if (n || nh) return // explicit invite — don't auto-join, show form
|
||||||
|
// 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')
|
const savedNetwork = localStorage.getItem('waste_last_network')
|
||||||
if (savedNetwork) doJoin(savedNetwork, '')
|
if (savedNetwork) doJoin(savedNetwork, '')
|
||||||
|
}
|
||||||
}, [adapterMode, status]) // eslint-disable-line react-hooks/exhaustive-deps
|
}, [adapterMode, status]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
function joinNetwork(e: React.FormEvent) {
|
function joinNetwork(e: React.FormEvent) {
|
||||||
@@ -87,8 +94,16 @@ export function Onboarding({ status }: Props) {
|
|||||||
if (adapterMode === 'browser') {
|
if (adapterMode === 'browser') {
|
||||||
localStorage.setItem('waste_anchor_url', anchorUrl)
|
localStorage.setItem('waste_anchor_url', anchorUrl)
|
||||||
if (nick.trim()) localStorage.setItem('waste_nick', nick.trim())
|
if (nick.trim()) localStorage.setItem('waste_nick', nick.trim())
|
||||||
if (name) localStorage.setItem('waste_last_network', name)
|
if (name) {
|
||||||
else localStorage.removeItem('waste_last_network')
|
// 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) {
|
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 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 ────────────────────────────────────────────────
|
// ── disconnected / connecting ────────────────────────────────────────────────
|
||||||
if (status !== 'connected') {
|
if (status !== 'connected') {
|
||||||
@@ -159,8 +175,21 @@ export function Onboarding({ status }: Props) {
|
|||||||
</div>
|
</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">
|
<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' && (
|
{adapterMode === 'browser' && (
|
||||||
<input
|
<input
|
||||||
|
|||||||
@@ -29,9 +29,12 @@ interface WasteState {
|
|||||||
|
|
||||||
// peers
|
// peers
|
||||||
connectedPeers: PeerInfo[]
|
connectedPeers: PeerInfo[]
|
||||||
|
knownPeers: Record<string, string> // id → alias for historical peers
|
||||||
|
|
||||||
// chat — keyed by room
|
// chat — keyed by room
|
||||||
messages: Record<string, ChatMessage[]>
|
messages: Record<string, ChatMessage[]>
|
||||||
|
// rooms for which we have received history: room → ts of last history message
|
||||||
|
historyCutoff: Record<string, number>
|
||||||
activeRoom: string
|
activeRoom: string
|
||||||
// user-created rooms, keyed by networkId
|
// user-created rooms, keyed by networkId
|
||||||
customRooms: Record<string, string[]>
|
customRooms: Record<string, string[]>
|
||||||
@@ -53,6 +56,10 @@ interface WasteState {
|
|||||||
pendingOffers: Record<string, { peerId: string; name: string; size: number }>
|
pendingOffers: Record<string, { peerId: string; name: string; size: number }>
|
||||||
// active in-progress transfers: xid → progress
|
// active in-progress transfers: xid → progress
|
||||||
fileProgress: Record<string, { peerId: string; name: string; received: number; total: number }>
|
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 }>
|
||||||
|
// reactions: mid → emoji → [fromId, ...]
|
||||||
|
reactions: Record<string, Record<string, string[]>>
|
||||||
|
|
||||||
// actions
|
// actions
|
||||||
connect: (url: string) => void
|
connect: (url: string) => void
|
||||||
@@ -69,6 +76,7 @@ interface WasteState {
|
|||||||
rejectOffer: (peerId: string, xid: string) => void
|
rejectOffer: (peerId: string, xid: string) => void
|
||||||
cancelTransfer: (peerId: string, xid: string, direction: 'recv' | 'send') => void
|
cancelTransfer: (peerId: string, xid: string, direction: 'recv' | 'send') => void
|
||||||
createRoom: (name: string) => void
|
createRoom: (name: string) => void
|
||||||
|
sendReaction: (networkId: string, mid: string, emoji: string) => void
|
||||||
logout: (clearIdentity: boolean) => void
|
logout: (clearIdentity: boolean) => void
|
||||||
handleEvent: (msg: IpcMessage) => void
|
handleEvent: (msg: IpcMessage) => void
|
||||||
}
|
}
|
||||||
@@ -83,7 +91,9 @@ export const useWaste = create<WasteState>((set, get) => ({
|
|||||||
networks: [],
|
networks: [],
|
||||||
activeNetworkId: null,
|
activeNetworkId: null,
|
||||||
connectedPeers: [],
|
connectedPeers: [],
|
||||||
|
knownPeers: {},
|
||||||
messages: {},
|
messages: {},
|
||||||
|
historyCutoff: {},
|
||||||
activeRoom: 'general',
|
activeRoom: 'general',
|
||||||
customRooms: {},
|
customRooms: {},
|
||||||
fileLists: {},
|
fileLists: {},
|
||||||
@@ -93,6 +103,8 @@ export const useWaste = create<WasteState>((set, get) => ({
|
|||||||
sharedFilesByNetwork: {},
|
sharedFilesByNetwork: {},
|
||||||
pendingOffers: {},
|
pendingOffers: {},
|
||||||
fileProgress: {},
|
fileProgress: {},
|
||||||
|
resumableFiles: {},
|
||||||
|
reactions: {},
|
||||||
|
|
||||||
connect(url: string) {
|
connect(url: string) {
|
||||||
const adapter = new DaemonAdapter(url)
|
const adapter = new DaemonAdapter(url)
|
||||||
@@ -181,6 +193,10 @@ export const useWaste = create<WasteState>((set, get) => ({
|
|||||||
window.location.reload()
|
window.location.reload()
|
||||||
},
|
},
|
||||||
|
|
||||||
|
sendReaction(networkId, mid, emoji) {
|
||||||
|
get().send({ type: 'send_reaction', network_id: networkId, reaction_mid: mid, reaction_emoji: emoji })
|
||||||
|
},
|
||||||
|
|
||||||
createRoom(name) {
|
createRoom(name) {
|
||||||
const netId = get().activeNetworkId
|
const netId = get().activeNetworkId
|
||||||
if (!netId || !name.trim()) return
|
if (!netId || !name.trim()) return
|
||||||
@@ -209,6 +225,8 @@ export const useWaste = create<WasteState>((set, get) => ({
|
|||||||
switch (msg.type) {
|
switch (msg.type) {
|
||||||
case 'state_snapshot': {
|
case 'state_snapshot': {
|
||||||
const networks = msg.networks ?? []
|
const networks = msg.networks ?? []
|
||||||
|
const knownPeers: Record<string, string> = {}
|
||||||
|
for (const p of msg.known_peers ?? []) knownPeers[p.id] = p.alias
|
||||||
set({
|
set({
|
||||||
masterAlias: msg.master_alias ?? null,
|
masterAlias: msg.master_alias ?? null,
|
||||||
masterId: msg.master_id ?? null,
|
masterId: msg.master_id ?? null,
|
||||||
@@ -216,6 +234,7 @@ export const useWaste = create<WasteState>((set, get) => ({
|
|||||||
networks,
|
networks,
|
||||||
connectedPeers: msg.connected_peers ?? [],
|
connectedPeers: msg.connected_peers ?? [],
|
||||||
activeNetworkId: networks[0]?.network_id ?? null,
|
activeNetworkId: networks[0]?.network_id ?? null,
|
||||||
|
knownPeers,
|
||||||
})
|
})
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -272,14 +291,14 @@ export const useWaste = create<WasteState>((set, get) => ({
|
|||||||
case 'message_received': {
|
case 'message_received': {
|
||||||
if (msg.message) {
|
if (msg.message) {
|
||||||
const m = msg.message
|
const m = msg.message
|
||||||
const room = m.room
|
const key = `${msg.network_id}:${m.room}`
|
||||||
const fromId = String(m.from)
|
const fromId = String(m.from)
|
||||||
set(s => {
|
set(s => {
|
||||||
const existing = s.messages[room] ?? []
|
const existing = s.messages[key] ?? []
|
||||||
if (m.mid && existing.some(e => e.mid === m.mid)) return s
|
if (m.mid && existing.some(e => e.mid === m.mid)) return s
|
||||||
const prev = s.peerStatus[fromId] ?? {}
|
const prev = s.peerStatus[fromId] ?? {}
|
||||||
return {
|
return {
|
||||||
messages: { ...s.messages, [room]: [...existing, m] },
|
messages: { ...s.messages, [key]: [...existing, m] },
|
||||||
peerStatus: { ...s.peerStatus, [fromId]: { ...prev, lastSeen: m.ts } },
|
peerStatus: { ...s.peerStatus, [fromId]: { ...prev, lastSeen: m.ts } },
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -341,10 +360,13 @@ export const useWaste = create<WasteState>((set, get) => ({
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
case 'file_complete': {
|
case 'file_complete': {
|
||||||
if (msg.path && msg.offer?.name) {
|
// Always clear progress — transfer_id is the xid in daemon mode; offer.xid in browser mode.
|
||||||
// clear progress entry
|
const xid = msg.transfer_id ?? msg.offer?.xid
|
||||||
const xid = msg.offer.xid
|
if (xid) {
|
||||||
set(s => { const fp = { ...s.fileProgress }; delete fp[xid]; return { fileProgress: fp } })
|
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')
|
const a = document.createElement('a')
|
||||||
a.href = msg.path
|
a.href = msg.path
|
||||||
a.download = msg.offer.name
|
a.download = msg.offer.name
|
||||||
@@ -352,6 +374,46 @@ export const useWaste = create<WasteState>((set, get) => ({
|
|||||||
}
|
}
|
||||||
break
|
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 'reaction': {
|
||||||
|
const mid = msg.reaction_mid
|
||||||
|
const emoji = msg.reaction_emoji
|
||||||
|
const from = msg.peer_id
|
||||||
|
if (!mid || !emoji || !from) break
|
||||||
|
set(s => {
|
||||||
|
const byEmoji = { ...(s.reactions[mid] ?? {}) }
|
||||||
|
const existing = byEmoji[emoji] ?? []
|
||||||
|
if (existing.includes(from)) return s
|
||||||
|
return { reactions: { ...s.reactions, [mid]: { ...byEmoji, [emoji]: [...existing, from] } } }
|
||||||
|
})
|
||||||
|
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,12 @@ export type IpcMsgType =
|
|||||||
| 'shares_list'
|
| 'shares_list'
|
||||||
| 'peer_status'
|
| 'peer_status'
|
||||||
| 'error'
|
| 'error'
|
||||||
|
| 'history_loaded'
|
||||||
|
| 'room_created'
|
||||||
|
| 'create_room'
|
||||||
|
| 'resumable_transfers'
|
||||||
|
| 'send_reaction'
|
||||||
|
| 'reaction'
|
||||||
|
|
||||||
export interface IpcMessage {
|
export interface IpcMessage {
|
||||||
type: IpcMsgType
|
type: IpcMsgType
|
||||||
@@ -113,6 +119,7 @@ export interface IpcMessage {
|
|||||||
master_id?: string
|
master_id?: string
|
||||||
local_peer?: PeerInfo
|
local_peer?: PeerInfo
|
||||||
connected_peers?: PeerInfo[]
|
connected_peers?: PeerInfo[]
|
||||||
|
known_peers?: PeerInfo[]
|
||||||
rooms?: string[]
|
rooms?: string[]
|
||||||
networks?: NetworkInfo[]
|
networks?: NetworkInfo[]
|
||||||
error_message?: string
|
error_message?: string
|
||||||
@@ -124,4 +131,11 @@ export interface IpcMessage {
|
|||||||
conn_state?: PeerConnState
|
conn_state?: PeerConnState
|
||||||
candidate_type?: CandidateType
|
candidate_type?: CandidateType
|
||||||
remote_address?: string
|
remote_address?: string
|
||||||
|
// history_loaded
|
||||||
|
messages?: ChatMessage[]
|
||||||
|
// resumable_transfers
|
||||||
|
resumable_files?: Array<{ name: string; sha256: string; from: string; size: number; offset: number }>
|
||||||
|
// reaction
|
||||||
|
reaction_mid?: string
|
||||||
|
reaction_emoji?: string
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user