terminalchat-cli 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import React from 'react'
2
3
  import { readFileSync } from 'node:fs'
3
4
  import { createInterface } from 'node:readline'
4
5
  import { fileURLToPath } from 'node:url'
@@ -67,7 +68,10 @@ try {
67
68
  process.exit(1)
68
69
  }
69
70
 
70
- const { unmount, waitUntilExit } = render(App({ engine }), { exitOnCtrlC: false })
71
+ const { unmount, waitUntilExit } = render(
72
+ React.createElement(App, { engine }),
73
+ { exitOnCtrlC: false }
74
+ )
71
75
 
72
76
  process.on('SIGINT', () => {
73
77
  // App handles Ctrl+C → engine.shutdown() then calls process.exit()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "terminalchat-cli",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "TerminalChat (Tchat) — a serverless, peer-to-peer terminal chat over HyperDHT. No server of ours; NAT hole-punching and Noise encryption built in.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/engine.js CHANGED
@@ -186,10 +186,13 @@ export class Engine extends EventEmitter {
186
186
  this._friends[inviterKeyHex] = { name: '…', addedAt: Date.now() }
187
187
  }
188
188
 
189
+ let timer
190
+
189
191
  // Once the inviter comes online (network accepted their hello), we're done.
190
192
  const onOnline = (keyHex) => {
191
193
  if (keyHex !== inviterKeyHex) return
192
194
  this.off('friend-online', onOnline)
195
+ if (timer) clearTimeout(timer)
193
196
  const name = this._friends[inviterKeyHex]?.name ?? ''
194
197
  // Persist the friend now that the join succeeded
195
198
  this._store.friends.save(this._friends)
@@ -207,13 +210,14 @@ export class Engine extends EventEmitter {
207
210
  this._network._connectTo(inviterKeyHex)
208
211
  .then(() => { this._network._handlers.getHello = origGetHello })
209
212
  .catch(err => {
213
+ if (timer) clearTimeout(timer)
210
214
  this._network._handlers.getHello = origGetHello
211
215
  this.off('friend-online', onOnline)
212
216
  if (!wasAlreadyFriend) delete this._friends[inviterKeyHex]
213
217
  reject(err)
214
218
  })
215
219
 
216
- const timer = setTimeout(() => {
220
+ timer = setTimeout(() => {
217
221
  this.off('friend-online', onOnline)
218
222
  this._network._handlers.getHello = origGetHello
219
223
  if (!wasAlreadyFriend) delete this._friends[inviterKeyHex]
@@ -242,7 +246,11 @@ export class Engine extends EventEmitter {
242
246
  // ---------------------------------------------------------------------------
243
247
 
244
248
  async getHistory (friendKeyHex, n = 50) {
245
- return this._store.readHistory(friendKeyHex, n)
249
+ const history = await this._store.readHistory(friendKeyHex, n)
250
+ const ackedUpTo = this._seqState.ackedUpTo?.[friendKeyHex] ?? 0
251
+ return history.map(entry => entry.direction === 'out'
252
+ ? { ...entry, delivered: (entry.seq ?? 0) <= ackedUpTo }
253
+ : entry)
246
254
  }
247
255
 
248
256
  whoami () {
package/src/ui/App.js CHANGED
@@ -1,5 +1,5 @@
1
- import React, { useMemo, useState } from 'react'
2
- import { Box, Text, useInput, useApp } from 'ink'
1
+ import React, { useEffect, useMemo, useState } from 'react'
2
+ import { Box, Text, useInput, useApp, useStdout } from 'ink'
3
3
  import { Engine } from '../engine.js'
4
4
  import { useEngine } from './useEngine.js'
5
5
  import { Sidebar } from './Sidebar.js'
@@ -16,9 +16,29 @@ export default function App ({ engine: providedEngine } = {}) {
16
16
  const [input, setInput] = useState('')
17
17
  const [overlay, setOverlay] = useState(null)
18
18
  const [selection, setSelection] = useState(0)
19
+ const [chatScroll, setChatScroll] = useState(0)
20
+ const { stdout } = useStdout()
21
+ const columns = stdout?.columns ?? 120
22
+ const rows = stdout?.rows ?? 30
19
23
  const selectedKey = state.selectedKey ?? state.friends[selection]?.keyHex
20
24
  const friend = state.friends.find(item => item.keyHex === selectedKey)
21
25
 
26
+ useEffect(() => {
27
+ if (!state.friends.length) {
28
+ setSelection(0)
29
+ return
30
+ }
31
+ if (!state.selectedKey && state.friends[0]) {
32
+ state.selectFriend(state.friends[0].keyHex)
33
+ setSelection(0)
34
+ return
35
+ }
36
+ const index = state.friends.findIndex(item => item.keyHex === state.selectedKey)
37
+ if (index >= 0) setSelection(index)
38
+ }, [state.friends, state.selectedKey])
39
+
40
+ useEffect(() => setChatScroll(0), [selectedKey])
41
+
22
42
  useInput((value, key) => {
23
43
  if (key.ctrl && value === 'c') {
24
44
  engine.shutdown().finally(exit)
@@ -32,6 +52,19 @@ export default function App ({ engine: providedEngine } = {}) {
32
52
  return
33
53
  }
34
54
  if (key.tab) { setFocus(previous => previous === 'sidebar' ? 'input' : 'sidebar'); return }
55
+ if (key.pageUp) { setChatScroll(previous => previous + 10); return }
56
+ if (key.pageDown) { setChatScroll(previous => Math.max(0, previous - 10)); return }
57
+ if (focus === 'input' && key.upArrow) { setChatScroll(previous => previous + 1); return }
58
+ if (focus === 'input' && key.downArrow) { setChatScroll(previous => Math.max(0, previous - 1)); return }
59
+ if (focus === 'sidebar' && key.return) {
60
+ const selectedFriend = state.friends[selection]
61
+ if (selectedFriend) {
62
+ state.selectFriend(selectedFriend.keyHex)
63
+ setChatScroll(0)
64
+ setFocus('input')
65
+ }
66
+ return
67
+ }
35
68
  if (focus === 'sidebar' && (key.upArrow || key.downArrow)) {
36
69
  const next = Math.max(0, Math.min(state.friends.length - 1, selection + (key.downArrow ? 1 : -1)))
37
70
  setSelection(next)
@@ -42,27 +75,41 @@ export default function App ({ engine: providedEngine } = {}) {
42
75
 
43
76
  const send = body => {
44
77
  if (friend && body.trim()) {
45
- try { engine.sendMessage(friend.keyHex, body) } catch {}
78
+ try { engine.sendMessage(friend.keyHex, body) } catch (error) { engine.emit('error', error) }
46
79
  setInput('')
47
80
  }
48
81
  }
49
82
 
50
- if (!state.ready) return h(Box, { padding: 1 }, h(Text, { color: 'cyan' }, 'Starting TerminalChat…'), state.error && h(Text, { color: 'red' }, ` ${state.error.message}`))
83
+ if (!state.ready) return h(Box, { flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' },
84
+ h(Text, { bold: true, color: 'cyan' }, '◉ TERMINALCHAT'),
85
+ h(Text, { dimColor: true }, 'Connecting securely…'),
86
+ state.error && h(Text, { color: 'red' }, state.error.message)
87
+ )
51
88
 
52
89
  let modal = null
53
- if (overlay === 'actions') modal = h(Actions)
90
+ if (overlay === 'actions') modal = h(Actions, { onChoose: item => {
91
+ const next = { Invite: 'invite', 'Add friend': 'add', Join: 'join', 'Who am I': 'whoami', History: 'history' }[item]
92
+ setOverlay(next)
93
+ } })
54
94
  if (overlay === 'invite') modal = h(InviteOverlay, { engine })
55
- if (overlay === 'add') modal = h(AddFriendOverlay, { engine, onDone: () => setOverlay(null) })
56
- if (overlay === 'join') modal = h(JoinOverlay, { engine, onJoined: () => setOverlay(null), onError: error => { setOverlay(null); state.error = error } })
95
+ if (overlay === 'add') modal = h(AddFriendOverlay, { engine, onDone: () => setOverlay(null), onError: error => { engine.emit('error', error); setOverlay(null) } })
96
+ if (overlay === 'join') modal = h(JoinOverlay, { engine, onJoined: () => setOverlay(null), onError: error => { engine.emit('error', error); setOverlay(null) } })
57
97
  if (overlay === 'whoami') modal = h(WhoamiOverlay, { engine })
58
98
  if (overlay === 'history' && friend) modal = h(HistoryOverlay, { engine, friendKey: friend.keyHex })
59
99
 
100
+ const identity = engine.whoami()
60
101
  return h(Box, { flexDirection: 'column', height: '100%' },
61
- h(Box, { flexGrow: 1 },
62
- h(Sidebar, { friends: state.friends, selectedKey, unread: state.unread, onSelect: state.selectFriend, focused: focus === 'sidebar' }),
63
- h(ChatPane, { friend, messages: state.messages[selectedKey], input, setInput, onSubmit: send, focused: focus === 'input' })
102
+ h(Box, { justifyContent: 'space-between', borderStyle: 'single', borderColor: 'cyan', paddingX: 1 },
103
+ h(Text, { bold: true, color: 'cyan' }, '◉ TERMINALCHAT'),
104
+ h(Text, { dimColor: true }, `${identity.name} · ${identity.publicKey.slice(0, 12)}…`)
105
+ ),
106
+ h(Box, { flexGrow: 1, marginTop: 0 },
107
+ h(Sidebar, { friends: state.friends, selectedKey, unread: state.unread, onSelect: state.selectFriend, focused: focus === 'sidebar', height: rows, width: columns }),
108
+ h(ChatPane, { friend, messages: state.messages[selectedKey], input, setInput, onSubmit: send, focused: focus === 'input', height: rows, width: columns, scrollOffset: chatScroll })
109
+ ),
110
+ h(Box, { borderStyle: 'single', borderColor: state.error ? 'red' : 'gray', paddingX: 1 },
111
+ h(Text, { color: state.error ? 'red' : undefined, dimColor: !state.error }, state.error ? `⚠ ${state.error.message}` : 'Ctrl+N Actions · Tab Focus · ↑/↓ Scroll · PgUp/PgDn History · Ctrl+C Quit')
64
112
  ),
65
- h(Text, { dimColor: true }, state.error ? `Error: ${state.error.message}` : 'Ctrl+N actions · Tab focus · Ctrl+C quit'),
66
113
  modal
67
114
  )
68
115
  }
@@ -4,20 +4,52 @@ import TextInput from 'ink-text-input'
4
4
 
5
5
  const h = React.createElement
6
6
 
7
- export function ChatPane ({ friend, messages, input, setInput, onSubmit, focused }) {
8
- return h(Box, { flexDirection: 'column', flexGrow: 1, paddingLeft: 1 },
9
- h(Text, { bold: true }, friend ? `Chat with ${friend.name}` : 'Select a friend'),
10
- h(Box, { flexDirection: 'column', flexGrow: 1, marginTop: 1 },
11
- ...(messages ?? []).map((message, index) => h(Text, { key: `${message.sender}-${message.seq}-${index}` },
12
- `${message.direction === 'out' ? 'you' : friend?.name ?? 'peer'}: ${message.body} `,
13
- h(Text, { dimColor: message.direction === 'out' && !message.delivered }, message.direction === 'out' ? (message.delivered ? '✓' : '…') : '')
14
- ))
7
+ export function ChatPane ({ friend, messages, input, setInput, onSubmit, focused, height = 30, width = 120, scrollOffset = 0 }) {
8
+ const displayedMessages = messages ?? []
9
+ const chatWidth = Math.max(40, width - (width < 90 ? 24 : 30) - 4)
10
+ const visibleCount = Math.max(4, (height || 30) - 10)
11
+ const maxScroll = Math.max(0, displayedMessages.length - visibleCount)
12
+ const effectiveScroll = Math.min(scrollOffset, maxScroll)
13
+ const end = Math.max(0, displayedMessages.length - effectiveScroll)
14
+ const start = Math.max(0, end - visibleCount)
15
+ const visibleMessages = displayedMessages.slice(start, end)
16
+
17
+ return h(Box, { flexDirection: 'column', flexGrow: 1, paddingLeft: 1, paddingRight: 1 },
18
+ h(Box, { justifyContent: 'space-between', borderStyle: 'round', borderColor: friend ? 'cyan' : 'gray', paddingX: 1 },
19
+ h(Text, { bold: true, color: friend ? 'cyan' : 'gray' }, friend ? friend.name : 'NO CONVERSATION'),
20
+ friend ? h(Text, { color: friend.online ? 'green' : 'gray' }, effectiveScroll > 0 ? `↑ ${effectiveScroll} older · ${friend.online ? '● online' : '○ offline'}` : (friend.online ? '● online' : '○ offline')) : null
21
+ ),
22
+ h(Box, { flexDirection: 'column', flexGrow: 1, marginTop: 1, marginBottom: 1 },
23
+ !friend
24
+ ? h(Box, { flexGrow: 1, alignItems: 'center', justifyContent: 'center' },
25
+ h(Box, { flexDirection: 'column', alignItems: 'center' },
26
+ h(Text, { bold: true, color: 'cyan' }, 'TerminalChat'),
27
+ h(Text, { dimColor: true }, 'Press Ctrl+N to invite or join')
28
+ )
29
+ )
30
+ : displayedMessages.length === 0
31
+ ? h(Box, { flexGrow: 1, alignItems: 'center', justifyContent: 'center' },
32
+ h(Text, { dimColor: true }, 'No messages yet. Say hello.')
33
+ )
34
+ : visibleMessages.map((message, index) => {
35
+ const outgoing = message.direction === 'out'
36
+ const time = new Date(message.ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
37
+ return h(Box, { key: `${message.sender}-${message.seq}-${index}`, justifyContent: outgoing ? 'flex-end' : 'flex-start', marginBottom: 0 },
38
+ h(Box, { flexDirection: 'column', alignItems: outgoing ? 'flex-end' : 'flex-start', maxWidth: chatWidth },
39
+ h(Text, { color: outgoing ? 'cyan' : 'green', bold: outgoing }, outgoing ? 'YOU' : (friend.name || 'PEER')),
40
+ h(Box, { borderStyle: 'round', borderColor: outgoing ? 'cyan' : 'green', paddingX: 1 },
41
+ h(Text, { wrap: 'wrap' }, message.body)
42
+ ),
43
+ h(Text, { dimColor: true }, `${time}${outgoing ? (message.delivered ? ' ✓ delivered' : ' … pending') : ''}`)
44
+ )
45
+ )
46
+ })
15
47
  ),
16
48
  friend
17
- ? h(Box, { borderStyle: 'single', borderColor: focused ? 'cyan' : 'gray', paddingX: 1 },
18
- h(Text, null, '> '),
19
- h(TextInput, { value: input, onChange: setInput, onSubmit, focus: focused, placeholder: 'Type a message' })
20
- )
21
- : h(Text, { dimColor: true }, 'Add a friend with Ctrl+N')
49
+ ? h(Box, { borderStyle: 'double', borderColor: focused ? 'cyan' : 'gray', paddingX: 1, height: 3 },
50
+ h(Text, { color: focused ? 'cyan' : 'gray', bold: true }, '› '),
51
+ h(TextInput, { value: input, onChange: setInput, onSubmit, focus: focused, placeholder: 'Write a message…' })
52
+ )
53
+ : h(Box, { borderStyle: 'round', borderColor: 'gray', paddingX: 1 }, h(Text, { dimColor: true }, 'Select or add a friend to chat'))
22
54
  )
23
55
  }
@@ -1,5 +1,5 @@
1
1
  import React, { useEffect, useState } from 'react'
2
- import { Box, Text } from 'ink'
2
+ import { Box, Text, useInput } from 'ink'
3
3
  import TextInput from 'ink-text-input'
4
4
 
5
5
  const h = React.createElement
@@ -13,17 +13,33 @@ function Overlay ({ title, children }) {
13
13
  }
14
14
 
15
15
  export function Actions ({ onChoose }) {
16
+ const items = ['Invite', 'Add friend', 'Join', 'Who am I', 'History']
17
+ const [selected, setSelected] = useState(0)
18
+
19
+ useInput((value, key) => {
20
+ if (key.upArrow) setSelected(previous => (previous + items.length - 1) % items.length)
21
+ if (key.downArrow) setSelected(previous => (previous + 1) % items.length)
22
+ if (key.return) onChoose(items[selected])
23
+ if (/^[1-5]$/.test(value)) onChoose(items[Number(value) - 1])
24
+ })
25
+
16
26
  return h(Overlay, { title: 'Actions' },
17
- ...['Invite', 'Add friend', 'Join', 'Who am I', 'History'].map((item, index) =>
18
- h(Text, { key: item, color: index === 0 ? 'cyan' : undefined }, `${index === 0 ? '›' : ' '} ${item}`)),
19
- h(Text, { dimColor: true }, 'Use number keys · Esc closes')
27
+ ...items.map((item, index) => h(Text, {
28
+ key: item,
29
+ bold: index === selected,
30
+ color: index === selected ? 'cyan' : undefined,
31
+ backgroundColor: index === selected ? 'blue' : undefined,
32
+ }, `${index + 1}. ${index === selected ? '›' : ' '} ${item}`)),
33
+ h(Text, { dimColor: true }, '↑/↓ select · Enter open · Esc close')
20
34
  )
21
35
  }
22
36
 
23
37
  export function InviteOverlay ({ engine }) {
38
+ const [code] = useState(() => engine.createInvite())
24
39
  return h(Overlay, { title: 'Invite' },
25
- h(Text, null, engine.createInvite()),
26
- h(Text, { dimColor: true }, 'Share this code · Esc closes')
40
+ h(Text, { color: 'yellow' }, 'One-time code · expires in 24 hours'),
41
+ h(Box, { borderStyle: 'round', borderColor: 'cyan', marginTop: 1, paddingX: 1 }, h(Text, { wrap: 'wrap', color: 'cyan' }, code)),
42
+ h(Text, { dimColor: true }, 'Copy this code and share it privately · Esc closes')
27
43
  )
28
44
  }
29
45
 
@@ -36,34 +52,57 @@ export function WhoamiOverlay ({ engine }) {
36
52
  )
37
53
  }
38
54
 
39
- export function AddFriendOverlay ({ engine, onDone }) {
55
+ export function AddFriendOverlay ({ engine, onDone, onError }) {
40
56
  const [name, setName] = useState('')
41
57
  const [key, setKey] = useState('')
58
+ const [editingKey, setEditingKey] = useState(false)
59
+
42
60
  return h(Overlay, { title: 'Add friend' },
43
- h(Text, null, 'Name'),
44
- h(TextInput, { value: name, onChange: setName, focus: true }),
45
- h(Text, null, 'Public key (hex)'),
46
- h(TextInput, { value: key, onChange: setKey, onSubmit: () => { engine.addFriend(name, key); onDone() } }),
47
- h(Text, { dimColor: true }, 'Enter submits · Esc closes')
61
+ h(Text, { color: 'cyan' }, editingKey ? 'Public key (64 hex characters)' : 'Display name'),
62
+ !editingKey
63
+ ? h(TextInput, { value: name, onChange: setName, focus: true, onSubmit: () => setEditingKey(true) })
64
+ : h(TextInput, { value: key, onChange: setKey, focus: true, onSubmit: () => {
65
+ try {
66
+ if (!name.trim()) throw new Error('Enter a display name')
67
+ if (!/^[0-9a-fA-F]{64}$/.test(key.trim())) throw new Error('Public key must be 64 hex characters')
68
+ engine.addFriend(name.trim(), key.trim().toLowerCase())
69
+ onDone()
70
+ } catch (error) { onError?.(error) }
71
+ } }),
72
+ h(Text, { dimColor: true }, editingKey ? 'Enter adds friend · Esc closes' : 'Enter continues · Esc closes')
48
73
  )
49
74
  }
50
75
 
51
76
  export function JoinOverlay ({ engine, onJoined, onError }) {
52
77
  const [code, setCode] = useState('')
78
+ const [busy, setBusy] = useState(false)
53
79
  return h(Overlay, { title: 'Join' },
54
- h(Text, null, 'Invite code'),
55
- h(TextInput, { value: code, onChange: setCode, focus: true, onSubmit: async () => {
56
- try { await engine.join(code); onJoined() } catch (error) { onError(error) }
80
+ h(Text, { color: busy ? 'yellow' : 'cyan' }, busy ? 'Connecting…' : 'Invite code'),
81
+ h(TextInput, { value: code, onChange: setCode, focus: !busy, onSubmit: async () => {
82
+ if (busy || !code.trim()) return
83
+ setBusy(true)
84
+ try { await engine.join(code.trim()); onJoined() } catch (error) { onError(error) }
85
+ finally { setBusy(false) }
57
86
  } }),
58
- h(Text, { dimColor: true }, 'Enter submits · Esc closes')
87
+ h(Text, { dimColor: true }, busy ? 'Waiting for the inviter · Esc cancels' : 'Paste a code, then press Enter · Esc closes')
59
88
  )
60
89
  }
61
90
 
62
91
  export function HistoryOverlay ({ engine, friendKey }) {
63
92
  const [messages, setMessages] = useState(null)
64
- useEffect(() => { engine.getHistory(friendKey, 20).then(setMessages) }, [engine, friendKey])
93
+ const [scroll, setScroll] = useState(0)
94
+ useEffect(() => { engine.getHistory(friendKey, 100).then(setMessages) }, [engine, friendKey])
95
+ useInput((value, key) => {
96
+ if (key.upArrow || key.pageUp) setScroll(previous => previous + 5)
97
+ if (key.downArrow || key.pageDown) setScroll(previous => Math.max(0, previous - 5))
98
+ })
99
+ const history = messages ? [...messages].reverse() : null
100
+ const visible = history ? history.slice(scroll, scroll + 12) : [{ body: 'Loading…' }]
65
101
  return h(Overlay, { title: 'History' },
66
- ...(messages ?? [ { body: 'Loading…' } ]).map((message, index) => h(Text, { key: index }, message.body)),
67
- h(Text, { dimColor: true }, 'Esc closes')
102
+ ...visible.map((message, index) => h(Box, { key: `${message.seq ?? index}-${index}` },
103
+ h(Text, { dimColor: true }, `${message.direction === 'out' ? 'You' : 'Friend'}: `),
104
+ h(Text, { wrap: 'wrap' }, message.body)
105
+ )),
106
+ h(Text, { dimColor: true }, history ? `↑/↓ scroll · Esc closes · ${Math.min(history.length, scroll + visible.length)}/${history.length}` : 'Esc closes')
68
107
  )
69
108
  }
package/src/ui/Sidebar.js CHANGED
@@ -1,18 +1,45 @@
1
- import React from 'react'
1
+ import React, { useEffect, useState } from 'react'
2
2
  import { Box, Text } from 'ink'
3
3
 
4
4
  const h = React.createElement
5
5
 
6
- export function Sidebar ({ friends, selectedKey, unread, onSelect, focused }) {
7
- return h(Box, { flexDirection: 'column', width: 28, borderStyle: 'round', borderColor: focused ? 'cyan' : 'gray', paddingX: 1 },
8
- h(Text, { bold: true, color: 'cyan' }, 'Friends'),
6
+ export function Sidebar ({ friends, selectedKey, unread, onSelect, focused, height = 30, width = 120 }) {
7
+ const onlineCount = friends.filter(friend => friend.online).length
8
+ const sidebarWidth = width < 90 ? 24 : 30
9
+ const [scrollOffset, setScrollOffset] = useState(0)
10
+ const visibleCount = Math.max(3, (height || 30) - 9)
11
+ const selectedIndex = friends.findIndex(friend => friend.keyHex === selectedKey)
12
+
13
+ useEffect(() => {
14
+ if (selectedIndex < 0) return
15
+ if (selectedIndex < scrollOffset) setScrollOffset(selectedIndex)
16
+ if (selectedIndex >= scrollOffset + visibleCount) setScrollOffset(selectedIndex - visibleCount + 1)
17
+ }, [selectedIndex, scrollOffset, visibleCount])
18
+
19
+ const visibleFriends = friends.slice(scrollOffset, scrollOffset + visibleCount)
20
+
21
+ return h(Box, { flexDirection: 'column', width: sidebarWidth, borderStyle: 'round', borderColor: focused ? 'cyan' : 'gray', paddingX: 1 },
22
+ h(Box, { justifyContent: 'space-between' },
23
+ h(Text, { bold: true, color: 'cyan' }, 'CONVERSATIONS'),
24
+ h(Text, { dimColor: true }, `${onlineCount}/${friends.length}`)
25
+ ),
26
+ h(Box, { marginTop: 1, marginBottom: 1 }, h(Text, { dimColor: true }, friends.length ? 'Use ↑/↓ to move' : 'No contacts connected')),
9
27
  friends.length === 0
10
- ? h(Text, { dimColor: true }, 'No friends yet')
11
- : friends.map(friend => h(Text, {
12
- key: friend.keyHex,
13
- color: friend.keyHex === selectedKey ? 'black' : undefined,
14
- backgroundColor: friend.keyHex === selectedKey ? 'cyan' : undefined,
15
- }, `${friend.online ? '●' : '○'} ${friend.name} ${(unread[friend.keyHex] ?? 0) > 0 ? `(${unread[friend.keyHex]})` : ''}`)),
16
- h(Box, { marginTop: 1 }, h(Text, { dimColor: true }, 'Tab focus · Ctrl+N menu'))
28
+ ? h(Box, { flexDirection: 'column', marginTop: 1 },
29
+ h(Text, { color: 'yellow' }, 'Start a conversation'),
30
+ h(Text, { dimColor: true }, 'Ctrl+N → Join or Invite')
31
+ )
32
+ : visibleFriends.map(friend => {
33
+ const selected = friend.keyHex === selectedKey
34
+ const unreadCount = unread[friend.keyHex] ?? 0
35
+ return h(Box, { key: friend.keyHex, paddingX: selected ? 0 : 1 },
36
+ h(Text, {
37
+ bold: selected,
38
+ color: selected ? 'black' : friend.online ? 'green' : 'gray',
39
+ backgroundColor: selected ? 'cyan' : undefined,
40
+ }, `${selected ? '› ' : ' '}${friend.online ? '●' : '○'} ${friend.name}${unreadCount ? ` ${unreadCount}` : ''}`)
41
+ )
42
+ }),
43
+ h(Box, { marginTop: 1 }, h(Text, { dimColor: true }, 'Tab switch · Ctrl+N actions'))
17
44
  )
18
45
  }
@@ -1,4 +1,5 @@
1
1
  import { useEffect, useState } from 'react'
2
+ import { sortMessages } from '../outbox.js'
2
3
 
3
4
  export function useEngine (engine) {
4
5
  const [snapshot, setSnapshot] = useState({
@@ -25,7 +26,10 @@ export function useEngine (engine) {
25
26
  const onReady = async () => {
26
27
  const friends = engine.getFriends()
27
28
  const messages = {}
28
- for (const friend of friends) messages[friend.keyHex] = await engine.getHistory(friend.keyHex)
29
+ for (const friend of friends) {
30
+ const history = await engine.getHistory(friend.keyHex)
31
+ messages[friend.keyHex] = sortMessages(history)
32
+ }
29
33
  if (active) setSnapshot(previous => ({ ...previous, friends, messages, ready: true }))
30
34
  }
31
35
  const onMessage = async (key, entry) => {
@@ -33,13 +37,23 @@ export function useEngine (engine) {
33
37
  if (!active) return
34
38
  setSnapshot(previous => ({
35
39
  ...previous,
36
- messages: { ...previous.messages, [key]: history },
40
+ messages: { ...previous.messages, [key]: sortMessages(history) },
37
41
  unread: entry.direction === 'in' && previous.selectedKey !== key
38
42
  ? { ...previous.unread, [key]: (previous.unread[key] ?? 0) + 1 }
39
43
  : previous.unread,
40
44
  }))
41
45
  }
42
46
  const onFriend = () => refresh()
47
+ const onAck = async (key, seq) => {
48
+ const history = await engine.getHistory(key)
49
+ if (!active) return
50
+ setSnapshot(previous => ({
51
+ ...previous,
52
+ friends: engine.getFriends(),
53
+ messages: { ...previous.messages, [key]: sortMessages(history) },
54
+ online: Object.fromEntries(engine.getFriends().map(friend => [friend.keyHex, friend.online])),
55
+ }))
56
+ }
43
57
  const onError = error => setSnapshot(previous => ({ ...previous, error }))
44
58
 
45
59
  engine.on('ready', onReady)
@@ -47,16 +61,20 @@ export function useEngine (engine) {
47
61
  engine.on('friend-added', onFriend)
48
62
  engine.on('friend-online', onFriend)
49
63
  engine.on('friend-offline', onFriend)
50
- engine.on('ack', onMessage)
64
+ engine.on('ack', onAck)
51
65
  engine.on('error', onError)
52
- engine.start().catch(onError)
66
+ if (engine._started) {
67
+ onReady()
68
+ } else {
69
+ engine.start().catch(onError)
70
+ }
53
71
 
54
72
  return () => {
55
73
  active = false
56
74
  for (const [event, listener] of [
57
75
  ['ready', onReady], ['message', onMessage], ['friend-added', onFriend],
58
76
  ['friend-online', onFriend], ['friend-offline', onFriend],
59
- ['ack', onMessage], ['error', onError],
77
+ ['ack', onAck], ['error', onError],
60
78
  ]) engine.off(event, listener)
61
79
  }
62
80
  }, [engine])