diff --git a/config.php b/config.php index 495c345..03cb64e 100644 --- a/config.php +++ b/config.php @@ -1,7 +1,7 @@ l.status === 'error'); - const msg = `pushed:${total.pushed} pulled:${total.pulled} del:${total.deleted}${rp ? ' relay:' + rp : ''}`; + const msg = `pushed:${caldavStats.pushed} pulled:${caldavStats.pulled + rp} del:${caldavStats.deleted}${rp ? ' relay:' + rp : ''}`; if (syncStatus) { syncStatus.textContent = msg; syncStatus.style.color = hasErrors ? 'var(--t-danger)' : 'var(--t-accent)'; } await window._reloadAll?.(); showLog(allLog); - showSyncNotification(total); + showSyncNotification('CalDAV', 'ph-cloud-arrow-down', caldavStats); + showSyncNotification('Relay', 'ph-broadcast', relayStats); } else { if (syncStatus) { syncStatus.textContent = res.error || 'sync failed'; syncStatus.style.color = 'var(--t-danger)'; } } @@ -99,19 +101,29 @@ export function autoSync() { // ── Sync notifications ────────────────────────────────────────── -function showSyncNotification(stats) { +/** Per-source sync toast. Caller picks the label ("CalDAV" vs "Relay") + * and icon so the user knows which pipeline just finished, instead of + * the old always-CalDAV banner that lumped relay traffic in silently. */ +let syncNoteOffset = 0; +function showSyncNotification(label, icon, stats) { const s = stats || {}; const parts = []; - if (s.pulled) parts.push(`${s.pulled} received`); - if (s.pushed) parts.push(`${s.pushed} sent`); + if (s.pulled) parts.push(`${s.pulled} received`); + if (s.pushed) parts.push(`${s.pushed} sent`); if (s.deleted) parts.push(`${s.deleted} deleted`); if (!parts.length) return; + const bottom = 60 + syncNoteOffset * 48; + syncNoteOffset++; const note = document.createElement('div'); - note.style.cssText = 'position:fixed;bottom:60px;right:16px;z-index:200;background:var(--t-surface);border:1px solid var(--t-accent);border-radius:4px;padding:10px 14px;box-shadow:0 4px 20px rgba(0,0,0,0.4);max-width:300px;'; - note.innerHTML = `
CalDAV: ${parts.join(', ')}
`; + note.style.cssText = `position:fixed;bottom:${bottom}px;right:16px;z-index:200;background:var(--t-surface);border:1px solid var(--t-accent);border-radius:4px;padding:10px 14px;box-shadow:0 4px 20px rgba(0,0,0,0.4);max-width:300px;`; + note.innerHTML = `
${label}: ${parts.join(', ')}
`; document.body.appendChild(note); - setTimeout(() => { note.style.transition = 'opacity 0.3s'; note.style.opacity = '0'; setTimeout(() => note.remove(), 350); }, 4000); + setTimeout(() => { + note.style.transition = 'opacity 0.3s'; + note.style.opacity = '0'; + setTimeout(() => { note.remove(); syncNoteOffset = Math.max(0, syncNoteOffset - 1); }, 350); + }, 4000); } // One toast per incoming sync event: "alice synced: Card Title". diff --git a/public/plugins/tests/board-find-replace.test.js b/public/plugins/tests/board-find-replace.test.js index 6f099fb..8c90afb 100644 --- a/public/plugins/tests/board-find-replace.test.js +++ b/public/plugins/tests/board-find-replace.test.js @@ -78,14 +78,17 @@ describe('Search: Find/Replace', () => { const okBtn = document.getElementById('dialog-ok'); if (okBtn) click(okBtn); - // Poll until the replace has actually persisted + // Poll until both replaces have persisted. Budget is generous + // (~10s) because a cold PHP run plus two sequential PATCH calls + // can easily blow past the original 4-second window — the retry + // always passes because opcache + SQLite WAL are warm by then. let updated1, updated2; - for (let i = 0; i < 40; i++) { + for (let i = 0; i < 100; i++) { await sleep(100); updated1 = await getCard(c1.id); - if (updated1?.body === 'goodbye world goodbye') break; + updated2 = await getCard(c2.id); + if (updated1?.body === 'goodbye world goodbye' && updated2?.body === 'goodbye there') break; } - updated2 = await getCard(c2.id); expect(updated1.body).toBe('goodbye world goodbye'); expect(updated2.body).toBe('goodbye there'); }); diff --git a/relay/inc/routes/chat.php b/relay/inc/routes/chat.php index 6629195..afcc4bc 100644 --- a/relay/inc/routes/chat.php +++ b/relay/inc/routes/chat.php @@ -23,14 +23,16 @@ if ($route === '/api/chat/threads' && $method === 'GET' && $sessionTenant) { $interKey = getInterTenantKey($db, $MASTER_KEY); if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set'], 500); $myId = $sessionTenant['id']; + // 1:1 threads: my 1:1 messages grouped by peer username. Group sends + // (room_uid IS NOT NULL) are excluded so they don't surface here. $stmt = $db->prepare(' SELECT sender_username AS peer, MAX(created_at) AS last_at, COUNT(*) AS count - FROM chat_messages WHERE recipient_id = :r + FROM chat_messages WHERE recipient_id = :r AND room_uid IS NULL GROUP BY sender_username UNION SELECT t.username AS peer, MAX(cm.created_at) AS last_at, COUNT(*) AS count FROM chat_messages cm JOIN tenants t ON t.id = cm.recipient_id - WHERE cm.sender_id = :s AND cm.recipient_id != :s2 + WHERE cm.sender_id = :s AND cm.recipient_id != :s2 AND cm.room_uid IS NULL GROUP BY t.username '); $stmt->execute(['r' => $myId, 's' => $myId, 's2' => $myId]); @@ -42,29 +44,85 @@ if ($route === '/api/chat/threads' && $method === 'GET' && $sessionTenant) { $threads[$peer]['count'] += (int)$row['count']; if ($row['last_at'] > $threads[$peer]['last_at']) $threads[$peer]['last_at'] = $row['last_at']; } - usort($threads, fn($a, $b) => strcmp($b['last_at'], $a['last_at'])); - // Add unread count per peer foreach ($threads as &$t) { - $stmt2 = $db->prepare('SELECT COUNT(*) FROM chat_messages WHERE recipient_id = :r AND sender_username = :p AND seen = 0'); + $stmt2 = $db->prepare('SELECT COUNT(*) FROM chat_messages WHERE recipient_id = :r AND sender_username = :p AND seen = 0 AND room_uid IS NULL'); $stmt2->execute(['r' => $myId, 'p' => $t['peer']]); $t['unread'] = (int)$stmt2->fetchColumn(); } - jsonResponse(array_values($threads)); + unset($t); + // Group rooms the caller is a member of. The UI renders these as + // first-class threads alongside 1:1 conversations; room_uid marks them + // so the client can key off the right identifier. + $roomStmt = $db->prepare(' + SELECT r.uid, r.name, r.owner_username, + (SELECT MAX(created_at) FROM chat_messages cm WHERE cm.room_uid = r.uid) AS last_at, + (SELECT COUNT(*) FROM chat_messages cm WHERE cm.room_uid = r.uid) AS count + FROM chat_rooms r + INNER JOIN chat_room_members m ON m.room_uid = r.uid + WHERE m.tenant_id = :tid + ORDER BY last_at DESC + '); + $roomStmt->execute(['tid' => $myId]); + $roomThreads = []; + foreach ($roomStmt->fetchAll() as $r) { + $roomThreads[] = [ + 'room_uid' => $r['uid'], + 'name' => $r['name'], + 'owner' => $r['owner_username'], + 'last_at' => $r['last_at'] ?? '', + 'count' => (int)$r['count'], + 'unread' => 0, // rooms have no per-recipient seen state yet + ]; + } + $combined = array_merge(array_values($threads), $roomThreads); + usort($combined, fn($a, $b) => strcmp($b['last_at'] ?? '', $a['last_at'] ?? '')); + jsonResponse($combined); } if ($route === '/api/chat/history' && $method === 'GET' && $sessionTenant) { - $peer = trim($_GET['peer'] ?? ''); - if (!$peer) jsonResponse(['error' => 'peer required'], 400); + $peer = trim($_GET['peer'] ?? ''); + $roomUid = trim($_GET['room_uid'] ?? ''); + if ($peer === '' && $roomUid === '') jsonResponse(['error' => 'peer or room_uid required'], 400); $interKey = getInterTenantKey($db, $MASTER_KEY); if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set'], 500); $myId = $sessionTenant['id']; + + if ($roomUid !== '') { + // Group room: caller must be a current member. + $check = $db->prepare('SELECT 1 FROM chat_room_members WHERE room_uid = :r AND tenant_id = :t'); + $check->execute(['r' => $roomUid, 't' => $myId]); + if (!$check->fetchColumn()) jsonResponse(['error' => 'not a member of this room'], 403); + $stmt = $db->prepare(' + SELECT id, sender_id, sender_username, body, created_at + FROM chat_messages + WHERE room_uid = :r + ORDER BY created_at ASC LIMIT 500 + '); + $stmt->execute(['r' => $roomUid]); + $rows = $stmt->fetchAll(); + $out = []; + foreach ($rows as $row) { + $out[] = [ + 'id' => (int)$row['id'], + 'from' => $row['sender_username'], + 'mine' => (int)$row['sender_id'] === $myId, + 'body' => clientDecrypt($row['body'] ?? '', $interKey), + 'created_at' => $row['created_at'], + 'seen' => 1, // group rooms don't track per-recipient seen + ]; + } + jsonResponse($out); + } + + // 1:1 fallback $peerTenant = getTenantByUsername($db, $peer); - if (!$peerTenant) jsonResponse(['error' => 'unknown peer'], 404); + if (!$peerTenant) jsonResponse(['error' => 'peer not found'], 404); $peerId = $peerTenant['id']; $stmt = $db->prepare(' SELECT id, sender_id, sender_username, body, created_at, seen FROM chat_messages - WHERE (recipient_id = :r AND sender_id = :p) OR (recipient_id = :p2 AND sender_id = :s) + WHERE room_uid IS NULL + AND ((recipient_id = :r AND sender_id = :p) OR (recipient_id = :p2 AND sender_id = :s)) ORDER BY created_at ASC LIMIT 500 '); $stmt->execute(['r' => $myId, 'p' => $peerId, 'p2' => $peerId, 's' => $myId]); @@ -90,13 +148,30 @@ if ($route === '/api/chat/send' && $method === 'POST' && $sessionTenant) { $input = json_decode(file_get_contents('php://input'), true) ?: []; $body = trim((string)($input['body'] ?? '')); $recipientName = trim((string)($input['recipient'] ?? '')); + $roomUid = trim((string)($input['room_uid'] ?? '')); if ($body === '') jsonResponse(['error' => 'body required'], 400); - if ($recipientName === '') jsonResponse(['error' => 'recipient required'], 400); - $recipient = getTenantByUsername($db, $recipientName); - if (!$recipient) jsonResponse(['error' => 'recipient not found'], 404); + if ($recipientName === '' && $roomUid === '') jsonResponse(['error' => 'recipient or room_uid required'], 400); $interKey = getInterTenantKey($db, $MASTER_KEY); if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set'], 500); $stored = clientEncrypt($body, $interKey); + + if ($roomUid !== '') { + // Group post: verify membership. `recipient_id` NOT NULL because of + // the FK, so we park the sender's own id there — GET filters on + // room_uid, never recipient_id, for group rows. + $check = $db->prepare('SELECT 1 FROM chat_room_members WHERE room_uid = :r AND tenant_id = :t'); + $check->execute(['r' => $roomUid, 't' => $sessionTenant['id']]); + if (!$check->fetchColumn()) jsonResponse(['error' => 'not a member of this room'], 403); + $db->prepare('INSERT INTO chat_messages (recipient_id, sender_id, sender_username, room_uid, body, persistent) VALUES (:me, :s, :sn, :ru, :b, 1)') + ->execute([ + 'me' => $sessionTenant['id'], 's' => $sessionTenant['id'], + 'sn' => $sessionTenant['username'], 'ru' => $roomUid, 'b' => $stored, + ]); + jsonResponse(['ok' => true, 'id' => (int)$db->lastInsertId(), 'room_uid' => $roomUid]); + } + + $recipient = getTenantByUsername($db, $recipientName); + if (!$recipient) jsonResponse(['error' => 'recipient not found'], 404); $db->prepare('INSERT INTO chat_messages (recipient_id, sender_id, sender_username, body) VALUES (:r, :s, :sn, :b)') ->execute(['r' => $recipient['id'], 's' => $sessionTenant['id'], 'sn' => $sessionTenant['username'], 'b' => $stored]); jsonResponse(['ok' => true, 'id' => (int)$db->lastInsertId()]); diff --git a/relay/ui/app.js b/relay/ui/app.js index 8e5ce0d..75e6e95 100644 --- a/relay/ui/app.js +++ b/relay/ui/app.js @@ -857,61 +857,88 @@ document.addEventListener('visibilitychange', () => { }); // ── Chat ── +// +// Two thread kinds live side by side: 1:1 (identified by peer username) +// and group rooms (identified by room_uid). The UI keeps a single +// "active thread" descriptor and switches the fetch / send shape based +// on which field is populated. -let chatActivePeer = null; +let chatActive = null; // { kind: 'peer' | 'room', peer?, roomUid?, label } let chatPollHandle = null; function startChatPoll() { stopChatPoll(); chatPollHandle = setInterval(() => { loadChatThreads(true); - if (chatActivePeer) loadChatHistory(chatActivePeer, true); + if (chatActive) loadChatHistory(chatActive, true); }, 5000); } function stopChatPoll() { if (chatPollHandle) { clearInterval(chatPollHandle); chatPollHandle = null; } } +function isSameActive(a, b) { + if (!a || !b) return false; + return a.kind === b.kind && (a.peer === b.peer) && (a.roomUid === b.roomUid); +} + async function loadChatThreads(quiet = false) { const list = $('chat-thread-list'); if (!list) return; const threads = await api('api/chat/threads') || []; if (!Array.isArray(threads)) return; - // If no threads and not quiet, show empty state if (!threads.length && !quiet) { list.innerHTML = `
no conversations yet
`; return; } if (!threads.length) return; - list.innerHTML = threads.map(t => ` -
- -
-
${escapeHtml(t.peer)}
-
${formatRelTime(t.last_at)}
-
- ${t.unread ? `${t.unread}` : ''} -
- `).join(''); + list.innerHTML = threads.map(t => { + const isRoom = !!t.room_uid; + const desc = isRoom + ? { kind: 'room', roomUid: t.room_uid, label: t.name || t.room_uid } + : { kind: 'peer', peer: t.peer, label: t.peer }; + const active = isSameActive(chatActive, desc); + const icon = isRoom ? 'ph-users-three' : 'ph-user-circle'; + const tag = isRoom ? 'room' : null; + const attrs = isRoom + ? `data-kind="room" data-room-uid="${escapeHtml(t.room_uid)}" data-label="${escapeHtml(desc.label)}"` + : `data-kind="peer" data-peer="${escapeHtml(t.peer)}"`; + return ` +
+ +
+
${escapeHtml(desc.label)}${tag ? ` ${tag}` : ''}
+
${escapeHtml(formatRelTime(t.last_at))}
+
+ ${t.unread ? `${t.unread}` : ''} +
`; + }).join(''); list.querySelectorAll('.chat-thread').forEach(el => { el.addEventListener('click', () => { - chatActivePeer = el.dataset.peer; + if (el.dataset.kind === 'room') { + chatActive = { kind: 'room', roomUid: el.dataset.roomUid, label: el.dataset.label }; + } else { + chatActive = { kind: 'peer', peer: el.dataset.peer, label: el.dataset.peer }; + } loadChatThreads(true); - loadChatHistory(chatActivePeer); + loadChatHistory(chatActive); $('chat-input-bar')?.classList.remove('hidden'); - $('chat-peer-name').textContent = chatActivePeer; + $('chat-peer-name').textContent = chatActive.label; $('chat-input')?.focus(); }); }); } -async function loadChatHistory(peer, quiet = false) { +async function loadChatHistory(active, quiet = false) { const container = $('chat-messages'); - if (!container) return; - const messages = await api('api/chat/history?peer=' + encodeURIComponent(peer)) || []; + if (!container || !active) return; + const qs = active.kind === 'room' + ? 'room_uid=' + encodeURIComponent(active.roomUid) + : 'peer=' + encodeURIComponent(active.peer); + const messages = await api('api/chat/history?' + qs) || []; if (!Array.isArray(messages)) return; const wasAtBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 20; @@ -921,8 +948,13 @@ async function loadChatHistory(peer, quiet = false) { return; } + // Group rooms need the sender's name visible above each incoming + // message (there isn't one single peer — it could be anyone in the + // room). 1:1 stays unlabeled for a tighter look. + const showSender = active.kind === 'room'; container.innerHTML = messages.map(m => `
+ ${showSender && !m.mine ? `
${escapeHtml(m.from)}
` : ''}
${escapeHtml(m.body)}
${formatChatTime(m.created_at)}${m.mine && m.seen ? ' ' : ''}
@@ -932,18 +964,20 @@ async function loadChatHistory(peer, quiet = false) { container.scrollTop = container.scrollHeight; } - // Refresh thread list to clear unread badges if (!quiet) loadChatThreads(true); } async function sendChatMessage() { const input = $('chat-input'); - if (!input || !chatActivePeer) return; + if (!input || !chatActive) return; const body = input.value.trim(); if (!body) return; input.value = ''; - await api('api/chat/send', { method: 'POST', body: { body, recipient: chatActivePeer } }); - loadChatHistory(chatActivePeer); + const payload = chatActive.kind === 'room' + ? { body, room_uid: chatActive.roomUid } + : { body, recipient: chatActive.peer }; + await api('api/chat/send', { method: 'POST', body: payload }); + loadChatHistory(chatActive); loadChatThreads(true); }