Skip to content

Commit 83c02e7

Browse files
ralyodioclaude
andauthored
Replies and reactions, Signal-style (0.3.0, qc 0.2.0) (#279)
Reactions are messages of their own (message_type 'reaction') whose END-TO-END ENCRYPTED body is { target, emoji, remove }: the server learns that someone reacted, never to what or with which emoji. One reaction per person per message; a new one replaces yours, tapping yours removes it. Replies use the existing reply_to_id; the quote is drawn from the reader's own decrypted copy, so quoted text is never stored twice. - src/lib/chat/reactions.js: envelope + foldMessages (reactions into their targets, reply quotes), shared by the web app and qc. - MessageItem: quote block (jumps to the original), reaction chips with OpenEmoji art and who-reacted titles, hover/tap action bar with six quick reactions, the full picker and Reply. MessageList folds and only auto-scrolls on new messages, not on a reaction. - Composer: reply bar (Escape/x cancels), sends replyToId. - Server: messageType allowlist; replyToId must be a message in the same conversation. /api/messages/load returned a chat's OLDEST N messages (ascending + limit); it now returns the newest N (default 200, max 500). - Migration 20261006180000: message_type CHECK allows 'reaction' (applied on dev2). - qc: messages fold reactions/replies, TUI shows quotes and reaction summaries, `qc react <chat> <id> <emoji> [--remove]`, `qc send --reply <id>`, MCP react_to_message + send_message reply_to. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent bfe84e4 commit 83c02e7

22 files changed

Lines changed: 619 additions & 56 deletions

File tree

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "qryptchat-web",
33
"private": true,
4-
"version": "0.2.2",
4+
"version": "0.3.0",
55
"type": "module",
66
"bin": {
77
"qc": "./bin/qc.js",

‎packages/qryptchat/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@profullstack/qryptchat",
3-
"version": "0.1.1",
3+
"version": "0.2.0",
44
"description": "qc: qrypt.chat in your terminal. A full-screen end-to-end encrypted chat client (ML-KEM-1024), plus a scriptable CLI and an MCP server.",
55
"type": "module",
66
"bin": {

‎public/openicon/sprite.svg‎

Lines changed: 3 additions & 0 deletions
Loading

‎scripts/sync-openemoji.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ const iconDir = arg('openicon', resolve(root, '..', 'openicon'));
3535
/** OpenIcon keys used by the composer, the picker tabs and the file chips. */
3636
export const ICONS = [
3737
'smile', 'paperclip', 'send', 'search', 'close', 'clock', 'users', 'leaf', 'coffee',
38-
'globe', 'trophy', 'lightbulb', 'hash', 'flag',
38+
'globe', 'trophy', 'lightbulb', 'hash', 'flag', 'reply', 'heart', 'plus-circle',
3939
];
4040

4141
for (const [label, dir, file] of [

‎src/app/api/messages/load/route.js‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ function normalizeConversationId(conversationId) {
1313

1414
export const POST = withAuth(async ({ request, locals }) => {
1515
try {
16-
const { conversationId: rawConversationId, limit = 50, before } = await request.json();
16+
const { conversationId: rawConversationId, limit = 200, before } = await request.json();
1717
const conversationId = normalizeConversationId(rawConversationId);
1818

1919
if (!conversationId) {
@@ -22,7 +22,7 @@ export const POST = withAuth(async ({ request, locals }) => {
2222

2323
const normalizedLimit = normalizeMessageLimit(limit);
2424
if (normalizedLimit === null) {
25-
return NextResponse.json({ error: 'limit must be an integer between 1 and 100' }, { status: 400 });
25+
return NextResponse.json({ error: 'limit must be an integer between 1 and 500' }, { status: 400 });
2626
}
2727

2828
const { supabase, user: authUser } = locals;
@@ -73,7 +73,9 @@ export const POST = withAuth(async ({ request, locals }) => {
7373
.eq('conversation_id', conversationId)
7474
.eq('message_recipients.recipient_user_id', userId)
7575
.is('deleted_at', null)
76-
.order('created_at', { ascending: true })
76+
// Newest N first, reversed below: ascending + limit returned a chat's
77+
// OLDEST messages, so anything past the limit never showed.
78+
.order('created_at', { ascending: false })
7779
.limit(normalizedLimit);
7880

7981
if (before) {
@@ -90,7 +92,7 @@ export const POST = withAuth(async ({ request, locals }) => {
9092
console.log('📨 [SSE-LOAD] Loaded', messages?.length || 0, 'messages');
9193

9294
// Process messages and add user-specific encrypted content
93-
const processedMessages = (messages || []).map(msg => {
95+
const processedMessages = (messages || []).slice().reverse().map(msg => {
9496
// Check if this message has per-user encrypted content in message_recipients
9597
if (msg.message_recipients && msg.message_recipients.length > 0) {
9698
// Find the encrypted content for this specific user
@@ -151,5 +153,5 @@ export const POST = withAuth(async ({ request, locals }) => {
151153
});
152154

153155
function normalizeMessageLimit(limit) {
154-
return Number.isInteger(limit) && limit >= 1 && limit <= 100 ? limit : null;
156+
return Number.isInteger(limit) && limit >= 1 && limit <= 500 ? limit : null;
155157
}

‎src/app/api/messages/load/route.test.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ describe('POST /api/messages/load validation', () => {
118118
const body = await response.json();
119119

120120
expect(response.status).toBe(400);
121-
expect(body.error).toBe('limit must be an integer between 1 and 100');
121+
expect(body.error).toBe('limit must be an integer between 1 and 500');
122122
expect(mocks.mockSupabase.from).not.toHaveBeenCalled();
123123
});
124124

‎src/app/api/messages/send/route.js‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ import { sseManager } from '@/lib/api/sse-manager.js';
99
import { MESSAGE_TYPES } from '@/lib/api/protocol.js';
1010
import { getServiceRoleClient } from '@/lib/supabase/service-role.js';
1111

12+
13+
const SENDABLE_TYPES = new Set(['text', 'image', 'file', 'reaction']);
14+
1215
export const POST = withAuth(async ({ request, locals }) => {
1316
try {
1417
let body;
@@ -49,6 +52,15 @@ export const POST = withAuth(async ({ request, locals }) => {
4952
return NextResponse.json({ error: 'metadata must be a JSON object' }, { status: 400 });
5053
}
5154

55+
// 'reaction' messages carry an encrypted { target, emoji } envelope (see
56+
// src/lib/chat/reactions.js); the server never learns what was reacted to.
57+
if (!SENDABLE_TYPES.has(messageType)) {
58+
return NextResponse.json({ error: `messageType must be one of ${[...SENDABLE_TYPES].join(', ')}` }, { status: 400 });
59+
}
60+
if (replyToId !== undefined && replyToId !== null && (typeof replyToId !== 'string' || !replyToId)) {
61+
return NextResponse.json({ error: 'replyToId must be a message id' }, { status: 400 });
62+
}
63+
5264
const { supabase, user: authUser } = locals;
5365

5466
// Get internal user ID from auth user ID
@@ -77,6 +89,20 @@ export const POST = withAuth(async ({ request, locals }) => {
7789
return NextResponse.json({ error: 'Access denied to conversation' }, { status: 403 });
7890
}
7991

92+
// A reply must point at a message in THIS conversation (it is shown as a
93+
// quote, so a foreign id would be a way to probe other conversations).
94+
if (replyToId) {
95+
const { data: target } = await supabase
96+
.from('messages')
97+
.select('id')
98+
.eq('id', replyToId)
99+
.eq('conversation_id', conversationId)
100+
.maybeSingle();
101+
if (!target) {
102+
return NextResponse.json({ error: 'replyToId is not a message in this conversation' }, { status: 400 });
103+
}
104+
}
105+
80106
// Insert message into database (without encrypted_content in main table)
81107
const messageData = {
82108
conversation_id: conversationId,

‎src/cli/api.js‎

Lines changed: 30 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
*/
77
import { baseUrl, saveSession } from './config.js';
88
import { keyring } from './crypto.js';
9+
import { foldMessages, reactionEnvelope, REACTION_TYPE } from '../lib/chat/reactions.js';
910

1011
export class QcError extends Error {
1112
constructor(message, status) {
@@ -82,39 +83,49 @@ export class QcClient {
8283
}
8384

8485
/** Decrypted messages, oldest first. */
85-
async messages(conversationId, { limit = 100, before } = {}) {
86+
/**
87+
* Decrypted messages, oldest first. Reactions (encrypted messages of their
88+
* own) are folded into their targets as `reactions`, and replies carry a
89+
* `replyTo` quote, exactly as the web app shows them.
90+
*/
91+
async messages(conversationId, { limit = 200, before } = {}) {
8692
const { messages = [], hasMore = false } = await this.request('/api/messages/load', {
8793
method: 'POST',
8894
body: { conversationId, limit, ...(before ? { before } : {}) },
8995
});
90-
const out = [];
96+
const raw = [];
9197
for (const m of messages) {
92-
let text;
98+
let content = m.encrypted_content ? await this.ring.decrypt(m.encrypted_content) : '';
9399
if (m.message_type === 'file' || m.has_attachments) {
94-
text = m.encrypted_content ? await this.ring.decrypt(m.encrypted_content) : '';
95-
text = `📎 ${text && text !== '[File attachment]' ? `${text} ` : ''}(attachment: open qrypt.chat to download)`;
96-
} else {
97-
text = m.encrypted_content ? await this.ring.decrypt(m.encrypted_content) : '';
100+
content = `📎 ${content && content !== '[File attachment]' ? `${content} ` : ''}(attachment: open qrypt.chat to download)`;
98101
}
99-
out.push({
100-
id: m.id,
101-
conversationId: m.conversation_id,
102-
senderId: m.sender_id,
103-
sender: m.sender?.display_name || m.sender?.username || 'unknown',
104-
username: m.sender?.username || '',
105-
mine: m.sender_id === this.me?.id,
106-
text,
107-
at: m.created_at,
108-
});
102+
raw.push({ ...m, content });
109103
}
104+
const out = foldMessages(raw, this.me?.id).map((m) => ({
105+
id: m.id,
106+
conversationId: m.conversation_id,
107+
senderId: m.sender_id,
108+
sender: m.sender?.display_name || m.sender?.username || 'unknown',
109+
username: m.sender?.username || '',
110+
mine: m.sender_id === this.me?.id,
111+
text: m.content,
112+
at: m.created_at,
113+
reactions: m.reactions.map(({ emoji, count, mine, names }) => ({ emoji, count, mine, names })),
114+
...(m.replyTo ? { replyTo: m.replyTo } : {}),
115+
}));
110116
return { messages: out, hasMore };
111117
}
112118

119+
/** React to a message (one per person; remove=true withdraws it). Encrypted like any message. */
120+
async react(conversationId, messageId, emoji, remove = false) {
121+
return this.send(conversationId, reactionEnvelope(messageId, emoji, remove), { messageType: REACTION_TYPE });
122+
}
123+
113124
/**
114125
* Encrypt the text once per participant (their public key, ML-KEM-1024) and
115126
* send every copy. The server stores ciphertext only.
116127
*/
117-
async send(conversationId, text) {
128+
async send(conversationId, text, { replyTo, messageType = 'text' } = {}) {
118129
const { participants = [] } = await this.request(`/api/chat/conversations/${encodeURIComponent(conversationId)}/participants`);
119130
const userIds = participants.map((p) => p.user_id);
120131
if (!userIds.length) throw new QcError('This conversation has no participants');
@@ -131,7 +142,7 @@ export class QcClient {
131142
if (!Object.keys(encryptedContents).length) throw new QcError('No participant has a public key yet');
132143
const { message } = await this.request('/api/messages/send', {
133144
method: 'POST',
134-
body: { conversationId, encryptedContents, messageType: 'text' },
145+
body: { conversationId, encryptedContents, messageType, ...(replyTo ? { replyToId: replyTo } : {}) },
135146
});
136147
return { message, skipped: missing.length };
137148
}

‎src/cli/commands.js‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ Usage:
1515
qc whoami who this terminal is signed in as
1616
qc chats list your chats
1717
qc read <chat> [-n 20] print the last messages of a chat
18-
qc send <chat> <text> send a message (text "-" reads stdin)
18+
qc send <chat> <text> send a message (text "-" reads stdin; --reply <message-id> to reply)
19+
qc react <chat> <message-id> <emoji> [--remove] react to a message
1920
qc listen print new messages as they arrive (NDJSON with --json)
2021
qc mcp run as an MCP server on stdio (list_chats, read_chat, send_message)
2122
@@ -33,7 +34,7 @@ export function parseArgs(argv) {
3334
if (a.startsWith('--')) {
3435
const [k, v] = a.slice(2).split('=', 2);
3536
if (v !== undefined) args.flags[k] = v;
36-
else if (['url', 'n', 'limit'].includes(k) && argv[i + 1] !== undefined) args.flags[k] = argv[++i];
37+
else if (['url', 'n', 'limit', 'reply'].includes(k) && argv[i + 1] !== undefined) args.flags[k] = argv[++i];
3738
else args.flags[k] = true;
3839
} else if (a === '-n' && argv[i + 1] !== undefined) {
3940
args.flags.n = argv[++i];
@@ -122,16 +123,32 @@ export async function main(argv, { version = '0.0.0' } = {}) {
122123
const { messages } = await c.messages(chat.id, { limit: 100 });
123124
const last = messages.slice(-Math.max(1, Number(flags.n || flags.limit || 20)));
124125
if (flags.json) return json(last);
125-
for (const m of last) out(`[${stamp(m.at)}] ${m.mine ? 'you' : m.sender}: ${m.text}`);
126+
for (const m of last) {
127+
if (m.replyTo) out(` ┃ ${m.replyTo.name ? `${m.replyTo.name}: ` : ''}${m.replyTo.snippet}`);
128+
const reactions = m.reactions?.length ? ` [${m.reactions.map((r) => `${r.emoji}${r.count > 1 ? r.count : ''}`).join(' ')}]` : '';
129+
out(`[${stamp(m.at)}] ${m.mine ? 'you' : m.sender}: ${m.text}${reactions} (${m.id.slice(0, 8)})`);
130+
}
126131
return;
127132
}
133+
case 'react': {
134+
const [chatQuery, messageId, emoji] = rest;
135+
if (!chatQuery || !messageId || !emoji) throw new Error('Usage: qc react <chat> <message-id> <emoji> [--remove]');
136+
const c = await client(flags);
137+
const chat = findChat(await c.conversations(), chatQuery);
138+
// A message id or its first characters, as qc read prints them.
139+
const { messages } = await c.messages(chat.id);
140+
const target = messages.filter((m) => m.id === messageId || m.id.startsWith(messageId));
141+
if (target.length !== 1) throw new Error(target.length ? `"${messageId}" matches ${target.length} messages` : `No message "${messageId}" in ${chat.title}`);
142+
await c.react(chat.id, target[0].id, emoji, !!flags.remove);
143+
return out(`${flags.remove ? 'Removed' : 'Reacted'} ${emoji} on ${chat.title}.`);
144+
}
128145
case 'send': {
129146
if (!rest[0] || rest.length < 2) throw new Error('Usage: qc send <chat> <text> (text "-" reads stdin)');
130147
const text = rest[1] === '-' && rest.length === 2 ? (await readStdin()).trim() : rest.slice(1).join(' ');
131148
if (!text) throw new Error('Nothing to send.');
132149
const c = await client(flags);
133150
const chat = findChat(await c.conversations(), rest[0]);
134-
const { message, skipped } = await c.send(chat.id, text);
151+
const { message, skipped } = await c.send(chat.id, text, { replyTo: flags.reply || undefined });
135152
if (flags.json) return json({ id: message?.id, conversation: chat.id, skipped });
136153
return out(`Sent to ${chat.title}${skipped ? ` (${skipped} participant(s) have no key yet)` : ''}.`);
137154
}

‎src/cli/mcp.js‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,27 @@ const TOOLS = [
3333
properties: {
3434
chat: { type: 'string', description: 'Conversation id or part of its name' },
3535
text: { type: 'string', description: 'The message' },
36+
reply_to: { type: 'string', description: 'Optional: id of the message this replies to (from read_chat)' },
3637
},
3738
required: ['chat', 'text'],
3839
additionalProperties: false,
3940
},
4041
},
42+
{
43+
name: 'react_to_message',
44+
description: 'React to a message with an emoji (Signal-style: one reaction per person; a new one replaces yours). End-to-end encrypted.',
45+
inputSchema: {
46+
type: 'object',
47+
properties: {
48+
chat: { type: 'string', description: 'Conversation id or part of its name' },
49+
message_id: { type: 'string', description: 'The message id, from read_chat' },
50+
emoji: { type: 'string', description: 'The emoji, e.g. ❤️' },
51+
remove: { type: 'boolean', description: 'Withdraw this reaction instead' },
52+
},
53+
required: ['chat', 'message_id', 'emoji'],
54+
additionalProperties: false,
55+
},
56+
},
4157
];
4258

4359
export async function callTool(client, name, args = {}) {
@@ -49,14 +65,30 @@ export async function callTool(client, name, args = {}) {
4965
const chat = findChat(await client.conversations(), args.chat);
5066
const { messages } = await client.messages(chat.id, { limit: 100 });
5167
const limit = Math.min(100, Math.max(1, Number(args.limit) || 20));
52-
return { chat: { id: chat.id, title: chat.title }, messages: messages.slice(-limit).map(({ sender, mine, text, at }) => ({ from: mine ? 'me' : sender, text, at })) };
68+
return {
69+
chat: { id: chat.id, title: chat.title },
70+
messages: messages.slice(-limit).map(({ id, sender, mine, text, at, reactions, replyTo }) => ({
71+
id,
72+
from: mine ? 'me' : sender,
73+
text,
74+
at,
75+
...(reactions?.length ? { reactions: reactions.map(({ emoji, count, mine: m }) => ({ emoji, count, mine: m })) } : {}),
76+
...(replyTo ? { reply_to: { id: replyTo.id, from: replyTo.name, text: replyTo.snippet } } : {}),
77+
})),
78+
};
5379
}
5480
if (name === 'send_message') {
5581
if (!args.text || typeof args.text !== 'string') throw new Error('text is required');
5682
const chat = findChat(await client.conversations(), args.chat);
57-
const { message, skipped } = await client.send(chat.id, args.text);
83+
const { message, skipped } = await client.send(chat.id, args.text, { replyTo: typeof args.reply_to === 'string' ? args.reply_to : undefined });
5884
return { sent: true, id: message?.id, chat: chat.title, skipped };
5985
}
86+
if (name === 'react_to_message') {
87+
if (!args.emoji || typeof args.emoji !== 'string') throw new Error('emoji is required');
88+
const chat = findChat(await client.conversations(), args.chat);
89+
await client.react(chat.id, String(args.message_id), args.emoji, !!args.remove);
90+
return { reacted: !args.remove, emoji: args.emoji, chat: chat.title };
91+
}
6092
throw new Error(`Unknown tool ${name}`);
6193
}
6294

0 commit comments

Comments
 (0)