6 Commits

Author SHA1 Message Date
Fredrik Johansson
1d9c9d1524 fix: add explicit Join button to sidebar add-network form
All checks were successful
Build / Build & release (push) Successful in 13m37s
The form had no submit button so there was no visible way to confirm.
Enter should have worked but was unreliable with two inputs. Added a
disabled-until-valid Join button.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-29 18:40:41 +02:00
Fredrik Johansson
f5fb0862ff fix: key messages by networkId:room to prevent collision across networks
Two networks sharing a room name (e.g. "general") were clobbering each
other's message lists. Now keyed by `${networkId}:${room}` throughout
the web store, MessagePane, and Sidebar DM detection.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-29 16:55:16 +02:00
Fredrik Johansson
dab5387cbd feat: multi-network join, persistence, and switching in web UI
- Sidebar: "+" button next to Networks opens an inline join form;
  in browser mode shows anchor URL field; saves to waste_saved_networks
- Onboarding: saved networks shown as quick-join chips above the join
  form; auto-rejoin all saved networks on reconnect (not just one)
- Browser mode: networks persisted as [{name, anchor}] array in
  localStorage (waste_saved_networks); legacy waste_last_network kept
  for backward compat
- Daemon mode: daemon already tracks joined networks; web UI just needs
  the "+" to send join_network for additional ones

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-29 16:38:46 +02:00
Fredrik Johansson
1d9827beb0 docs: mark resume UX and history gossip shipped; remove proposal doc
- FUTURE.md: remove "not yet done" note on resume UX, update Native UI
  section to reflect tray/notifications shipped, add new roadmap entries
- Delete PROPOSAL-history-gossip.md (implemented, documented in EXTENSIONS.md)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-29 15:47:14 +02:00
Fredrik Johansson
fcbd84f873 fix: compact timestamps, historical alias resolution, wider ts column
- Timestamps now show "Jun 28 10:58" for older messages (dropped
  "Yesterday" which overflowed the fixed-width column)
- Timestamp column widened from 52px to 72px to fit date+time
- state_snapshot now includes known_peers (historically seen, not
  currently connected) so the UI can resolve aliases in history
- MessagePane aliasFor falls back to knownPeers map

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-29 13:43:29 +02:00
Fredrik Johansson
cef9374416 fix: show date in timestamps; fix history divider appearing immediately
- MessagePane: show date in timestamps (Yesterday/MMM D) for messages
  not from today; divider now appears at the top of history on load
  rather than waiting for a live message to create the boundary
- TUI: same date-aware timestamp formatting (Yesterday / Jan 2)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-29 11:45:51 +02:00
11 changed files with 184 additions and 188 deletions

View File

@@ -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,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 | 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 |
--- ---

View File

@@ -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)

View File

@@ -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

View File

@@ -459,6 +459,22 @@ 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

View File

@@ -350,6 +350,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"`

View File

@@ -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); }

View File

@@ -1,12 +1,34 @@
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { useWaste } from '../store' 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() { export function MessagePane() {
const { messages, historyCutoff, activeRoom, activeNetworkId, localPeer, connectedPeers, send } = useWaste() const { messages, historyCutoff, activeRoom, activeNetworkId, localPeer, connectedPeers, knownPeers, send } = useWaste()
const [draft, setDraft] = useState('') const [draft, setDraft] = useState('')
const bottomRef = useRef<HTMLDivElement>(null) const bottomRef = useRef<HTMLDivElement>(null)
const roomMessages = messages[activeRoom] ?? [] const msgKey = activeNetworkId ? `${activeNetworkId}:${activeRoom}` : activeRoom
const cutoff = historyCutoff[activeRoom] ?? 0 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(() => { useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: 'smooth' }) bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
@@ -31,7 +53,9 @@ 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)
} }
const roomLabel = activeRoom.startsWith('dm:') const roomLabel = activeRoom.startsWith('dm:')
@@ -43,20 +67,20 @@ export function MessagePane() {
<div className="message-pane-header">{roomLabel}</div> <div className="message-pane-header">{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 showDivider = cutoff > 0 && i > 0 && roomMessages[i - 1].ts <= cutoff && msg.ts > cutoff
return ( return (
<div key={msg.mid ?? i}> <div key={msg.mid ?? i}>
{showDivider && ( {i === dividerIdx && dividerIdx > 0 && (
<div className="history-divider"> <div className="history-divider"><span>earlier messages</span></div>
<span>earlier messages</span>
</div>
)} )}
<div className={`message ${mine ? 'mine' : ''}`}> <div className={`message ${mine ? 'mine' : ''}`}>
<span className="message-ts">{time}</span> <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">{msg.text}</span>
</div> </div>

View File

@@ -32,16 +32,25 @@ export function Sidebar() {
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
@@ -95,9 +123,12 @@ export function Sidebar() {
<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
@@ -108,6 +139,29 @@ export function Sidebar() {
{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">

View File

@@ -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

View File

@@ -29,6 +29,7 @@ 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[]>
@@ -87,6 +88,7 @@ export const useWaste = create<WasteState>((set, get) => ({
networks: [], networks: [],
activeNetworkId: null, activeNetworkId: null,
connectedPeers: [], connectedPeers: [],
knownPeers: {},
messages: {}, messages: {},
historyCutoff: {}, historyCutoff: {},
activeRoom: 'general', activeRoom: 'general',
@@ -215,6 +217,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,
@@ -222,6 +226,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
} }
@@ -278,14 +283,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 } },
} }
}) })
@@ -373,16 +378,17 @@ export const useWaste = create<WasteState>((set, get) => ({
const room = msg.room const room = msg.room
const incoming = (msg.messages ?? []) as ChatMessage[] const incoming = (msg.messages ?? []) as ChatMessage[]
if (!room || incoming.length === 0) break if (!room || incoming.length === 0) break
const key = `${msg.network_id}:${room}`
set(s => { set(s => {
const existing = s.messages[room] ?? [] const existing = s.messages[key] ?? []
const existingMids = new Set(existing.map(m => m.mid).filter(Boolean)) const existingMids = new Set(existing.map(m => m.mid).filter(Boolean))
const fresh = incoming.filter(m => !m.mid || !existingMids.has(m.mid)) const fresh = incoming.filter(m => !m.mid || !existingMids.has(m.mid))
if (fresh.length === 0) return s if (fresh.length === 0) return s
const merged = [...fresh, ...existing].sort((a, b) => a.ts - b.ts) const merged = [...fresh, ...existing].sort((a, b) => a.ts - b.ts)
const cutoff = fresh[fresh.length - 1]?.ts ?? 0 const cutoff = fresh[fresh.length - 1]?.ts ?? 0
return { return {
messages: { ...s.messages, [room]: merged }, messages: { ...s.messages, [key]: merged },
historyCutoff: { ...s.historyCutoff, [room]: cutoff }, historyCutoff: { ...s.historyCutoff, [key]: cutoff },
} }
}) })
break break

View File

@@ -117,6 +117,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