chat: read receipts (delivered + seen) and persisted active bucket
Read receipts on chat messages — single check for delivered (recipient
polled), double check for seen (recipient opened the thread). Pending
state shows a clock until the relay acks the post.
Relay (relay/):
* bootstrap.php: ALTER TABLE chat_messages ADD COLUMN seen + a
(sender_id, id) index for the sender-side state poll. Migration is
idempotent via PRAGMA table_info.
* routes/chat.php: two new routes
- GET /api/chat/sent?since=N — returns the receipt state (id,
recipient_id, fetched, seen, created_at) for messages the caller
sent. No body — sender already has the plaintext locally.
- POST /api/chat/seen { peer } — marks every message FROM peer TO
caller as seen=1. Idempotent. Frontend calls this when opening
a thread; sender's next /sent poll picks the new state up.
Plugin backend (public/plugins/chat/backend.php):
* schema migration: chat_messages gets `delivered` and `seen` columns
(idempotent), only meaningful for direction='out'.
* /api/chat/send: stores the relay's autoincrement id as `relay_id`
on the local outgoing row so the receipt poll can match against it.
* /api/chat/poll: after the normal incoming pull, also calls
GET /api/chat/sent?since=last_sent_relay_id and updates local
outgoing rows with delivered/seen via UPDATE WHERE relay_id. The
cursor (last_sent_relay_id state value) only advances past rows
whose state is final (seen=1); rows still in flight stay re-pollable.
Response now carries `receipts: <count>` so the frontend can refresh
the open thread when state changes without new incoming.
* /api/chat/read: after the local is_read=1 update, fires a POST to
the relay's /api/chat/seen so the sender gets the double-check.
Silent on failure — the user already saw the messages locally.
* /api/chat/messages: SELECT now includes delivered, seen.
Plugin frontend (public/plugins/chat/chat.js):
* renderThread() appends a receipt icon to outgoing bubbles:
- seen=1 → ph-checks (accent, double check)
- delivered=1, seen=0 → ph-check (muted, single check)
- both 0 → ph-clock (dim, pending)
Incoming messages get nothing.
* pollOnce() refreshes the open thread when receipts > 0 even with
no new incoming, so the icons update in real time while the user
is looking at the thread.
CSS (public/plugins/chat/chat.css):
* .chat-bubble-time becomes flex with gap so timestamp + receipt
icon sit on one line.
* .chat-receipt.pending / .delivered / .seen color tiers.
board: persist active bucket across reloads
* state.js: state.activeBucket initializes from
localStorage.getItem('hyprcrd-active-bucket') || 'all'. New
setActiveBucket(value) helper writes through to localStorage; new
ensureActiveBucketValid() helper falls back to 'all' if the
persisted id no longer exists in state.buckets.
* buckets.js: loadBuckets() calls ensureActiveBucketValid() right
after the API fetch and before renderBar(). All four production
assignments (delete-keep, delete-all, popover entry click, regular
tab click) replaced with setActiveBucket() so the persisted value
stays in sync. Tests still mutate state.activeBucket directly so
they don't touch localStorage.
chore: bump version to 0.9.6
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
9b4869812f
commit
285e3b4abe
8 files changed
+223
-16
No files matched your search
@@ -32,6 +32,17 @@
|
||||
");
|
||||
$db->exec("CREATE INDEX IF NOT EXISTS idx_chat_peer ON chat_messages(peer, sent_at)");
|
||||
$db->exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_chat_relay_id ON chat_messages(relay_id) WHERE relay_id IS NOT NULL");
|
||||
// Read receipts for outgoing messages: `delivered` = recipient polled
|
||||
// (single check), `seen` = recipient opened the thread (double check).
|
||||
// Both filled in via /api/chat/sent receipt-poll on the relay side.
|
||||
$cols = $db->query("PRAGMA table_info(chat_messages)")->fetchAll();
|
||||
$colNames = array_column($cols, 'name');
|
||||
if (!in_array('delivered', $colNames)) {
|
||||
$db->exec("ALTER TABLE chat_messages ADD COLUMN delivered INTEGER NOT NULL DEFAULT 0");
|
||||
}
|
||||
if (!in_array('seen', $colNames)) {
|
||||
$db->exec("ALTER TABLE chat_messages ADD COLUMN seen INTEGER NOT NULL DEFAULT 0");
|
||||
}
|
||||
// Track the largest relay msg id we've ever seen (so the next poll uses since=that)
|
||||
$db->exec("
|
||||
CREATE TABLE IF NOT EXISTS chat_state (
|
||||
@@ -115,7 +126,7 @@ PluginManager::instance()->onApiRoute(function (string $route, string $method) {
|
||||
$peer = trim((string)($_GET['peer'] ?? ''));
|
||||
if ($peer === '') chatJson(['error' => 'peer required'], 400);
|
||||
$db = Database::connect();
|
||||
$stmt = $db->prepare('SELECT id, direction, body, sent_at, is_read FROM chat_messages WHERE peer = :p ORDER BY id ASC LIMIT 500');
|
||||
$stmt = $db->prepare('SELECT id, direction, body, sent_at, is_read, delivered, seen FROM chat_messages WHERE peer = :p ORDER BY id ASC LIMIT 500');
|
||||
$stmt->execute(['p' => $peer]);
|
||||
chatJson(['messages' => $stmt->fetchAll()]);
|
||||
}
|
||||
@@ -164,10 +175,12 @@ PluginManager::instance()->onApiRoute(function (string $route, string $method) {
|
||||
$resData = json_decode($response, true);
|
||||
$relayId = isset($resData['id']) ? (int)$resData['id'] : null;
|
||||
|
||||
// Store the outgoing message locally so the UI can render it immediately
|
||||
// Store the outgoing message locally so the UI can render it
|
||||
// immediately. relay_id is the relay's autoincrement id; the
|
||||
// receipt-poll matches against it to update delivered/seen state.
|
||||
$db = Database::connect();
|
||||
$db->prepare('INSERT INTO chat_messages (peer, direction, body, relay_id, sent_at, is_read) VALUES (:p, "out", :b, NULL, datetime("now"), 1)')
|
||||
->execute(['p' => $peer, 'b' => $body]);
|
||||
$db->prepare('INSERT INTO chat_messages (peer, direction, body, relay_id, sent_at, is_read, delivered, seen) VALUES (:p, "out", :b, :rid, datetime("now"), 1, 0, 0)')
|
||||
->execute(['p' => $peer, 'b' => $body, 'rid' => $relayId]);
|
||||
chatJson(['ok' => true, 'id' => (int)$db->lastInsertId()]);
|
||||
}
|
||||
|
||||
@@ -218,7 +231,58 @@ PluginManager::instance()->onApiRoute(function (string $route, string $method) {
|
||||
}
|
||||
if ($maxId > $since) chatSetState('last_relay_id', $maxId);
|
||||
|
||||
chatJson(['ok' => true, 'new' => $newCount]);
|
||||
// ── Receipt poll for our SENT messages ──────────────────
|
||||
// Pulls fetched/seen state for everything we've sent. Updates
|
||||
// local outgoing rows by relay_id. Uses an independent `since`
|
||||
// cursor so we keep getting state changes even on rows we
|
||||
// already saw before.
|
||||
$sentSince = (int)chatGetState('last_sent_relay_id', 0);
|
||||
$ch2 = curl_init(rtrim($r['url'], '/') . '/api/chat/sent?since=' . $sentSince);
|
||||
curl_setopt_array($ch2, [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'X-Relay-User: ' . $r['user'],
|
||||
'X-Relay-Key: ' . $r['key'],
|
||||
],
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
]);
|
||||
$resp2 = curl_exec($ch2);
|
||||
$st2 = curl_getinfo($ch2, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch2);
|
||||
$receiptUpdates = 0;
|
||||
if ($st2 === 200) {
|
||||
$sentData = json_decode($resp2, true) ?: [];
|
||||
$receipts = $sentData['receipts'] ?? [];
|
||||
$sentMaxId = (int)($sentData['max_id'] ?? $sentSince);
|
||||
$upd = $db->prepare('UPDATE chat_messages SET delivered = :d, seen = :s WHERE relay_id = :rid AND direction = "out"');
|
||||
foreach ($receipts as $rcpt) {
|
||||
$upd->execute([
|
||||
'd' => (int)($rcpt['fetched'] ?? 0),
|
||||
's' => (int)($rcpt['seen'] ?? 0),
|
||||
'rid' => (int)$rcpt['id'],
|
||||
]);
|
||||
$receiptUpdates += $upd->rowCount();
|
||||
}
|
||||
// Cursor only advances when EVERY row's state is final (seen=1).
|
||||
// Otherwise we need to keep re-polling those rows for updates.
|
||||
// Cheap implementation: if every row in this batch is seen, bump
|
||||
// cursor to maxId; else keep polling from the lowest non-seen id.
|
||||
$allSeen = true;
|
||||
$minPending = $sentMaxId;
|
||||
foreach ($receipts as $rcpt) {
|
||||
if ((int)($rcpt['seen'] ?? 0) !== 1) {
|
||||
$allSeen = false;
|
||||
if ((int)$rcpt['id'] - 1 < $minPending) $minPending = (int)$rcpt['id'] - 1;
|
||||
}
|
||||
}
|
||||
if ($allSeen && $sentMaxId > $sentSince) {
|
||||
chatSetState('last_sent_relay_id', $sentMaxId);
|
||||
} else if (!$allSeen && $minPending > $sentSince) {
|
||||
chatSetState('last_sent_relay_id', $minPending);
|
||||
}
|
||||
}
|
||||
|
||||
chatJson(['ok' => true, 'new' => $newCount, 'receipts' => $receiptUpdates]);
|
||||
}
|
||||
|
||||
if ($route === '/api/chat/read' && $method === 'POST') {
|
||||
@@ -228,6 +292,28 @@ PluginManager::instance()->onApiRoute(function (string $route, string $method) {
|
||||
$db = Database::connect();
|
||||
$db->prepare('UPDATE chat_messages SET is_read = 1 WHERE peer = :p AND direction = "in" AND is_read = 0')
|
||||
->execute(['p' => $peer]);
|
||||
|
||||
// Tell the relay this peer's messages have been seen by us so the
|
||||
// peer's next /api/chat/sent poll picks up the double-check state.
|
||||
$r = chatRelaySettings();
|
||||
if ($r['url'] && $r['user'] && $r['key']) {
|
||||
$ch = curl_init(rtrim($r['url'], '/') . '/api/chat/seen');
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => json_encode(['peer' => $peer]),
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'Content-Type: application/json',
|
||||
'X-Relay-User: ' . $r['user'],
|
||||
'X-Relay-Key: ' . $r['key'],
|
||||
],
|
||||
CURLOPT_TIMEOUT => 5,
|
||||
]);
|
||||
curl_exec($ch);
|
||||
curl_close($ch);
|
||||
// Failures are silent — the user already saw the messages
|
||||
// locally, the relay state is just lagging.
|
||||
}
|
||||
chatJson(['ok' => true]);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user