@vellumai/assistant 0.11.2-dev.202608070306.b97cdd6 → 0.11.2-dev.202608070442.84135c4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -211,7 +211,6 @@ export const CreateOutboundSessionIpcParamsSchema = z.object({
211
211
  requireSourceSessionPending: z.string().min(1).optional(),
212
212
  // Mint only if the channel has no active (pending_bootstrap /
213
213
  // awaiting_response, non-expired) session.
214
- ifNoneActive: z.boolean().optional(),
215
214
  // Sender-scoped variant: mint unless the channel's active session is bound
216
215
  // to this expectedExternalUserId (a different sender may supersede).
217
216
  ifNoneActiveForExternalUserId: z.string().min(1).optional(),
@@ -240,7 +239,8 @@ export type CreateOutboundSessionIpcResponse = z.infer<
240
239
 
241
240
  /**
242
241
  * Conflict marker returned by `verification_sessions_create_outbound` when a
243
- * claim guard (`requireSourceSessionPending` / `ifNoneActive`) fails. Only
242
+ * claim guard (`requireSourceSessionPending` /
243
+ * `ifNoneActiveForExternalUserId`) fails. Only
244
244
  * reachable when a guard was passed — legacy callers never see this shape.
245
245
  */
246
246
  export const CreateOutboundSessionConflictSchema = z.object({
@@ -277,7 +277,17 @@ export type GetPendingSessionIpcParams = z.infer<
277
277
  * Request for `verification_sessions_find_active` (statuses
278
278
  * `pending_bootstrap`/`awaiting_response`, newest first).
279
279
  */
280
- export const FindActiveSessionIpcParamsSchema = ChannelOnlyIpcParamsSchema;
280
+ export const FindActiveSessionIpcParamsSchema =
281
+ ChannelOnlyIpcParamsSchema.extend({
282
+ /**
283
+ * Narrows the lookup to one session. A channel can carry several live
284
+ * sessions at once, one per person verifying plus the guardian's own flow,
285
+ * so a caller that means a particular one has to say which. Omitted, the
286
+ * lookup returns whoever started most recently.
287
+ */
288
+ expectedExternalUserId: z.string().min(1).optional(),
289
+ verificationPurpose: VerificationPurposeSchema.optional(),
290
+ });
281
291
 
282
292
  export type FindActiveSessionIpcParams = z.infer<
283
293
  typeof FindActiveSessionIpcParamsSchema
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.11.2-dev.202608070306.b97cdd6",
3
+ "version": "0.11.2-dev.202608070442.84135c4",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -40,10 +40,24 @@ const realGatewaySessionsModule = {
40
40
  };
41
41
  mock.module("../channels/gateway-verification-sessions.js", () => ({
42
42
  ...realGatewaySessionsModule,
43
- findActiveSession: async (channel: string) =>
44
- findActiveSessionMockActive
45
- ? activeVoiceSession
46
- : realGatewaySessionsModule.findActiveSession(channel),
43
+ // Honours the caller's filter: the guard asks for the number it is about
44
+ // to dial, so a session for a different number must read as absent.
45
+ findActiveSession: async (
46
+ channel: string,
47
+ filter?: { expectedExternalUserId?: string },
48
+ ) => {
49
+ if (!findActiveSessionMockActive) {
50
+ return realGatewaySessionsModule.findActiveSession(channel, filter);
51
+ }
52
+ const wanted = filter?.expectedExternalUserId;
53
+ if (
54
+ wanted !== undefined &&
55
+ activeVoiceSession?.expectedPhoneE164 !== wanted
56
+ ) {
57
+ return null;
58
+ }
59
+ return activeVoiceSession;
60
+ },
47
61
  }));
48
62
 
49
63
  const { executeCallStart } = await import("../tools/calls/call-start.js");
@@ -1640,32 +1640,42 @@ describe("outbound verification sessions", () => {
1640
1640
 
1641
1641
  // ── Auto-revoke of prior sessions ──
1642
1642
 
1643
- test("creating a new outbound session auto-revokes prior pending/awaiting sessions", async () => {
1643
+ test("a second code for the same number revokes the first", async () => {
1644
1644
  const { sessionId: firstId } = await createOutboundSession({
1645
1645
  channel: "phone",
1646
- expectedPhoneE164: "+15551234567",
1647
- destinationAddress: "+15551234567",
1646
+ expectedPhoneE164: "+15555550101",
1647
+ destinationAddress: "+15555550101",
1648
+ });
1649
+ const { sessionId: secondId } = await createOutboundSession({
1650
+ channel: "phone",
1651
+ expectedPhoneE164: "+15555550101",
1652
+ destinationAddress: "+15555550101",
1648
1653
  });
1649
1654
 
1650
- const first = await serviceFindActiveSession("phone");
1651
- expect(first).not.toBeNull();
1652
- expect(first!.id).toBe(firstId);
1655
+ // Read by id rather than through the unfiltered lookup: two live
1656
+ // sessions minted in the same millisecond have no defined order, and
1657
+ // what matters here is each row's status, not which one is "latest".
1658
+ expect(getSessionById(firstId)!.status).toBe("revoked");
1659
+ expect(getSessionById(secondId)!.status).toBe("awaiting_response");
1660
+ });
1653
1661
 
1654
- // Create a second session — first should be revoked
1662
+ test("a code for a different number leaves the first alone", async () => {
1663
+ // Two numbers are two people. Verifying one must not silently kill the
1664
+ // other's code, which they would learn about only by trying to use it
1665
+ // and being told it is "invalid or has expired".
1666
+ const { sessionId: firstId } = await createOutboundSession({
1667
+ channel: "phone",
1668
+ expectedPhoneE164: "+15555550101",
1669
+ destinationAddress: "+15555550101",
1670
+ });
1655
1671
  const { sessionId: secondId } = await createOutboundSession({
1656
1672
  channel: "phone",
1657
- expectedPhoneE164: "+15559876543",
1658
- destinationAddress: "+15559876543",
1673
+ expectedPhoneE164: "+15555550102",
1674
+ destinationAddress: "+15555550102",
1659
1675
  });
1660
1676
 
1661
- const second = await serviceFindActiveSession("phone");
1662
- expect(second).not.toBeNull();
1663
- expect(second!.id).toBe(secondId);
1664
-
1665
- // First session should no longer be findable as active
1666
- const firstRow = getSessionById(firstId);
1667
- expect(firstRow).not.toBeNull();
1668
- expect(firstRow!.status).toBe("revoked");
1677
+ expect(getSessionById(firstId)!.status).toBe("awaiting_response");
1678
+ expect(getSessionById(secondId)!.status).toBe("awaiting_response");
1669
1679
  });
1670
1680
 
1671
1681
  // ── findActiveSession returns correct session ──
@@ -0,0 +1,104 @@
1
+ import type { Database } from "bun:sqlite";
2
+ import { beforeEach, describe, expect, test } from "bun:test";
3
+
4
+ import { createConversation } from "../persistence/conversation-crud.js";
5
+ import { ensureGroupMigration } from "../persistence/conversation-group-migration.js";
6
+ import {
7
+ listConversations,
8
+ listPinnedConversations,
9
+ } from "../persistence/conversation-queries.js";
10
+ import { getDb } from "../persistence/db-connection.js";
11
+ import { initializeDb } from "../persistence/db-init.js";
12
+ import { createGroup } from "../persistence/group-crud.js";
13
+
14
+ await initializeDb();
15
+ ensureGroupMigration();
16
+
17
+ function getRawDb(): Database {
18
+ return (getDb() as unknown as { $client: Database }).$client;
19
+ }
20
+
21
+ /**
22
+ * Every conversation list orders by recency, pinned and custom groups
23
+ * included.
24
+ *
25
+ * `display_order` is a live column and some rows carry a value in it, so
26
+ * "nothing writes it" is not enough to make the order consistent: a read that
27
+ * consulted it would serve those rows in an arrangement no user can change,
28
+ * while every other surface shows recency.
29
+ *
30
+ * Each test sets `display_order` to contradict recency, so a read that
31
+ * consults it fails here rather than passing by coincidence.
32
+ */
33
+ describe("conversation list ordering ignores display_order", () => {
34
+ beforeEach(() => {
35
+ const raw = getRawDb();
36
+ raw.run("DELETE FROM conversations");
37
+ raw.run("DELETE FROM conversation_groups WHERE is_system_group = 0");
38
+ });
39
+
40
+ /** Give a row a `display_order` and a recency stamp that disagree. */
41
+ function arrange(id: string, displayOrder: number, lastMessageAt: number) {
42
+ getRawDb().run(
43
+ "UPDATE conversations SET display_order = ?, last_message_at = ? WHERE id = ?",
44
+ [displayOrder, lastMessageAt, id],
45
+ );
46
+ }
47
+
48
+ test("a custom group orders by recency, ignoring display_order", () => {
49
+ const groupId = createGroup("Briefs").id;
50
+ createConversation({ id: "conv-old", source: "user", groupId });
51
+ createConversation({ id: "conv-new", source: "user", groupId });
52
+ // `display_order` says old-then-new; recency says the opposite.
53
+ arrange("conv-old", 0, 1_000);
54
+ arrange("conv-new", 1, 9_000);
55
+
56
+ expect(listConversations({ groupId }).map((c) => c.id)).toEqual([
57
+ "conv-new",
58
+ "conv-old",
59
+ ]);
60
+ });
61
+
62
+ test("the pinned group orders by recency, ignoring display_order", () => {
63
+ createConversation({
64
+ id: "pin-old",
65
+ source: "user",
66
+ groupId: "system:pinned",
67
+ });
68
+ createConversation({
69
+ id: "pin-new",
70
+ source: "user",
71
+ groupId: "system:pinned",
72
+ });
73
+ arrange("pin-old", 0, 1_000);
74
+ arrange("pin-new", 1, 9_000);
75
+
76
+ expect(
77
+ listConversations({ groupId: "system:pinned" }).map((c) => c.id),
78
+ ).toEqual(["pin-new", "pin-old"]);
79
+ });
80
+
81
+ /* The page-one pinned injection reads through its own query, so it needs
82
+ the same guarantee: one section must not have two orderings depending on
83
+ which read served it. */
84
+ test("listPinnedConversations orders by recency too", () => {
85
+ createConversation({
86
+ id: "pin-old",
87
+ source: "user",
88
+ groupId: "system:pinned",
89
+ });
90
+ createConversation({
91
+ id: "pin-new",
92
+ source: "user",
93
+ groupId: "system:pinned",
94
+ });
95
+ getRawDb().run("UPDATE conversations SET is_pinned = 1");
96
+ arrange("pin-old", 0, 1_000);
97
+ arrange("pin-new", 1, 9_000);
98
+
99
+ expect(listPinnedConversations().map((c) => c.id)).toEqual([
100
+ "pin-new",
101
+ "pin-old",
102
+ ]);
103
+ });
104
+ });
@@ -139,9 +139,22 @@ export function createGatewayVerificationSessionsStub(options: {
139
139
  throwIfUnreachable("updateSessionDelivery");
140
140
  calls.updateSessionDelivery.push(args);
141
141
  },
142
- findActiveSession: async () => {
142
+ // Honours the caller's `expectedExternalUserId` filter the way the
143
+ // gateway does. Returning the session for every filter would make a
144
+ // "someone else is verifying" test pass against a lookup that, against
145
+ // the real gateway, would have found nothing.
146
+ findActiveSession: async (...args: unknown[]) => {
143
147
  calls.sessionReads.push("findActiveSession");
144
148
  throwIfUnreachable("findActiveSession");
149
+ const wantedActor = (
150
+ args[1] as { expectedExternalUserId?: string } | undefined
151
+ )?.expectedExternalUserId;
152
+ if (
153
+ wantedActor !== undefined &&
154
+ state.activeSession?.expectedExternalUserId !== wantedActor
155
+ ) {
156
+ return null;
157
+ }
145
158
  return state.activeSession;
146
159
  },
147
160
  getPendingSession: async () => {
@@ -62,10 +62,48 @@ function isInterceptable(s: VerificationSessionWire): boolean {
62
62
  return (INTERCEPTABLE_STATUSES as readonly string[]).includes(s.status);
63
63
  }
64
64
 
65
- function revokeInterceptable(channel: string): void {
65
+ const OUTBOUND_LIVE_STATUSES = ["pending_bootstrap", "awaiting_response"];
66
+
67
+ /**
68
+ * The identity a session redeems on, in `checkIdentityMatch`'s precedence
69
+ * order. Null when the session carries none, which is a bootstrap session.
70
+ */
71
+ function boundIdentity(session: {
72
+ expectedExternalUserId?: string | null;
73
+ expectedChatId?: string | null;
74
+ expectedPhoneE164?: string | null;
75
+ }): string | null {
76
+ if (session.expectedExternalUserId) {
77
+ return `user:${session.expectedExternalUserId}`;
78
+ }
79
+ if (session.expectedPhoneE164) {
80
+ return `phone:${session.expectedPhoneE164}`;
81
+ }
82
+ if (session.expectedChatId) {
83
+ return `chat:${session.expectedChatId}`;
84
+ }
85
+ return null;
86
+ }
87
+
88
+ /**
89
+ * Mirrors the gateway store: an outbound mint supersedes only sessions bound
90
+ * to the same identity, leaving other actors and inbound challenges alone.
91
+ */
92
+ function revokeSameActorOutbound(
93
+ channel: string,
94
+ params: SimCreateOutboundParams,
95
+ ): void {
96
+ const identity = boundIdentity(params);
97
+ if (identity === null) {
98
+ return;
99
+ }
66
100
  const now = Date.now();
67
101
  for (const s of sessions.values()) {
68
- if (s.channel === channel && isInterceptable(s)) {
102
+ if (
103
+ s.channel === channel &&
104
+ OUTBOUND_LIVE_STATUSES.includes(s.status) &&
105
+ boundIdentity(s) === identity
106
+ ) {
69
107
  s.status = "revoked";
70
108
  s.updatedAt = now;
71
109
  }
@@ -164,7 +202,7 @@ export interface SimCreateOutboundResult {
164
202
  export function createOutboundSession(
165
203
  params: SimCreateOutboundParams,
166
204
  ): SimCreateOutboundResult {
167
- revokeInterceptable(params.channel);
205
+ revokeSameActorOutbound(params.channel, params);
168
206
 
169
207
  const isUnbound = params.identityBindingStatus === "pending_bootstrap";
170
208
  const secret = isUnbound
@@ -220,17 +258,30 @@ export type SimGuardedCreateOutboundResult =
220
258
  export function createOutboundSessionGuarded(
221
259
  params: SimCreateOutboundParams & {
222
260
  requireSourceSessionPending?: string;
223
- ifNoneActive?: boolean;
224
261
  ifNoneActiveForExternalUserId?: string;
225
262
  },
226
263
  ): SimGuardedCreateOutboundResult {
227
264
  const {
228
265
  requireSourceSessionPending,
229
- ifNoneActive,
230
266
  ifNoneActiveForExternalUserId,
231
267
  ...createParams
232
268
  } = params;
233
269
 
270
+ if (ifNoneActiveForExternalUserId !== undefined) {
271
+ // Scoped, like the gateway. Reading the channel's latest and comparing
272
+ // misses this sender's session whenever somebody else started later.
273
+ const active = findActiveSession(params.channel, {
274
+ expectedExternalUserId: ifNoneActiveForExternalUserId,
275
+ });
276
+ if (active !== null) {
277
+ return { conflict: true, reason: "active_session_exists" };
278
+ }
279
+ }
280
+
281
+ // Claim the named source row. Winning the claim IS the guard, so a second
282
+ // claim of the same deep-link token conflicts. The identity-scoped revoke
283
+ // cannot do this: a bootstrap row carries whichever identity was bound onto
284
+ // it last.
234
285
  if (requireSourceSessionPending !== undefined) {
235
286
  const source = sessions.get(requireSourceSessionPending);
236
287
  if (
@@ -240,20 +291,8 @@ export function createOutboundSessionGuarded(
240
291
  ) {
241
292
  return { conflict: true, reason: "source_session_not_pending" };
242
293
  }
243
- }
244
-
245
- if (ifNoneActive && findActiveSession(params.channel) !== null) {
246
- return { conflict: true, reason: "active_session_exists" };
247
- }
248
-
249
- if (ifNoneActiveForExternalUserId !== undefined) {
250
- const active = findActiveSession(params.channel);
251
- if (
252
- active !== null &&
253
- active.expectedExternalUserId === ifNoneActiveForExternalUserId
254
- ) {
255
- return { conflict: true, reason: "active_session_exists" };
256
- }
294
+ source.status = "revoked";
295
+ source.updatedAt = Date.now();
257
296
  }
258
297
 
259
298
  return createOutboundSession(createParams);
@@ -309,6 +348,10 @@ export function getPendingSession(
309
348
 
310
349
  export function findActiveSession(
311
350
  channel: string,
351
+ filter: {
352
+ expectedExternalUserId?: string;
353
+ verificationPurpose?: "guardian" | "trusted_contact";
354
+ } = {},
312
355
  ): VerificationSessionWire | null {
313
356
  const now = Date.now();
314
357
  return (
@@ -318,7 +361,11 @@ export function findActiveSession(
318
361
  s.channel === channel &&
319
362
  (s.status === "pending_bootstrap" ||
320
363
  s.status === "awaiting_response") &&
321
- s.expiresAt > now,
364
+ s.expiresAt > now &&
365
+ (!filter.expectedExternalUserId ||
366
+ s.expectedExternalUserId === filter.expectedExternalUserId) &&
367
+ (!filter.verificationPurpose ||
368
+ s.verificationPurpose === filter.verificationPurpose),
322
369
  )
323
370
  .sort(newestFirst)[0] ?? null
324
371
  );
@@ -182,7 +182,12 @@ describe("introduction card decisions", () => {
182
182
  expectedExternalUserId: "U-REQUESTER",
183
183
  expectedChatId: "C-CHAT",
184
184
  identityBindingStatus: "bound",
185
- destinationAddress: "C-CHAT",
185
+ // The person, not the room. Slack delivers to a user id, and the room
186
+ // may hold an audience the code was never meant for. `expectedChatId`
187
+ // still carries the room because that is where the conversation is;
188
+ // with both identity fields set the consume path requires the user
189
+ // match, so the room is not a credential.
190
+ destinationAddress: "U-REQUESTER",
186
191
  verificationPurpose: "trusted_contact",
187
192
  });
188
193
  expect(outcomesOfType("activate_member")).toHaveLength(0);
@@ -104,7 +104,10 @@ mock.module("../channels/gateway-verification-sessions.js", () => ({
104
104
  params: Parameters<typeof createOutboundSessionGuarded>[0],
105
105
  ) => createOutboundSessionGuarded(params),
106
106
  getPendingSession: async (channel: string) => getPendingSession(channel),
107
- findActiveSession: async (channel: string) => findActiveSession(channel),
107
+ findActiveSession: async (
108
+ channel: string,
109
+ filter?: Parameters<typeof findActiveSession>[1],
110
+ ) => findActiveSession(channel, filter),
108
111
  }));
109
112
 
110
113
  await initializeDb();
@@ -92,7 +92,10 @@ mock.module("../channels/gateway-verification-sessions.js", () => ({
92
92
  params: Parameters<typeof createOutboundSessionGuarded>[0],
93
93
  ) => createOutboundSessionGuarded(params),
94
94
  getPendingSession: async (channel: string) => getPendingSession(channel),
95
- findActiveSession: async (channel: string) => findActiveSession(channel),
95
+ findActiveSession: async (
96
+ channel: string,
97
+ filter?: Parameters<typeof findActiveSession>[1],
98
+ ) => findActiveSession(channel, filter),
96
99
  }));
97
100
  import { createGuardianBinding } from "./helpers/create-guardian-binding.js";
98
101
  import {
@@ -59,6 +59,7 @@ import { getLogger } from "../util/logger.js";
59
59
  import {
60
60
  channelCanAddressOneReaderInBand,
61
61
  channelCanCompleteCodeHandshakeInDm,
62
+ channelDeliversToUserId,
62
63
  resolveDeliverCallbackUrlForChannel,
63
64
  resolveRequesterDeliveryTarget,
64
65
  } from "./guardian-channel-delivery.js";
@@ -1038,6 +1039,17 @@ const accessRequestResolver: GuardianRequestResolver = {
1038
1039
  // Non-voice approvals: mint an identity-bound verification session so the
1039
1040
  // requester can verify their identity. The raw secret transits back on
1040
1041
  // the decide response for daemon-owned delivery.
1042
+ //
1043
+ // The session is addressed to the requester, not to the room the request
1044
+ // arrived in. On the channels that reach a person by user id, that room is
1045
+ // one other people can read, so recording it as the destination describes
1046
+ // somewhere the code is never sent. `expectedChatId` keeps the room, which
1047
+ // is where the conversation is, and it is not a credential: whenever both
1048
+ // identity fields are set, `checkIdentityMatch` requires the user match.
1049
+ const destinationAddress = channelDeliversToUserId(channel)
1050
+ ? requesterExternalUserId || requesterChatId
1051
+ : requesterChatId;
1052
+
1041
1053
  return {
1042
1054
  ok: true,
1043
1055
  aclOutcome: {
@@ -1046,7 +1058,7 @@ const accessRequestResolver: GuardianRequestResolver = {
1046
1058
  expectedExternalUserId: requesterExternalUserId,
1047
1059
  expectedChatId: requesterChatId,
1048
1060
  identityBindingStatus: "bound",
1049
- destinationAddress: requesterChatId,
1061
+ destinationAddress,
1050
1062
  verificationPurpose: "trusted_contact",
1051
1063
  },
1052
1064
  persistFailureReason: "verification_session_mint_failed",
@@ -1090,7 +1102,9 @@ const accessRequestResolver: GuardianRequestResolver = {
1090
1102
  // Where the guardian's own copy goes when their channel has no in-band
1091
1103
  // route. Resolved from THEIR channel, never the requester's, or the code
1092
1104
  // is handed to the wrong transport.
1093
- const guardianDmUrl = resolveDeliverCallbackUrlForChannel(ctx.actor.channel);
1105
+ const guardianDmUrl = resolveDeliverCallbackUrlForChannel(
1106
+ ctx.actor.channel,
1107
+ );
1094
1108
 
1095
1109
  // Guardian-facing label prefers the contact display name over the raw ID.
1096
1110
  const requesterLabel =
@@ -1280,7 +1294,10 @@ const accessRequestResolver: GuardianRequestResolver = {
1280
1294
  // silently suppressed it for both.
1281
1295
  let requesterNotified = false;
1282
1296
  let codeDelivered = false;
1283
- const codeText = guardianVerificationCodeText(requesterLabel, session.secret);
1297
+ const codeText = guardianVerificationCodeText(
1298
+ requesterLabel,
1299
+ session.secret,
1300
+ );
1284
1301
 
1285
1302
  if (guardianInBandContext) {
1286
1303
  codeDelivered = true;
@@ -1375,7 +1392,8 @@ const accessRequestResolver: GuardianRequestResolver = {
1375
1392
  // code straight to the requester. Everywhere else the guardian relays
1376
1393
  // it and the requester gets a courier notice.
1377
1394
  const requesterCodeDelivered =
1378
- channelCanCompleteCodeHandshakeInDm(channel) && requesterExternalUserId
1395
+ channelCanCompleteCodeHandshakeInDm(channel) &&
1396
+ requesterExternalUserId
1379
1397
  ? await deliverVerificationCodeToRequester({
1380
1398
  replyCallbackUrl: requesterReplyUrl,
1381
1399
  requesterExternalUserId,
@@ -192,14 +192,14 @@ describe("createOutboundSessionConditional", () => {
192
192
  const result = await client.createOutboundSessionConditional({
193
193
  channel: "telegram",
194
194
  requireSourceSessionPending: "bootstrap-1",
195
- ifNoneActive: true,
195
+ ifNoneActiveForExternalUserId: "user-1",
196
196
  });
197
197
 
198
198
  expect(ipcCalls[0]?.method).toBe("verification_sessions_create_outbound");
199
199
  expect(ipcCalls[0]?.params).toEqual({
200
200
  channel: "telegram",
201
201
  requireSourceSessionPending: "bootstrap-1",
202
- ifNoneActive: true,
202
+ ifNoneActiveForExternalUserId: "user-1",
203
203
  });
204
204
  expect(result).toEqual(created);
205
205
  });
@@ -209,7 +209,7 @@ describe("createOutboundSessionConditional", () => {
209
209
 
210
210
  const result = await client.createOutboundSessionConditional({
211
211
  channel: "telegram",
212
- ifNoneActive: true,
212
+ ifNoneActiveForExternalUserId: "user-1",
213
213
  });
214
214
 
215
215
  expect(result).toEqual({
@@ -122,7 +122,8 @@ export async function createOutboundSession(
122
122
 
123
123
  /**
124
124
  * Guarded variant of `createOutboundSession` for callers passing an atomic
125
- * claim guard (`requireSourceSessionPending` / `ifNoneActive`). The gateway
125
+ * claim guard (`requireSourceSessionPending` /
126
+ * `ifNoneActiveForExternalUserId`). The gateway
126
127
  * evaluates the guard in the same synchronous section as the mint; a failed
127
128
  * guard returns a conflict marker instead of revoking the concurrent
128
129
  * winner's session. Throws when the gateway is unreachable (fail-closed).
@@ -160,10 +161,14 @@ export async function getPendingSession(
160
161
  */
161
162
  export async function findActiveSession(
162
163
  channel: string,
164
+ filter: {
165
+ expectedExternalUserId?: string;
166
+ verificationPurpose?: "guardian" | "trusted_contact";
167
+ } = {},
163
168
  ): Promise<VerificationSessionWire | null> {
164
169
  return callGateway(
165
170
  VERIFICATION_SESSIONS_IPC_METHODS.findActive,
166
- { channel },
171
+ { channel, ...filter },
167
172
  SessionLookupIpcResponseSchema,
168
173
  );
169
174
  }
@@ -209,7 +209,10 @@ export async function getVerificationStatus(
209
209
  // restart and detect bootstrap completion.
210
210
  const [pendingSession, activeOutboundSession] = await Promise.all([
211
211
  getPendingSession(resolvedChannel),
212
- findActiveSession(resolvedChannel),
212
+ // The guardian's own session. A channel can carry one per person
213
+ // verifying, so an unscoped read would report a requester's session as
214
+ // the guardian's pending verification.
215
+ findActiveSession(resolvedChannel, { verificationPurpose: "guardian" }),
213
216
  ]);
214
217
  const hasPendingChallenge = pendingSession != null;
215
218
  const outboundFields: Record<string, unknown> = {};
@@ -324,27 +324,6 @@ function originChannelClause(originChannel: string) {
324
324
  return eq(conversations.originChannel, originChannel);
325
325
  }
326
326
 
327
- /**
328
- * Order a group's rows the way the user arranged them: by explicit
329
- * `display_order` first, then by recency. Only meaningful for a real group;
330
- * the ungrouped bucket is pure recency, since a row that was dragged inside a
331
- * group and later removed keeps a stale `display_order` that must not
332
- * resurface as a sort key.
333
- */
334
- function isUserOrderedGroup(groupId: string | undefined): boolean {
335
- if (groupId === undefined) {
336
- return false;
337
- }
338
- // Pinned and custom groups are the only drag-reorderable sections, so they
339
- // are the only ones whose `display_order` means anything. Every other
340
- // system bucket sorts by recency: `batchSetDisplayOrders` writes
341
- // `display_order` alongside `group_id` when a row moves into
342
- // `system:background` / `system:scheduled`, and that value persists through
343
- // later moves, so honouring it would order the same section differently
344
- // depending on whether it was fetched by `conversationType` or `groupId`.
345
- return groupId === PINNED_GROUP_ID || !groupId.startsWith("system:");
346
- }
347
-
348
327
  function conversationListWhere(filter: ConversationListFilter) {
349
328
  const {
350
329
  conversationType = "standard",
@@ -380,14 +359,11 @@ export function listConversations(
380
359
  // distinguish a total order from a lucky one. The guarantee becomes
381
360
  // observable, and gets its test, with the keyset pagination work.
382
361
  const tiebreak = desc(conversations.id);
383
- const orderBy = isUserOrderedGroup(filter.groupId)
384
- ? [sql`COALESCE(display_order, 999999) ASC`, recency, tiebreak]
385
- : [recency, tiebreak];
386
362
  return db
387
363
  .select()
388
364
  .from(conversations)
389
365
  .where(conversationListWhere(filter))
390
- .orderBy(...orderBy)
366
+ .orderBy(recency, tiebreak)
391
367
  .limit(limit ?? 100)
392
368
  .offset(offset)
393
369
  .all()
@@ -513,7 +489,6 @@ export function listPinnedConversations(
513
489
  ),
514
490
  )
515
491
  .orderBy(
516
- sql`COALESCE(display_order, 999999) ASC`,
517
492
  desc(
518
493
  sql`COALESCE(${conversations.lastMessageAt}, ${conversations.updatedAt})`,
519
494
  ),
@@ -329,19 +329,34 @@ describe("GET /v1/conversations with groupId", () => {
329
329
  ]);
330
330
  });
331
331
 
332
- test("a group-scoped page is ordered by the user's arrangement", async () => {
333
- // Pinned and custom groups are drag-reorderable, so display order wins
334
- // over recency inside a group.
335
- seedPinned("third", 2);
336
- seedPinned("first", 0);
337
- seedPinned("second", 1);
332
+ test("a group-scoped page is ordered by recency, not by display_order", async () => {
333
+ /* `display_order` still holds values for anyone who arranged rows by hand
334
+ before that affordance was removed, so the column is set here to the
335
+ REVERSE of the expected result: a read that consults it again fails
336
+ rather than passing by coincidence. Seeded oldest-first so insertion
337
+ order cannot be mistaken for the assertion either. */
338
+ const oldest = seedPinned("oldest", 0);
339
+ const middle = seedPinned("middle", 1);
340
+ const newest = seedPinned("newest", 2);
341
+ for (const [id, at] of [
342
+ [oldest, 1_000],
343
+ [middle, 5_000],
344
+ [newest, 9_000],
345
+ ] as const) {
346
+ rawRun(
347
+ "test:setLastMessageAt",
348
+ "UPDATE conversations SET last_message_at = ? WHERE id = ?",
349
+ at,
350
+ id,
351
+ );
352
+ }
338
353
 
339
354
  const result = (await invoke({ groupId: "system:pinned" })) as ListResponse;
340
355
 
341
356
  expect(result.conversations.map((c) => c.title)).toEqual([
342
- "first",
343
- "second",
344
- "third",
357
+ "newest",
358
+ "middle",
359
+ "oldest",
345
360
  ]);
346
361
  });
347
362
 
@@ -434,10 +449,9 @@ describe("GET /v1/conversations with groupId", () => {
434
449
  expect(custom.conversations.map((c) => c.title)).toEqual(["car-1"]);
435
450
  });
436
451
 
437
- test("system buckets other than Pinned sort by recency, not stale display order", async () => {
438
- // `display_order` persists through moves, so honouring it for
439
- // system:background would order that section differently depending on
440
- // whether it was fetched by conversationType or by groupId.
452
+ test("a surfaced background row sorts by recency, not stale display order", async () => {
453
+ // `display_order` persists through moves, so a row that carries one from
454
+ // an earlier group must not have it resurface as a sort key here.
441
455
  const older = createConversation({
442
456
  title: "older",
443
457
  conversationType: "background",
@@ -980,7 +980,12 @@ async function initiateVerificationChallenge(params: {
980
980
  try {
981
981
  [existingChallenge, existingSession] = await Promise.all([
982
982
  getPendingSession(sourceChannel),
983
- findActiveSession(sourceChannel),
983
+ // Scoped to this sender. Reading the channel's latest and comparing
984
+ // its `expectedExternalUserId` misses their session whenever somebody
985
+ // else started more recently.
986
+ findActiveSession(sourceChannel, {
987
+ expectedExternalUserId: senderUserId,
988
+ }),
984
989
  ]);
985
990
  } catch (err) {
986
991
  log.warn(
@@ -992,8 +997,7 @@ async function initiateVerificationChallenge(params: {
992
997
  const senderHasPending =
993
998
  (existingChallenge &&
994
999
  existingChallenge.expectedExternalUserId === senderUserId) ||
995
- (existingSession &&
996
- existingSession.expectedExternalUserId === senderUserId);
1000
+ existingSession != null;
997
1001
  if (senderHasPending) {
998
1002
  log.debug(
999
1003
  {
@@ -122,8 +122,9 @@ describe("handleGuardianActivationIntercept", () => {
122
122
  identityBindingStatus: "bound",
123
123
  destinationAddress: "chat-123",
124
124
  verificationPurpose: "guardian",
125
- // No session was read: the create is a gateway-side create-if-absent.
126
- ifNoneActive: true,
125
+ // No session was read for this sender, so the create is a
126
+ // sender-scoped create-if-absent.
127
+ ifNoneActiveForExternalUserId: "user-42",
127
128
  });
128
129
 
129
130
  // Verify deliverChannelReply was called with the welcome/verify message
@@ -243,7 +244,11 @@ describe("handleGuardianActivationIntercept", () => {
243
244
  expect(emitNotificationSignalCalls).toHaveLength(0);
244
245
  });
245
246
 
246
- test("existing active session from different sender allows superseding", async () => {
247
+ test("someone else verifying does not turn this sender away", async () => {
248
+ // The read is scoped to the sender, so another person's live session is
249
+ // invisible here and this activation proceeds as a first one. Without the
250
+ // scope it would return the stranger's session and this sender would be
251
+ // told a verification is "already in progress" that is not theirs.
247
252
  gatewaySessions.state.activeSession = {
248
253
  id: "existing-sess",
249
254
  channel: "telegram",
@@ -254,16 +259,14 @@ describe("handleGuardianActivationIntercept", () => {
254
259
 
255
260
  const result = await handleGuardianActivationIntercept(makeParams());
256
261
 
257
- // Should proceed and create a new session (superseding the stale one)
258
- expect(result).not.toBeNull();
259
- const body = result!;
260
- expect(body).toEqual({ accepted: true, guardianActivation: true });
262
+ expect(result).toEqual({ accepted: true, guardianActivation: true });
261
263
  expect(gatewaySessions.calls.create).toHaveLength(1);
262
- // Deliberate supersede: the create-if-absent guard is omitted so the
263
- // stale session gets revoked.
264
+ // Carrying the guard is what keeps the stranger's code alive: the mint
265
+ // supersedes by bound identity, and this sender is not that identity.
264
266
  expect(
265
- (gatewaySessions.calls.create[0] as Record<string, unknown>).ifNoneActive,
266
- ).toBeUndefined();
267
+ (gatewaySessions.calls.create[0] as Record<string, unknown>)
268
+ .ifNoneActiveForExternalUserId,
269
+ ).toBe("user-42");
267
270
  expect(emitNotificationSignalCalls).toHaveLength(1);
268
271
  });
269
272
 
@@ -133,7 +133,11 @@ export async function handleGuardianActivationIntercept(
133
133
  // normal pipeline handle the message.
134
134
  let existingSession: VerificationSessionWire | null;
135
135
  try {
136
- existingSession = await findActiveSession(sourceChannel);
136
+ // This sender's own session. The channel may carry others, and what the
137
+ // guard below needs to know is whether THIS activation is a duplicate.
138
+ existingSession = await findActiveSession(sourceChannel, {
139
+ expectedExternalUserId: rawSenderId,
140
+ });
137
141
  } catch (err) {
138
142
  log.warn(
139
143
  { err, sourceChannel },
@@ -158,25 +162,18 @@ export async function handleGuardianActivationIntercept(
158
162
  return { accepted: true, guardianActivationPending: true };
159
163
  };
160
164
 
165
+ // The read is scoped to this sender, so anything it returned is this
166
+ // sender's own activation already in flight.
161
167
  if (existingSession) {
162
- // Only block if the session belongs to the same sender. If a different
163
- // user triggered the session, let this sender proceed (they'll supersede
164
- // the stale session via createOutboundSession's revocation logic).
165
- const sessionOwner =
166
- existingSession.expectedExternalUserId ?? existingSession.expectedChatId;
167
- if (
168
- sessionOwner === rawSenderId ||
169
- sessionOwner === conversationExternalId
170
- ) {
171
- return respondActivationPending();
172
- }
168
+ return respondActivationPending();
173
169
  }
174
170
 
175
171
  // ── Create verification session ──
176
- // When the read above saw no active session, ifNoneActive makes the create
177
- // a gateway-side create-if-absent: a concurrent activation that minted in
178
- // between conflicts here instead of revoking that first code. A supersede
179
- // (stale session from a different sender) deliberately omits the guard.
172
+ // The read above saw no session for this sender, so the sender-scoped
173
+ // create-if-absent makes the mint atomic: a concurrent activation from the
174
+ // same sender that minted in between conflicts here instead of revoking that
175
+ // first code. Scoped to the sender rather than the channel, because another
176
+ // person verifying at the same time is ordinary and must not block this.
180
177
  let sessionResult: Awaited<
181
178
  ReturnType<typeof createOutboundSessionConditional>
182
179
  >;
@@ -188,7 +185,7 @@ export async function handleGuardianActivationIntercept(
188
185
  identityBindingStatus: "bound",
189
186
  destinationAddress: conversationExternalId,
190
187
  verificationPurpose: "guardian",
191
- ...(existingSession ? {} : { ifNoneActive: true }),
188
+ ifNoneActiveForExternalUserId: rawSenderId,
192
189
  });
193
190
  } catch (err) {
194
191
  log.warn(
@@ -875,7 +875,13 @@ export async function resendOutbound(
875
875
  const channel = params.channel;
876
876
  const originConversationId = params.originConversationId;
877
877
 
878
- const session = await findActiveSession(channel);
878
+ // Scoped to the guardian's own flow. A channel can carry a live session per
879
+ // person verifying, so an unscoped lookup returns whoever started most
880
+ // recently, which on a busy channel is a requester rather than the guardian
881
+ // this resend is for.
882
+ const session = await findActiveSession(channel, {
883
+ verificationPurpose: "guardian",
884
+ });
879
885
  if (!session) {
880
886
  return {
881
887
  success: false,
@@ -1064,7 +1070,11 @@ export async function cancelOutbound(
1064
1070
  ): Promise<OutboundActionResult> {
1065
1071
  const channel = params.channel;
1066
1072
 
1067
- const session = await findActiveSession(channel);
1073
+ // Scoped the same way as resend: cancelling the guardian's verification must
1074
+ // not revoke a requester's live session.
1075
+ const session = await findActiveSession(channel, {
1076
+ verificationPurpose: "guardian",
1077
+ });
1068
1078
  if (!session) {
1069
1079
  return {
1070
1080
  success: false,
@@ -48,11 +48,14 @@ export async function executeCallStart(
48
48
 
49
49
  const requestedPhone = normalizePhoneNumber(parsed.phone_number);
50
50
  if (requestedPhone) {
51
- const activeVoiceVerification = await findActiveSession("phone");
52
- const verificationDestination =
53
- activeVoiceVerification?.destinationAddress ??
54
- activeVoiceVerification?.expectedPhoneE164;
55
- if (verificationDestination === requestedPhone) {
51
+ // Scoped to the number being called. Voice sessions bind
52
+ // `expectedExternalUserId` to the E.164 number, and several can be live
53
+ // at once, so reading the latest and comparing would miss a verification
54
+ // for this number whenever another one started more recently.
55
+ const activeVoiceVerification = await findActiveSession("phone", {
56
+ expectedExternalUserId: requestedPhone,
57
+ });
58
+ if (activeVoiceVerification) {
56
59
  return {
57
60
  content: [
58
61
  "Error: A guardian voice verification call is already active for this number.",