v2.0.9 — sync toast split, relay group chat UI, find/replace flaky fix

- sync: the post-sync toast lumped relay pulls into the CalDAV stats
  and always labelled the banner "CalDAV". Split into two separate
  toasts (CalDAV cloud-arrow + Relay broadcast icon), each only shown
  when its numbers are non-zero. Banners now stack vertically so both
  can appear together on a sync that pulled on both sides.
- relay UI: the session chat view was 1:1-only. Group rooms (which
  the client API already supports) now surface as first-class threads
  in the sidebar — sorted chronologically with 1:1 peers, tagged
  "ROOM", with a users-three icon. Sending posts to `room_uid`
  instead of `recipient`; history shows the sender name above each
  incoming message so it's clear who's talking in the room.
  Relay backend: `/api/chat/threads` returns rooms alongside 1:1
  threads; `/api/chat/history` accepts `?room_uid=`; `/api/chat/send`
  accepts `room_uid` in the body.
- tests: bump "replace all updates card bodies" poll budget from 4s
  to 10s and poll both updated cards. Flaky on cold runs because a
  fresh PHP worker + SQLite WAL warm-up plus two sequential PATCH
  calls can just barely exceed 4 seconds.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
thandClaude Opus 4.7 committed 2026-04-18 18:28:00 +02:00
1 parent 4aca21812e
commit 87ebcd156b
6 files changed
+175 -51

No files matched your search

+88 -13
View File
@@ -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()]);
+57 -23
View File
@@ -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 = `<div class="chat-empty"><i class="ph ph-chat-circle-dots" style="font-size:24px;"></i><div>no conversations yet</div></div>`;
return;
}
if (!threads.length) return;
list.innerHTML = threads.map(t => `
<div class="chat-thread ${chatActivePeer === t.peer ? 'active' : ''}" data-peer="${escapeHtml(t.peer)}">
<i class="ph ph-user-circle" style="font-size:16px;color:var(--accent2);flex-shrink:0;"></i>
<div style="flex:1;min-width:0;">
<div class="peer-name">${escapeHtml(t.peer)}</div>
<div class="thread-time">${formatRelTime(t.last_at)}</div>
</div>
${t.unread ? `<span class="unread-badge">${t.unread}</span>` : ''}
</div>
`).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 `
<div class="chat-thread ${active ? 'active' : ''}" ${attrs}>
<i class="ph ${icon}" style="font-size:16px;color:var(--accent2);flex-shrink:0;"></i>
<div style="flex:1;min-width:0;">
<div class="peer-name">${escapeHtml(desc.label)}${tag ? ` <span style="font-family:var(--pixel);font-size:8px;color:var(--dim);text-transform:uppercase;letter-spacing:0.5px;margin-left:4px;">${tag}</span>` : ''}</div>
<div class="thread-time">${escapeHtml(formatRelTime(t.last_at))}</div>
</div>
${t.unread ? `<span class="unread-badge">${t.unread}</span>` : ''}
</div>`;
}).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 => `
<div class="chat-msg ${m.mine ? 'mine' : 'theirs'}">
${showSender && !m.mine ? `<div class="msg-from" style="font-family:var(--pixel);font-size:9px;color:var(--accent2);margin-bottom:2px;">${escapeHtml(m.from)}</div>` : ''}
<div>${escapeHtml(m.body)}</div>
<div class="msg-time">${formatChatTime(m.created_at)}${m.mine && m.seen ? ' <i class="ph ph-checks"></i>' : ''}</div>
</div>
@@ -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);
}