terminalchat-cli 0.0.0-stage → 0.1.0

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.
package/src/outbox.js ADDED
@@ -0,0 +1,159 @@
1
+ /**
2
+ * src/outbox.js — pure seq/ack/dedup/ordering engine
3
+ *
4
+ * This module is intentionally side-effect-free: every function takes
5
+ * state objects and returns new/mutated state. No I/O, no DHT, no Ink.
6
+ * That makes it trivially unit-testable and re-usable from both network.js
7
+ * and the integration test.
8
+ *
9
+ * Terminology:
10
+ * outbox = { [friendKeyHex]: [ {seq, ts, body}, … ] } unacked sent msgs
11
+ * seqState = { nextSeq: { [friendKeyHex]: n }, ackedUpTo: { [friendKeyHex]: n } }
12
+ * inbox = internal per-friend map of received { [senderKeyHex]: Set<seq> }
13
+ * and the last contiguous seq per sender (for cumulative acks)
14
+ *
15
+ * Message identity: (senderPubKeyHex, seq) — globally unique because seq is
16
+ * per-sender-per-receiver pair and each device owns one identity.
17
+ */
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // Outbox: allocate + prune
21
+ // ---------------------------------------------------------------------------
22
+
23
+ /**
24
+ * Allocate the next seq number for a message to `friendKey`, mutate seqState,
25
+ * append to outbox, and return { seq }.
26
+ */
27
+ export function allocateSeq (outboxData, seqState, friendKey, ts, body) {
28
+ const nextSeq = seqState.nextSeq[friendKey] ?? 1
29
+ seqState.nextSeq[friendKey] = nextSeq + 1
30
+
31
+ if (!outboxData[friendKey]) outboxData[friendKey] = []
32
+ outboxData[friendKey].push({ seq: nextSeq, ts, body })
33
+
34
+ return nextSeq
35
+ }
36
+
37
+ /**
38
+ * Process a cumulative ack {upTo:N} from `friendKey`.
39
+ * Removes all outbox entries for that friend with seq ≤ N.
40
+ * Updates seqState.ackedUpTo.
41
+ * Returns the number of entries pruned.
42
+ */
43
+ export function processAck (outboxData, seqState, friendKey, upTo) {
44
+ seqState.ackedUpTo[friendKey] = Math.max(
45
+ seqState.ackedUpTo[friendKey] ?? 0,
46
+ upTo
47
+ )
48
+ if (!outboxData[friendKey]) return 0
49
+ const before = outboxData[friendKey].length
50
+ outboxData[friendKey] = outboxData[friendKey].filter(m => m.seq > upTo)
51
+ return before - outboxData[friendKey].length
52
+ }
53
+
54
+ /**
55
+ * Return the full outbox for a given friend (for flushing on connect).
56
+ * Returns [] if empty.
57
+ */
58
+ export function getOutbox (outboxData, friendKey) {
59
+ return (outboxData[friendKey] ?? []).slice().sort((a, b) => a.seq - b.seq)
60
+ }
61
+
62
+ // ---------------------------------------------------------------------------
63
+ // Inbox: dedup + cumulative ack tracking
64
+ // ---------------------------------------------------------------------------
65
+
66
+ /**
67
+ * Create a fresh per-connection inbox tracker for one peer.
68
+ *
69
+ * Returns an object with:
70
+ * receive(senderKey, seq, ts, body) → { stored: bool, ackUpTo: number }
71
+ * getAck(senderKey) → number (last contiguous seq)
72
+ *
73
+ * The tracker is in-memory only; it is re-created each time a connection
74
+ * is established (re-established connections re-deliver from the outbox,
75
+ * and duplicates are detected via the persistent history dedup below).
76
+ */
77
+ export function createInboxTracker () {
78
+ // seqs we've seen per sender, as a sorted array
79
+ const received = {} // senderKey → Set<seq>
80
+ const contiguous = {} // senderKey → last contiguous seq (starts at 0)
81
+
82
+ return {
83
+ /**
84
+ * Record receipt of (senderKey, seq).
85
+ * Returns { stored: bool, ackUpTo: number }.
86
+ * stored=false means it's a duplicate; still ack it.
87
+ */
88
+ receive (senderKey, seq) {
89
+ if (!received[senderKey]) {
90
+ received[senderKey] = new Set()
91
+ contiguous[senderKey] = 0
92
+ }
93
+ const set = received[senderKey]
94
+ const c0 = contiguous[senderKey]
95
+
96
+ // Already fully delivered: seq is at or below the contiguous mark,
97
+ // OR it's in the pending-gap set (arrived out of order before).
98
+ const isDup = seq <= c0 || set.has(seq)
99
+ if (!isDup) set.add(seq)
100
+
101
+ // Advance contiguous pointer past any now-consecutive pending seqs
102
+ let c = c0
103
+ while (set.has(c + 1)) {
104
+ c++
105
+ set.delete(c) // safe: entry is now "contiguous", not needed in set
106
+ }
107
+ contiguous[senderKey] = c
108
+
109
+ return { stored: !isDup, ackUpTo: c }
110
+ },
111
+
112
+ getAck (senderKey) {
113
+ return contiguous[senderKey] ?? 0
114
+ },
115
+ }
116
+ }
117
+
118
+ // ---------------------------------------------------------------------------
119
+ // History-level dedup (persistent, across reconnects)
120
+ // ---------------------------------------------------------------------------
121
+
122
+ /**
123
+ * Build a Set of "<senderKey>:<seq>" from an array of history entries.
124
+ * Used to skip duplicate messages that survived a reconnect cycle.
125
+ */
126
+ export function buildSeenSet (historyEntries) {
127
+ const seen = new Set()
128
+ for (const e of historyEntries) {
129
+ if (e.sender && e.seq != null) {
130
+ seen.add(`${e.sender}:${e.seq}`)
131
+ }
132
+ }
133
+ return seen
134
+ }
135
+
136
+ export function isSeen (seenSet, senderKey, seq) {
137
+ return seenSet.has(`${senderKey}:${seq}`)
138
+ }
139
+
140
+ export function markSeen (seenSet, senderKey, seq) {
141
+ seenSet.add(`${senderKey}:${seq}`)
142
+ }
143
+
144
+ // ---------------------------------------------------------------------------
145
+ // Display ordering
146
+ // ---------------------------------------------------------------------------
147
+
148
+ /**
149
+ * Sort an array of history entries for display.
150
+ * Primary: ts (timestamp ms). Tiebreak: (sender, seq) lexicographic.
151
+ */
152
+ export function sortMessages (messages) {
153
+ return messages.slice().sort((a, b) => {
154
+ if (a.ts !== b.ts) return a.ts - b.ts
155
+ if (a.sender < b.sender) return -1
156
+ if (a.sender > b.sender) return 1
157
+ return a.seq - b.seq
158
+ })
159
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * src/protocol.js — wire protocol framing + inline base58
3
+ *
4
+ * Wire: newline-delimited JSON over the Noise-encrypted HyperDHT stream.
5
+ *
6
+ * Frame types:
7
+ * {type:"hello", name, invite?} first frame each direction
8
+ * {type:"msg", seq, ts, body} body UTF-8, max 8 KB
9
+ * {type:"ack", upTo} cumulative ack
10
+ *
11
+ * Line limits: single line > 64 KB → drop connection.
12
+ * Body limit: body > 8 KB → drop connection.
13
+ *
14
+ * Invite codes: base58( publicKey[32] ‖ secret[16] ) → 48+ char string
15
+ */
16
+ import b4a from 'b4a'
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // Constants
20
+ // ---------------------------------------------------------------------------
21
+
22
+ export const MAX_LINE_BYTES = 64 * 1024 // 64 KB hard limit per line
23
+ export const MAX_BODY_BYTES = 8 * 1024 // 8 KB body limit
24
+
25
+ // ---------------------------------------------------------------------------
26
+ // Inline base58
27
+ // ---------------------------------------------------------------------------
28
+
29
+ const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
30
+ const BASE = 58n
31
+
32
+ function base58Encode (buf) {
33
+ if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
34
+ let num = BigInt('0x' + buf.toString('hex') || '0')
35
+ let str = ''
36
+ while (num > 0n) {
37
+ str = ALPHABET[Number(num % BASE)] + str
38
+ num = num / BASE
39
+ }
40
+ // Leading zero bytes → '1'
41
+ for (const byte of buf) {
42
+ if (byte !== 0) break
43
+ str = '1' + str
44
+ }
45
+ return str
46
+ }
47
+
48
+ function base58Decode (str) {
49
+ let num = 0n
50
+ for (const ch of str) {
51
+ const idx = ALPHABET.indexOf(ch)
52
+ if (idx < 0) throw new Error(`Invalid base58 character: ${ch}`)
53
+ num = num * BASE + BigInt(idx)
54
+ }
55
+ // Count leading '1's → leading zero bytes
56
+ let leadingZeros = 0
57
+ for (const ch of str) {
58
+ if (ch !== '1') break
59
+ leadingZeros++
60
+ }
61
+ const hex = num.toString(16).padStart(2, '0')
62
+ const paddedHex = (hex.length % 2 ? '0' : '') + hex
63
+ const bytes = Buffer.from(paddedHex, 'hex')
64
+ return Buffer.concat([Buffer.alloc(leadingZeros), bytes])
65
+ }
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // Invite code encode / decode
69
+ // ---------------------------------------------------------------------------
70
+
71
+ /** Build a one-time invite code from a public key (32 bytes) and a 16-byte secret. */
72
+ export function encodeInvite (publicKey, secret) {
73
+ const pk = b4a.isBuffer(publicKey) ? publicKey : b4a.from(publicKey, 'hex')
74
+ const sec = b4a.isBuffer(secret) ? secret : b4a.from(secret, 'hex')
75
+ if (pk.length !== 32) throw new Error('publicKey must be 32 bytes')
76
+ if (sec.length !== 16) throw new Error('secret must be 16 bytes')
77
+ return base58Encode(Buffer.concat([pk, sec]))
78
+ }
79
+
80
+ /** Parse a one-time invite code. Returns { publicKey<Buffer>, secret<Buffer> }. */
81
+ export function decodeInvite (code) {
82
+ const buf = base58Decode(code)
83
+ if (buf.length !== 48) throw new Error(`Invalid invite code (expected 48 bytes, got ${buf.length})`)
84
+ return {
85
+ publicKey: buf.slice(0, 32),
86
+ secret: buf.slice(32, 48),
87
+ }
88
+ }
89
+
90
+ // ---------------------------------------------------------------------------
91
+ // Frame encode / decode
92
+ // ---------------------------------------------------------------------------
93
+
94
+ /** Serialise a frame object to a newline-terminated JSON string. */
95
+ export function encodeFrame (frame) {
96
+ return JSON.stringify(frame) + '\n'
97
+ }
98
+
99
+ /**
100
+ * Parse and validate a single JSON line (without the trailing newline).
101
+ * Throws if invalid or violates limits.
102
+ */
103
+ export function parseFrame (line) {
104
+ if (Buffer.byteLength(line, 'utf8') > MAX_LINE_BYTES) {
105
+ throw new Error('Frame too large')
106
+ }
107
+ let frame
108
+ try {
109
+ frame = JSON.parse(line)
110
+ } catch {
111
+ throw new Error('Malformed JSON frame')
112
+ }
113
+ if (!frame || typeof frame.type !== 'string') {
114
+ throw new Error('Frame missing type')
115
+ }
116
+ switch (frame.type) {
117
+ case 'hello':
118
+ if (typeof frame.name !== 'string') throw new Error('hello: missing name')
119
+ break
120
+ case 'msg':
121
+ if (typeof frame.seq !== 'number') throw new Error('msg: missing seq')
122
+ if (typeof frame.ts !== 'number') throw new Error('msg: missing ts')
123
+ if (typeof frame.body !== 'string') throw new Error('msg: missing body')
124
+ if (Buffer.byteLength(frame.body, 'utf8') > MAX_BODY_BYTES) {
125
+ throw new Error('msg: body too large')
126
+ }
127
+ break
128
+ case 'ack':
129
+ if (typeof frame.upTo !== 'number') throw new Error('ack: missing upTo')
130
+ break
131
+ default:
132
+ throw new Error(`Unknown frame type: ${frame.type}`)
133
+ }
134
+ return frame
135
+ }
136
+
137
+ // ---------------------------------------------------------------------------
138
+ // Line assembler (stateful, feeds raw chunk data)
139
+ // ---------------------------------------------------------------------------
140
+
141
+ /**
142
+ * Create a line assembler that buffers incoming data and emits complete lines.
143
+ *
144
+ * Usage:
145
+ * const la = createLineAssembler({ onLine, onError })
146
+ * socket.on('data', chunk => la.push(chunk))
147
+ *
148
+ * onLine(line: string) — called with each '\n'-terminated line (without '\n')
149
+ * onError(err) — called on oversized line or other error; caller should close the socket
150
+ */
151
+ export function createLineAssembler ({ onLine, onError }) {
152
+ let buf = ''
153
+ let totalBytes = 0
154
+
155
+ return {
156
+ push (chunk) {
157
+ const str = typeof chunk === 'string' ? chunk : b4a.toString(chunk, 'utf8')
158
+ totalBytes += Buffer.byteLength(str, 'utf8')
159
+
160
+ if (totalBytes > MAX_LINE_BYTES) {
161
+ onError(new Error('Line too large; dropping connection'))
162
+ return
163
+ }
164
+
165
+ buf += str
166
+ let idx
167
+ while ((idx = buf.indexOf('\n')) !== -1) {
168
+ const line = buf.slice(0, idx)
169
+ buf = buf.slice(idx + 1)
170
+ totalBytes = Buffer.byteLength(buf, 'utf8')
171
+ onLine(line)
172
+ }
173
+ },
174
+ }
175
+ }
package/src/store.js ADDED
@@ -0,0 +1,168 @@
1
+ /**
2
+ * src/store.js — atomic JSON persistence for ~/.terminalchat/
3
+ *
4
+ * All writes go to a temp file first, then rename() so readers never see
5
+ * a partial write. History files are append-only (.jsonl) and don't use
6
+ * the atomic rename path.
7
+ *
8
+ * createStore(baseDir) returns a per-instance store bound to baseDir so
9
+ * multiple engines in the same process never step on each other's data.
10
+ * The module-level convenience exports (identity/friends/…) still read
11
+ * from TCHAT_DATA_DIR for the default single-engine case.
12
+ */
13
+ import {
14
+ readFileSync, writeFileSync, mkdirSync, renameSync,
15
+ existsSync, chmodSync, appendFileSync, createReadStream,
16
+ } from 'node:fs'
17
+ import { resolve, dirname } from 'node:path'
18
+ import { homedir } from 'node:os'
19
+ import { randomBytes } from 'node:crypto'
20
+ import { createInterface } from 'node:readline'
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // Low-level helpers (take an explicit baseDir)
24
+ // ---------------------------------------------------------------------------
25
+
26
+ function _resolve (baseDir, sub) {
27
+ return sub ? resolve(baseDir, sub) : baseDir
28
+ }
29
+
30
+ function _ensure (baseDir) {
31
+ mkdirSync(_resolve(baseDir, ''), { recursive: true })
32
+ mkdirSync(_resolve(baseDir, 'history'), { recursive: true })
33
+ }
34
+
35
+ function _readJSON (baseDir, relPath, defaultValue = null) {
36
+ const full = _resolve(baseDir, relPath)
37
+ if (!existsSync(full)) return defaultValue
38
+ return JSON.parse(readFileSync(full, 'utf8'))
39
+ }
40
+
41
+ function _writeJSON (baseDir, relPath, data, mode = null) {
42
+ const full = _resolve(baseDir, relPath)
43
+ mkdirSync(dirname(full), { recursive: true })
44
+ const tmp = `${full}.${randomBytes(4).toString('hex')}.tmp`
45
+ writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8')
46
+ if (mode !== null) chmodSync(tmp, mode)
47
+ renameSync(tmp, full)
48
+ }
49
+
50
+ function _appendHistory (baseDir, friendKeyHex, entry) {
51
+ const full = _resolve(baseDir, `history/${friendKeyHex}.jsonl`)
52
+ mkdirSync(dirname(full), { recursive: true })
53
+ appendFileSync(full, JSON.stringify(entry) + '\n', 'utf8')
54
+ }
55
+
56
+ async function _readHistory (baseDir, friendKeyHex, n = 50) {
57
+ const full = _resolve(baseDir, `history/${friendKeyHex}.jsonl`)
58
+ if (!existsSync(full)) return []
59
+ const lines = []
60
+ const rl = createInterface({ input: createReadStream(full, 'utf8'), crlfDelay: Infinity })
61
+ for await (const line of rl) {
62
+ if (!line.trim()) continue
63
+ try { lines.push(JSON.parse(line)) } catch { /* skip corrupt */ }
64
+ if (lines.length > n) lines.shift()
65
+ }
66
+ return lines
67
+ }
68
+
69
+ // ---------------------------------------------------------------------------
70
+ // createStore — per-instance factory (use this in Engine)
71
+ // ---------------------------------------------------------------------------
72
+
73
+ /**
74
+ * Returns a store object bound to `baseDir`. Each Engine should create its
75
+ * own store so concurrent engines in the same process don't interfere.
76
+ */
77
+ export function createStore (baseDir) {
78
+ return {
79
+ baseDir,
80
+ ensure: () => _ensure(baseDir),
81
+ readJSON: (p, def) => _readJSON(baseDir, p, def),
82
+ writeJSON: (p, d, m) => _writeJSON(baseDir, p, d, m),
83
+ appendHistory: (k, e) => _appendHistory(baseDir, k, e),
84
+ readHistory: (k, n) => _readHistory(baseDir, k, n),
85
+
86
+ identity: {
87
+ load: () => _readJSON(baseDir, 'identity.json', null),
88
+ save: (kp) => _writeJSON(baseDir, 'identity.json', kp, 0o600),
89
+ },
90
+ friends: {
91
+ load: () => _readJSON(baseDir, 'friends.json', {}),
92
+ save: (d) => _writeJSON(baseDir, 'friends.json', d),
93
+ },
94
+ invites: {
95
+ load: () => _readJSON(baseDir, 'invites.json', {}),
96
+ save: (d) => _writeJSON(baseDir, 'invites.json', d),
97
+ },
98
+ outbox: {
99
+ load: () => _readJSON(baseDir, 'outbox.json', {}),
100
+ save: (d) => _writeJSON(baseDir, 'outbox.json', d),
101
+ },
102
+ state: {
103
+ load: () => _readJSON(baseDir, 'state.json', { nextSeq: {}, ackedUpTo: {} }),
104
+ save: (d) => _writeJSON(baseDir, 'state.json', d),
105
+ },
106
+ }
107
+ }
108
+
109
+ // ---------------------------------------------------------------------------
110
+ // Default base directory (falls back to TCHAT_DATA_DIR or ~/.terminalchat)
111
+ // ---------------------------------------------------------------------------
112
+
113
+ function defaultBase () {
114
+ return process.env.TCHAT_DATA_DIR ?? resolve(homedir(), '.terminalchat')
115
+ }
116
+
117
+ // ---------------------------------------------------------------------------
118
+ // Module-level convenience exports (use TCHAT_DATA_DIR, single-engine default)
119
+ // ---------------------------------------------------------------------------
120
+
121
+ export function dataDir (sub = '') {
122
+ return _resolve(defaultBase(), sub)
123
+ }
124
+
125
+ export function ensureDataDir () {
126
+ _ensure(defaultBase())
127
+ }
128
+
129
+ export function readJSON (relPath, defaultValue = null) {
130
+ return _readJSON(defaultBase(), relPath, defaultValue)
131
+ }
132
+
133
+ export function writeJSON (relPath, data, mode = null) {
134
+ _writeJSON(defaultBase(), relPath, data, mode)
135
+ }
136
+
137
+ export function appendHistory (friendKeyHex, entry) {
138
+ _appendHistory(defaultBase(), friendKeyHex, entry)
139
+ }
140
+
141
+ export async function readHistory (friendKeyHex, n = 50) {
142
+ return _readHistory(defaultBase(), friendKeyHex, n)
143
+ }
144
+
145
+ export const identity = {
146
+ load: () => readJSON('identity.json', null),
147
+ save: (kp) => writeJSON('identity.json', kp, 0o600),
148
+ }
149
+
150
+ export const friends = {
151
+ load: () => readJSON('friends.json', {}),
152
+ save: (data) => writeJSON('friends.json', data),
153
+ }
154
+
155
+ export const invites = {
156
+ load: () => readJSON('invites.json', {}),
157
+ save: (data) => writeJSON('invites.json', data),
158
+ }
159
+
160
+ export const outbox = {
161
+ load: () => readJSON('outbox.json', {}),
162
+ save: (data) => writeJSON('outbox.json', data),
163
+ }
164
+
165
+ export const state = {
166
+ load: () => readJSON('state.json', { nextSeq: {}, ackedUpTo: {} }),
167
+ save: (data) => writeJSON('state.json', data),
168
+ }
package/src/ui/App.js ADDED
@@ -0,0 +1,68 @@
1
+ import React, { useMemo, useState } from 'react'
2
+ import { Box, Text, useInput, useApp } from 'ink'
3
+ import { Engine } from '../engine.js'
4
+ import { useEngine } from './useEngine.js'
5
+ import { Sidebar } from './Sidebar.js'
6
+ import { ChatPane } from './ChatPane.js'
7
+ import { Actions, AddFriendOverlay, HistoryOverlay, InviteOverlay, JoinOverlay, WhoamiOverlay } from './Overlays.js'
8
+
9
+ const h = React.createElement
10
+
11
+ export default function App ({ engine: providedEngine } = {}) {
12
+ const { exit } = useApp()
13
+ const engine = useMemo(() => providedEngine ?? new Engine(), [providedEngine])
14
+ const state = useEngine(engine)
15
+ const [focus, setFocus] = useState('input')
16
+ const [input, setInput] = useState('')
17
+ const [overlay, setOverlay] = useState(null)
18
+ const [selection, setSelection] = useState(0)
19
+ const selectedKey = state.selectedKey ?? state.friends[selection]?.keyHex
20
+ const friend = state.friends.find(item => item.keyHex === selectedKey)
21
+
22
+ useInput((value, key) => {
23
+ if (key.ctrl && value === 'c') {
24
+ engine.shutdown().finally(exit)
25
+ return
26
+ }
27
+ if (key.escape) { setOverlay(null); return }
28
+ if (overlay) {
29
+ if (overlay === 'actions' && /^[1-5]$/.test(value)) {
30
+ setOverlay(['invite', 'add', 'join', 'whoami', 'history'][Number(value) - 1])
31
+ }
32
+ return
33
+ }
34
+ if (key.tab) { setFocus(previous => previous === 'sidebar' ? 'input' : 'sidebar'); return }
35
+ if (focus === 'sidebar' && (key.upArrow || key.downArrow)) {
36
+ const next = Math.max(0, Math.min(state.friends.length - 1, selection + (key.downArrow ? 1 : -1)))
37
+ setSelection(next)
38
+ state.selectFriend(state.friends[next]?.keyHex)
39
+ }
40
+ if (key.ctrl && value === 'n') setOverlay('actions')
41
+ })
42
+
43
+ const send = body => {
44
+ if (friend && body.trim()) {
45
+ try { engine.sendMessage(friend.keyHex, body) } catch {}
46
+ setInput('')
47
+ }
48
+ }
49
+
50
+ if (!state.ready) return h(Box, { padding: 1 }, h(Text, { color: 'cyan' }, 'Starting TerminalChat…'), state.error && h(Text, { color: 'red' }, ` ${state.error.message}`))
51
+
52
+ let modal = null
53
+ if (overlay === 'actions') modal = h(Actions)
54
+ 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 } })
57
+ if (overlay === 'whoami') modal = h(WhoamiOverlay, { engine })
58
+ if (overlay === 'history' && friend) modal = h(HistoryOverlay, { engine, friendKey: friend.keyHex })
59
+
60
+ 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' })
64
+ ),
65
+ h(Text, { dimColor: true }, state.error ? `Error: ${state.error.message}` : 'Ctrl+N actions · Tab focus · Ctrl+C quit'),
66
+ modal
67
+ )
68
+ }
@@ -0,0 +1,23 @@
1
+ import React from 'react'
2
+ import { Box, Text } from 'ink'
3
+ import TextInput from 'ink-text-input'
4
+
5
+ const h = React.createElement
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
+ ))
15
+ ),
16
+ 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')
22
+ )
23
+ }
@@ -0,0 +1,69 @@
1
+ import React, { useEffect, useState } from 'react'
2
+ import { Box, Text } from 'ink'
3
+ import TextInput from 'ink-text-input'
4
+
5
+ const h = React.createElement
6
+
7
+ function Overlay ({ title, children }) {
8
+ return h(Box, { position: 'absolute', width: '100%', height: '100%', alignItems: 'center', justifyContent: 'center' },
9
+ h(Box, { flexDirection: 'column', borderStyle: 'double', borderColor: 'cyan', paddingX: 2, paddingY: 1, width: 60 },
10
+ h(Text, { bold: true, color: 'cyan' }, title), children
11
+ )
12
+ )
13
+ }
14
+
15
+ export function Actions ({ onChoose }) {
16
+ 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')
20
+ )
21
+ }
22
+
23
+ export function InviteOverlay ({ engine }) {
24
+ return h(Overlay, { title: 'Invite' },
25
+ h(Text, null, engine.createInvite()),
26
+ h(Text, { dimColor: true }, 'Share this code · Esc closes')
27
+ )
28
+ }
29
+
30
+ export function WhoamiOverlay ({ engine }) {
31
+ const identity = engine.whoami()
32
+ return h(Overlay, { title: 'Who am I?' },
33
+ h(Text, null, identity.name),
34
+ h(Text, { wrap: 'wrap' }, identity.publicKey),
35
+ h(Text, { dimColor: true }, 'Esc closes')
36
+ )
37
+ }
38
+
39
+ export function AddFriendOverlay ({ engine, onDone }) {
40
+ const [name, setName] = useState('')
41
+ const [key, setKey] = useState('')
42
+ 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')
48
+ )
49
+ }
50
+
51
+ export function JoinOverlay ({ engine, onJoined, onError }) {
52
+ const [code, setCode] = useState('')
53
+ 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) }
57
+ } }),
58
+ h(Text, { dimColor: true }, 'Enter submits · Esc closes')
59
+ )
60
+ }
61
+
62
+ export function HistoryOverlay ({ engine, friendKey }) {
63
+ const [messages, setMessages] = useState(null)
64
+ useEffect(() => { engine.getHistory(friendKey, 20).then(setMessages) }, [engine, friendKey])
65
+ 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')
68
+ )
69
+ }
@@ -0,0 +1,18 @@
1
+ import React from 'react'
2
+ import { Box, Text } from 'ink'
3
+
4
+ const h = React.createElement
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'),
9
+ 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'))
17
+ )
18
+ }