Skip to content

Commit 2c3bf47

Browse files
ralyodioclaude
andauthored
Agents: open the operator chat without the broken RPC; full rollback (0.7.1) (#296)
create_direct_conversation() inserts the creator as a participant after a trigger already did, so it always failed on the unique key and agent joins rolled back. Insert the conversation and upsert both participants instead. The rollback now also deletes the users row (deleting the auth user does not cascade), its trigger-made note-to-self, the key and the conversation. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent a7941de commit 2c3bf47

3 files changed

Lines changed: 66 additions & 10 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.7.0",
4+
"version": "0.7.1",
55
"type": "module",
66
"bin": {
77
"qc": "./bin/qc.js",

‎src/lib/agents/agents.js‎

Lines changed: 41 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,30 @@ export async function redeemInvite(db, token, { username, displayName, publicKey
118118
if (!claimed?.length) throw new AgentError('invite_invalid', 'This invite was just used', 410);
119119

120120
let authUserId = null;
121+
let userId = null;
122+
let conversationId = null;
123+
// Everything made here is removed again on failure: deleting the auth user
124+
// does not cascade to public.users, and a trigger gives every new user a
125+
// note-to-self conversation.
121126
const undo = async () => {
122-
if (authUserId) await db.auth.admin.deleteUser(authUserId).catch(() => {});
127+
const quietly = (p) => Promise.resolve(p).catch(() => {});
128+
if (conversationId) {
129+
await quietly(db.from('conversation_participants').delete().eq('conversation_id', conversationId));
130+
await quietly(db.from('conversations').delete().eq('id', conversationId));
131+
}
132+
if (userId) {
133+
const { data: own } = await db.from('conversations').select('id').eq('created_by', userId).then((r) => r, () => ({ data: [] }));
134+
for (const c of own ?? []) {
135+
await quietly(db.from('conversation_participants').delete().eq('conversation_id', c.id));
136+
await quietly(db.from('conversations').delete().eq('id', c.id));
137+
}
138+
await quietly(db.from('conversation_participants').delete().eq('user_id', userId));
139+
await quietly(db.from('users').delete().eq('id', userId));
140+
}
141+
if (authUserId) {
142+
await quietly(db.from('user_public_keys').delete().eq('user_id', authUserId));
143+
await quietly(db.auth.admin.deleteUser(authUserId));
144+
}
123145
await db.from('agent_invites').update({ redeemed_at: null, redeemed_by: null }).eq('id', invite.id);
124146
};
125147

@@ -148,17 +170,30 @@ export async function redeemInvite(db, token, { username, displayName, publicKey
148170
if (userError?.code === '23505') throw new AgentError('username_taken', 'That username is taken', 409);
149171
throw new AgentError('server_error', 'Could not create the agent account', 500);
150172
}
173+
userId = user.id;
151174

152175
const { error: keyError } = await db
153176
.from('user_public_keys')
154177
.insert({ user_id: authUserId, public_key: keyBytes.toString('base64'), key_type: 'ML-KEM-1024' });
155178
if (keyError) throw new AgentError('server_error', 'Could not store the agent key', 500);
156179

157-
const { data: conversationId, error: convError } = await db.rpc('create_direct_conversation', {
158-
user1_id: invite.inviter_user_id,
159-
user2_id: user.id,
160-
});
161-
if (convError || !conversationId) throw new AgentError('server_error', 'Could not open the conversation', 500);
180+
// The direct conversation with the operator. (create_direct_conversation()
181+
// collides with the trigger that already adds the creator as a participant.)
182+
const { data: conv, error: convError } = await db
183+
.from('conversations')
184+
.insert({ type: 'direct', created_by: invite.inviter_user_id })
185+
.select('id')
186+
.single();
187+
if (convError || !conv?.id) throw new AgentError('server_error', 'Could not open the conversation', 500);
188+
conversationId = conv.id;
189+
const { error: partError } = await db.from('conversation_participants').upsert(
190+
[
191+
{ conversation_id: conversationId, user_id: invite.inviter_user_id },
192+
{ conversation_id: conversationId, user_id: user.id },
193+
],
194+
{ onConflict: 'conversation_id,user_id', ignoreDuplicates: true },
195+
);
196+
if (partError) throw new AgentError('server_error', 'Could not open the conversation', 500);
162197

163198
await db.from('agent_invites').update({ redeemed_by: user.id }).eq('id', invite.id);
164199

‎src/lib/agents/agents.test.js‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ const KEY = Buffer.alloc(1568, 7).toString('base64');
88

99
/** A tiny in-memory stand-in for the service-role client. */
1010
function fakeDb({ invite, usernameTaken = false, keyInsertFails = false } = {}) {
11-
const state = { invite: invite ? { ...invite } : null, users: [], keys: [], deletedAuth: [], rpc: [] };
11+
const state = { invite: invite ? { ...invite } : null, users: [], keys: [], deletedAuth: [], conversations: [], participants: [], deleted: [] };
1212
const db = {
1313
state,
1414
auth: {
@@ -17,7 +17,7 @@ function fakeDb({ invite, usernameTaken = false, keyInsertFails = false } = {})
1717
deleteUser: vi.fn(async (id) => state.deletedAuth.push(id))
1818
}
1919
},
20-
rpc: vi.fn(async (name, args) => (state.rpc.push([name, args]), { data: 'conv-1', error: null })),
20+
rpc: vi.fn(async () => ({ data: null, error: { message: 'create_direct_conversation must not be used' } })),
2121
from(table) {
2222
let op = 'select';
2323
let patch = null;
@@ -29,11 +29,28 @@ function fakeDb({ invite, usernameTaken = false, keyInsertFails = false } = {})
2929
ilike: (k, v) => (filters.push(['ilike', k, v]), q),
3030
update: (p) => ((op = 'update'), (patch = p), q),
3131
insert: (row) => ((op = 'insert'), (patch = row), q),
32+
upsert: (rows) => ((op = 'upsert'), (patch = rows), q),
33+
delete: () => ((op = 'delete'), q),
3234
maybeSingle: async () => run('one'),
3335
single: async () => run('one'),
3436
then: (res, rej) => run('many').then(res, rej)
3537
};
3638
async function run(shape) {
39+
if (op === 'delete') {
40+
state.deleted.push([table, ...filters.map(([, k, v]) => `${k}=${v}`)]);
41+
return { data: null, error: null };
42+
}
43+
if (table === 'conversations') {
44+
if (op === 'insert') {
45+
state.conversations.push(patch);
46+
return { data: { id: 'conv-1' }, error: null };
47+
}
48+
return { data: [], error: null };
49+
}
50+
if (table === 'conversation_participants') {
51+
state.participants.push(...[].concat(patch ?? []));
52+
return { data: null, error: null };
53+
}
3754
if (table === 'agent_invites') {
3855
const inv = state.invite;
3956
const match = inv && filters.every(([t, k, v]) => (t === 'is' ? inv[k] === v || (v === null && inv[k] == null) : k === 'token_hash' ? inv.token_hash === v : inv[k] === v));
@@ -116,7 +133,9 @@ describe('redeemInvite', () => {
116133
expect(out.conversationId).toBe('conv-1');
117134
expect(db.state.users[0]).toMatchObject({ account_type: 'agent', operator_user_id: 'inviter', username: 'athena_bot', display_name: 'Athena' });
118135
expect(db.state.keys[0]).toEqual({ user_id: 'auth-agent', public_key: KEY, key_type: 'ML-KEM-1024' });
119-
expect(db.rpc).toHaveBeenCalledWith('create_direct_conversation', { user1_id: 'inviter', user2_id: 'user-agent' });
136+
expect(db.rpc).not.toHaveBeenCalled();
137+
expect(db.state.conversations[0]).toEqual({ type: 'direct', created_by: 'inviter' });
138+
expect(db.state.participants.map((p) => p.user_id)).toEqual(['inviter', 'user-agent']);
120139
expect(db.state.invite.redeemed_at).toBeTruthy();
121140
expect(db.state.invite.redeemed_by).toBe('user-agent');
122141
});
@@ -136,6 +155,8 @@ describe('redeemInvite', () => {
136155
const db = fakeDb({ invite: openInviteFor(token), keyInsertFails: true });
137156
await expect(redeemInvite(db, token, { username: 'athena_bot', publicKey: KEY })).rejects.toBeInstanceOf(AgentError);
138157
expect(db.state.deletedAuth).toEqual(['auth-agent']);
158+
// The users row goes too: deleting the auth user does not cascade to public.users.
159+
expect(db.state.deleted).toContainEqual(['users', 'id=user-agent']);
139160
expect(db.state.invite.redeemed_at).toBeNull();
140161
});
141162
});

0 commit comments

Comments
 (0)