@vellumai/assistant 0.11.7-dev.202608311516.e0ee55e → 0.11.7-dev.202608311714.ac2d126

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.11.7-dev.202608311516.e0ee55e",
3
+ "version": "0.11.7-dev.202608311714.ac2d126",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -435,6 +435,307 @@ describe("loadFromDb history repair", () => {
435
435
  ]);
436
436
  });
437
437
 
438
+ test("a stored reaction row loads as rendered text, not the sentinel", async () => {
439
+ mockConversation = {
440
+ id: "conv-1",
441
+ contextSummary: null,
442
+ contextCompactedMessageCount: 0,
443
+ totalInputTokens: 0,
444
+ totalOutputTokens: 0,
445
+ totalEstimatedCost: 0,
446
+ };
447
+ mockDbMessages = [
448
+ {
449
+ id: "m1",
450
+ role: "user",
451
+ content: [{ type: "text", text: "Deploy is done" }],
452
+ metadata: JSON.stringify({
453
+ providerMeta: JSON.stringify({
454
+ source: "discord",
455
+ conversationExternalId: "chan-1",
456
+ messageId: "555.1",
457
+ eventKind: "message",
458
+ }),
459
+ }),
460
+ },
461
+ {
462
+ id: "m2",
463
+ role: "user",
464
+ content: [{ type: "text", text: "[reaction]" }],
465
+ metadata: JSON.stringify({
466
+ providerMeta: JSON.stringify({
467
+ source: "discord",
468
+ conversationExternalId: "chan-1",
469
+ eventKind: "reaction",
470
+ reaction: {
471
+ targetMessageId: "555.1",
472
+ emoji: "thumbsup",
473
+ op: "added",
474
+ actorDisplayName: "Alice",
475
+ },
476
+ }),
477
+ }),
478
+ },
479
+ ];
480
+
481
+ const conversation = makeConversation();
482
+ await conversation.loadFromDb();
483
+ const messages = conversation.getMessages();
484
+
485
+ // History repair merges the two adjacent user rows into one message;
486
+ // what matters is that the model reads the rendered fact, never the
487
+ // sentinel.
488
+ const allText = messages
489
+ .flatMap((m) => m.content)
490
+ .filter((b) => b.type === "text")
491
+ .map((b) => (b.type === "text" ? b.text : ""))
492
+ .join("\n");
493
+ expect(allText).not.toContain("[reaction]");
494
+ expect(allText).toContain(
495
+ 'Alice reacted with :thumbsup: to the message "Deploy is done"',
496
+ );
497
+ expect(allText).toContain("<external_content");
498
+ });
499
+
500
+ test("markHistoryStale makes the next ensureActorScopedHistory reload", async () => {
501
+ mockConversation = {
502
+ id: "conv-1",
503
+ contextSummary: null,
504
+ contextCompactedMessageCount: 0,
505
+ totalInputTokens: 0,
506
+ totalOutputTokens: 0,
507
+ totalEstimatedCost: 0,
508
+ };
509
+ mockDbMessages = [
510
+ {
511
+ id: "m1",
512
+ role: "user",
513
+ content: [{ type: "text", text: "Hello" }],
514
+ },
515
+ {
516
+ id: "m2",
517
+ role: "assistant",
518
+ content: [{ type: "text", text: "Hi" }],
519
+ },
520
+ ];
521
+
522
+ const conversation = makeConversation();
523
+ conversation.setTrustContext({
524
+ trustClass: "guardian",
525
+ sourceChannel: "telegram",
526
+ });
527
+ await conversation.loadFromDb();
528
+ expect(conversation.getMessages()).toHaveLength(2);
529
+
530
+ // A channel event lands straight in the store while the conversation
531
+ // stays resident.
532
+ mockDbMessages.push({
533
+ id: "m3",
534
+ role: "user",
535
+ content: [{ type: "text", text: "[reaction]" }],
536
+ });
537
+
538
+ // Same actor, no stale mark: the resident history is reused.
539
+ await conversation.ensureActorScopedHistory();
540
+ expect(conversation.getMessages()).toHaveLength(2);
541
+
542
+ conversation.markHistoryStale();
543
+ await conversation.ensureActorScopedHistory();
544
+ expect(conversation.getMessages()).toHaveLength(3);
545
+ });
546
+
547
+ test("a deleted row loads as the deletion marker, not its original text", async () => {
548
+ mockConversation = {
549
+ id: "conv-1",
550
+ contextSummary: null,
551
+ contextCompactedMessageCount: 0,
552
+ totalInputTokens: 0,
553
+ totalOutputTokens: 0,
554
+ totalEstimatedCost: 0,
555
+ };
556
+ mockDbMessages = [
557
+ {
558
+ id: "m1",
559
+ role: "user",
560
+ content: [
561
+ { type: "text", text: "Please forget this password: hunter2" },
562
+ ],
563
+ metadata: JSON.stringify({
564
+ providerMeta: JSON.stringify({
565
+ source: "discord",
566
+ conversationExternalId: "chan-1",
567
+ messageId: "555.1",
568
+ eventKind: "message",
569
+ deletedAt: 1700000001000,
570
+ }),
571
+ }),
572
+ },
573
+ {
574
+ id: "m2",
575
+ role: "assistant",
576
+ content: [{ type: "text", text: "Understood" }],
577
+ },
578
+ ];
579
+
580
+ const conversation = makeConversation();
581
+ await conversation.loadFromDb();
582
+ const allText = conversation
583
+ .getMessages()
584
+ .flatMap((m) => m.content)
585
+ .filter((b) => b.type === "text")
586
+ .map((b) => (b.type === "text" ? b.text : ""))
587
+ .join("\n");
588
+ expect(allText).toContain("[This message was deleted]");
589
+ expect(allText).not.toContain("hunter2");
590
+ });
591
+
592
+ test("a reaction never quotes a target that was later deleted", async () => {
593
+ mockConversation = {
594
+ id: "conv-1",
595
+ contextSummary: null,
596
+ contextCompactedMessageCount: 0,
597
+ totalInputTokens: 0,
598
+ totalOutputTokens: 0,
599
+ totalEstimatedCost: 0,
600
+ };
601
+ mockDbMessages = [
602
+ {
603
+ id: "m1",
604
+ role: "user",
605
+ content: [{ type: "text", text: "secret text" }],
606
+ metadata: JSON.stringify({
607
+ providerMeta: JSON.stringify({
608
+ source: "discord",
609
+ conversationExternalId: "chan-1",
610
+ messageId: "555.1",
611
+ eventKind: "message",
612
+ deletedAt: 1700000001000,
613
+ }),
614
+ }),
615
+ },
616
+ {
617
+ id: "m2",
618
+ role: "user",
619
+ content: [{ type: "text", text: "[reaction]" }],
620
+ metadata: JSON.stringify({
621
+ providerMeta: JSON.stringify({
622
+ source: "discord",
623
+ conversationExternalId: "chan-1",
624
+ eventKind: "reaction",
625
+ reaction: {
626
+ targetMessageId: "555.1",
627
+ emoji: "thumbsup",
628
+ op: "added",
629
+ actorDisplayName: "Alice",
630
+ },
631
+ }),
632
+ }),
633
+ },
634
+ ];
635
+
636
+ const conversation = makeConversation();
637
+ await conversation.loadFromDb();
638
+ const allText = conversation
639
+ .getMessages()
640
+ .flatMap((m) => m.content)
641
+ .filter((b) => b.type === "text")
642
+ .map((b) => (b.type === "text" ? b.text : ""))
643
+ .join("\n");
644
+ expect(allText).toContain("reacted with :thumbsup: to an earlier message");
645
+ expect(allText).not.toContain("secret text");
646
+ });
647
+
648
+ test("a reaction row does not count as a turn on rehydration", async () => {
649
+ mockConversation = {
650
+ id: "conv-1",
651
+ contextSummary: null,
652
+ contextCompactedMessageCount: 0,
653
+ totalInputTokens: 0,
654
+ totalOutputTokens: 0,
655
+ totalEstimatedCost: 0,
656
+ };
657
+ mockDbMessages = [
658
+ {
659
+ id: "m1",
660
+ role: "user",
661
+ content: [{ type: "text", text: "Hello" }],
662
+ },
663
+ {
664
+ id: "m2",
665
+ role: "assistant",
666
+ content: [{ type: "text", text: "Hi" }],
667
+ },
668
+ {
669
+ id: "m3",
670
+ role: "user",
671
+ content: [{ type: "text", text: "[reaction]" }],
672
+ metadata: JSON.stringify({
673
+ providerMeta: JSON.stringify({
674
+ source: "discord",
675
+ conversationExternalId: "chan-1",
676
+ eventKind: "reaction",
677
+ reaction: {
678
+ targetMessageId: "555.1",
679
+ emoji: "thumbsup",
680
+ op: "added",
681
+ },
682
+ }),
683
+ }),
684
+ },
685
+ ];
686
+
687
+ const conversation = makeConversation();
688
+ await conversation.loadFromDb();
689
+ // One real user message; the reaction row never dispatched a turn, so
690
+ // the rehydrated counter must match the live counter's one increment.
691
+ expect(conversation.turnCount).toBe(1);
692
+ });
693
+
694
+ test("a slackMeta-shaped reaction row renders with its actor id as origin", async () => {
695
+ mockConversation = {
696
+ id: "conv-1",
697
+ contextSummary: null,
698
+ contextCompactedMessageCount: 0,
699
+ totalInputTokens: 0,
700
+ totalOutputTokens: 0,
701
+ totalEstimatedCost: 0,
702
+ };
703
+ mockDbMessages = [
704
+ {
705
+ id: "m1",
706
+ role: "user",
707
+ content: [{ type: "text", text: "[reaction]" }],
708
+ metadata: JSON.stringify({
709
+ slackMeta: JSON.stringify({
710
+ source: "slack",
711
+ channelId: "C123",
712
+ channelTs: "1700000000.111111",
713
+ eventKind: "reaction",
714
+ actorExternalUserId: "U_REACTOR",
715
+ displayName: "Alice",
716
+ reaction: {
717
+ emoji: "tada",
718
+ targetChannelTs: "1700000000.111111",
719
+ op: "added",
720
+ actorDisplayName: "Alice",
721
+ },
722
+ }),
723
+ }),
724
+ },
725
+ ];
726
+
727
+ const conversation = makeConversation();
728
+ await conversation.loadFromDb();
729
+ const allText = conversation
730
+ .getMessages()
731
+ .flatMap((m) => m.content)
732
+ .filter((b) => b.type === "text")
733
+ .map((b) => (b.type === "text" ? b.text : ""))
734
+ .join("\n");
735
+ expect(allText).toContain("Alice reacted with :tada:");
736
+ expect(allText).toContain('origin="U_REACTOR"');
737
+ });
738
+
438
739
  test("persistUserMessage reloads actor-scoped history before persisting on role switch", async () => {
439
740
  mockConversation = {
440
741
  id: "conv-1",
@@ -106,6 +106,7 @@ function resetState(): void {
106
106
  db.run("DELETE FROM contact_channels");
107
107
  db.run("DELETE FROM contacts");
108
108
  gatewayGuardians = [];
109
+ _conversationMocks.clear();
109
110
  }
110
111
 
111
112
  function seedActiveMember(): void {
@@ -264,6 +265,10 @@ describe("Slack reaction event persistence", () => {
264
265
  expect(row.content).toBe("[reaction]");
265
266
 
266
267
  const envelope = JSON.parse(row.metadata!) as Record<string, unknown>;
268
+ // Provenance keeps the row visible to actor-scoped history loads:
269
+ // filterMessagesForUntrustedActor drops rows with no trust class.
270
+ expect(envelope.provenanceTrustClass).toBe("trusted_contact");
271
+ expect(envelope.provenanceSourceChannel).toBe("slack");
267
272
  const slackMetaRaw = envelope.slackMeta;
268
273
  expect(typeof slackMetaRaw).toBe("string");
269
274
 
@@ -276,6 +281,9 @@ describe("Slack reaction event persistence", () => {
276
281
  // Slack sends no thread on a reaction, so the row claims none.
277
282
  expect(slackMeta!.threadTs).toBeUndefined();
278
283
  expect(slackMeta!.displayName).toBe(SLACK_DISPLAY_NAME);
284
+ // Stable identity, not the sender-controlled label: the history
285
+ // renderer attributes the fenced line's origin by this id.
286
+ expect(slackMeta!.actorExternalUserId).toBe(SLACK_USER_ID);
279
287
  expect(slackMeta!.reaction).toEqual({
280
288
  emoji: "thumbsup",
281
289
  actorDisplayName: SLACK_DISPLAY_NAME,
@@ -414,6 +422,39 @@ describe("Slack reaction event persistence", () => {
414
422
  expect(rows.length).toBe(1);
415
423
  });
416
424
 
425
+ test("a persisted reaction stale-marks the resident conversation", async () => {
426
+ const conversationId = seedStoredMessage("1700000000.111111");
427
+ const markHistoryStale = mock(() => {});
428
+ _conversationMocks.set(conversationId, {
429
+ markHistoryStale,
430
+ } as unknown as Conversation);
431
+
432
+ const resp = await handleChannelInbound(
433
+ buildReactionRequest("reaction:thumbsup"),
434
+ undefined,
435
+ TEST_BEARER_TOKEN,
436
+ );
437
+ expect(resp.status).toBe(200);
438
+ expect(markHistoryStale).toHaveBeenCalledTimes(1);
439
+ });
440
+
441
+ test("a duplicate reaction does not stale-mark again", async () => {
442
+ const conversationId = seedStoredMessage("1700000000.111111");
443
+ const markHistoryStale = mock(() => {});
444
+ _conversationMocks.set(conversationId, {
445
+ markHistoryStale,
446
+ } as unknown as Conversation);
447
+ const sharedExternalMessageId = `${SLACK_CHANNEL_ID}:1700000000.777777:bob`;
448
+ const makeReq = () =>
449
+ buildReactionRequest("reaction:tada", {
450
+ externalMessageId: sharedExternalMessageId,
451
+ });
452
+
453
+ await handleChannelInbound(makeReq(), undefined, TEST_BEARER_TOKEN);
454
+ await handleChannelInbound(makeReq(), undefined, TEST_BEARER_TOKEN);
455
+ expect(markHistoryStale).toHaveBeenCalledTimes(1);
456
+ });
457
+
417
458
  test("reaction on the assistant's own post lands in that conversation", async () => {
418
459
  // An outbound post opens no inbound event, so the only record of its ts
419
460
  // is the `slackMeta` on the assistant row. Seeded here the way the
@@ -41,6 +41,7 @@ import {
41
41
  derefToolResultReReads,
42
42
  postTurnTruncateToolResults,
43
43
  } from "../context/post-turn-tool-result-truncation.js";
44
+ import { readProviderMetadata } from "../messaging/read-provider-metadata.js";
44
45
  import { isGuardianCardRow } from "../notifications/approval-card-data.js";
45
46
  import { PermissionPrompter } from "../permissions/prompter.js";
46
47
  import { SecretPrompter } from "../permissions/secret-prompter.js";
@@ -55,6 +56,7 @@ import {
55
56
  setConversationProcessingStartedAt,
56
57
  } from "../persistence/conversation-crud.js";
57
58
  import { getResolvedConversationDirPath } from "../persistence/conversation-directories.js";
59
+ import { extractTextFromStoredMessageContent } from "../persistence/message-content.js";
58
60
  import { reportSlowSync } from "../persistence/slow-sync-log.js";
59
61
  import { defaultCompact } from "../plugins/defaults/compaction/compact.js";
60
62
  import {
@@ -173,6 +175,7 @@ import { filterMessagesForUntrustedActor } from "./message-provenance.js";
173
175
  import type { ConversationTransportMetadata } from "./message-types/conversations.js";
174
176
  import { isHostProxyTransport } from "./message-types/conversations.js";
175
177
  import { conversationMetadataSyncTag } from "./message-types/sync.js";
178
+ import { renderReactionHistoryText } from "./reaction-history-render.js";
176
179
  import {
177
180
  resolveSummarizeBoundary,
178
181
  startsNewTurn,
@@ -539,6 +542,7 @@ export class Conversation {
539
542
  /** @internal */ currentTurnSourceActorPrincipalId?: string;
540
543
  /** @internal */ loadedHistoryTrustClass?: TrustClass;
541
544
  /** @internal */ loadedHistoryPersonalMemoryAllowed?: boolean;
545
+ /** @internal */ loadedHistoryStale = false;
542
546
  /** @internal */ voiceCallControlPrompt?: string;
543
547
  /** @internal */ transportHints?: string[];
544
548
  /**
@@ -1063,6 +1067,9 @@ export class Conversation {
1063
1067
 
1064
1068
  async loadFromDb(): Promise<LoadFromDbResult> {
1065
1069
  const loadStartedAt = performance.now();
1070
+ // Cleared before the rows are read: a channel event persisted mid-load
1071
+ // re-marks the flag, so the next turn reloads rather than missing it.
1072
+ this.loadedHistoryStale = false;
1066
1073
  const trustClass = this.trustContext?.trustClass;
1067
1074
  const canAccessMemory = resolveCapabilities(trustClass).canAccessMemory;
1068
1075
  const allDbMessages = getMessages(this.conversationId);
@@ -1153,6 +1160,36 @@ export class Conversation {
1153
1160
  }
1154
1161
  return v3PrunedSlugsMemo;
1155
1162
  };
1163
+ // Provider-id → row-text index for reaction target resolution, built
1164
+ // lazily on the first reaction row: most conversations carry none, so
1165
+ // most loads never walk the rows a second time. Keyed over the full
1166
+ // (unsliced) history so a reaction whose target was compacted out of
1167
+ // context still resolves its quote.
1168
+ let reactionTargetIndexMemo: Map<string, string> | null = null;
1169
+ const resolveReactionTarget = (
1170
+ targetMessageId: string,
1171
+ ): string | undefined => {
1172
+ if (reactionTargetIndexMemo === null) {
1173
+ reactionTargetIndexMemo = new Map();
1174
+ for (const row of dbMessages) {
1175
+ const rowMeta = readProviderMetadata(row.metadata);
1176
+ // A deleted target is a logical erasure (same rule as the Slack
1177
+ // transcript renderer), so its text is never quoted back.
1178
+ if (
1179
+ rowMeta?.eventKind === "message" &&
1180
+ rowMeta.deletedAt === undefined &&
1181
+ rowMeta.messageId &&
1182
+ !reactionTargetIndexMemo.has(rowMeta.messageId)
1183
+ ) {
1184
+ const text = extractTextFromStoredMessageContent(row.content);
1185
+ if (text) {
1186
+ reactionTargetIndexMemo.set(rowMeta.messageId, text);
1187
+ }
1188
+ }
1189
+ }
1190
+ }
1191
+ return reactionTargetIndexMemo.get(targetMessageId);
1192
+ };
1156
1193
  const parsedMessages: Message[] = slicedDbMessages.map((m, index, arr) => {
1157
1194
  const isPreStripped = index < preStrippedCount;
1158
1195
  const role = m.role as "user" | "assistant";
@@ -1160,6 +1197,36 @@ export class Conversation {
1160
1197
 
1161
1198
  content = reinjectAttachmentPathAnnotations(content, role, m.metadata);
1162
1199
 
1200
+ // Channel facts stamped in metadata render at load time rather than
1201
+ // at persist time, so every stored row reads correctly whenever it
1202
+ // was written: a reaction row's "[reaction]" sentinel renders as who
1203
+ // reacted with what to which message, and a deleted row's original
1204
+ // text gives way to a deletion marker (the delete intercepts stamp
1205
+ // metadata and deliberately leave the content column untouched). The
1206
+ // substring guard keeps the per-row metadata parse off rows that can
1207
+ // carry neither fact: both envelopes spell these keys literally, in
1208
+ // providerMeta and in nested slackMeta alike.
1209
+ if (
1210
+ role === "user" &&
1211
+ m.metadata &&
1212
+ (m.metadata.includes("reaction") || m.metadata.includes("deletedAt"))
1213
+ ) {
1214
+ const providerMeta = readProviderMetadata(m.metadata);
1215
+ if (providerMeta?.eventKind === "reaction") {
1216
+ const rendered = renderReactionHistoryText(
1217
+ providerMeta,
1218
+ resolveReactionTarget,
1219
+ );
1220
+ if (rendered) {
1221
+ content = [{ type: "text", text: rendered }];
1222
+ }
1223
+ } else if (providerMeta?.deletedAt !== undefined) {
1224
+ // Neutral marker, no actor: Discord deletes can be authorless
1225
+ // (`actorUnattributed`), so the marker never claims who deleted.
1226
+ content = [{ type: "text", text: "[This message was deleted]" }];
1227
+ }
1228
+ }
1229
+
1163
1230
  // Re-inject persisted injection blocks from metadata so it survives
1164
1231
  // conversation reloads (eviction, restart, fork).
1165
1232
  if (role === "user" && m.metadata && !isPreStripped) {
@@ -1533,6 +1600,7 @@ export class Conversation {
1533
1600
  this.trustContext,
1534
1601
  );
1535
1602
  if (
1603
+ !this.loadedHistoryStale &&
1536
1604
  this.loadedHistoryTrustClass === currentTrustClass &&
1537
1605
  this.loadedHistoryPersonalMemoryAllowed === currentPersonalMemoryAllowed
1538
1606
  ) {
@@ -1541,6 +1609,17 @@ export class Conversation {
1541
1609
  await this.loadFromDb();
1542
1610
  }
1543
1611
 
1612
+ /**
1613
+ * Mark the resident history stale: a channel event (a reaction, edit, or
1614
+ * delete) was persisted straight to the store while this conversation was
1615
+ * loaded, so `this.messages` no longer reflects the rows. The next
1616
+ * {@link ensureActorScopedHistory} reloads instead of reusing the resident
1617
+ * history.
1618
+ */
1619
+ markHistoryStale(): void {
1620
+ this.loadedHistoryStale = true;
1621
+ }
1622
+
1544
1623
  /**
1545
1624
  * Deliver an event through the conversation's sink, then to every observer.
1546
1625
  * The single emission point for conversation-level events (activity state,
@@ -0,0 +1,129 @@
1
+ import { describe, expect, test } from "bun:test";
2
+
3
+ import type { ProviderMessageMetadata } from "../messaging/provider-message-metadata.js";
4
+ import { renderReactionHistoryText } from "./reaction-history-render.js";
5
+
6
+ function reactionMeta(
7
+ overrides: Omit<Partial<ProviderMessageMetadata>, "reaction"> & {
8
+ reaction?: Partial<NonNullable<ProviderMessageMetadata["reaction"]>>;
9
+ } = {},
10
+ ): ProviderMessageMetadata {
11
+ const { reaction, ...rest } = overrides;
12
+ return {
13
+ source: "slack",
14
+ conversationExternalId: "C123",
15
+ eventKind: "reaction",
16
+ reaction: {
17
+ targetMessageId: "1716000000.000001",
18
+ emoji: "thumbsup",
19
+ op: "added",
20
+ actorDisplayName: "Alice",
21
+ ...reaction,
22
+ },
23
+ ...rest,
24
+ } as ProviderMessageMetadata;
25
+ }
26
+
27
+ const noTarget = () => undefined;
28
+
29
+ describe("renderReactionHistoryText", () => {
30
+ test("renders an added reaction with the quoted target", () => {
31
+ const rendered = renderReactionHistoryText(
32
+ reactionMeta(),
33
+ () => "Deploy is done",
34
+ );
35
+ expect(rendered).toContain(
36
+ 'Alice reacted with :thumbsup: to the message "Deploy is done"',
37
+ );
38
+ });
39
+
40
+ test("renders a removed reaction", () => {
41
+ const rendered = renderReactionHistoryText(
42
+ reactionMeta({ reaction: { op: "removed" } }),
43
+ noTarget,
44
+ );
45
+ expect(rendered).toContain(
46
+ "Alice removed their :thumbsup: reaction from an earlier message",
47
+ );
48
+ });
49
+
50
+ test("fences the line as untrusted channel content", () => {
51
+ const rendered = renderReactionHistoryText(
52
+ reactionMeta({ actorExternalId: "U123" }),
53
+ noTarget,
54
+ );
55
+ expect(rendered).toContain('<external_content source="slack"');
56
+ expect(rendered).toContain('origin="U123"');
57
+ expect(rendered).toContain("</external_content>");
58
+ });
59
+
60
+ test("non-slack channels fence with the webhook source", () => {
61
+ const rendered = renderReactionHistoryText(
62
+ reactionMeta({ source: "discord" }),
63
+ noTarget,
64
+ );
65
+ expect(rendered).toContain('<external_content source="webhook"');
66
+ });
67
+
68
+ test("keeps a Discord custom-emoji mention form as-is", () => {
69
+ const rendered = renderReactionHistoryText(
70
+ reactionMeta({ reaction: { emoji: "<:vex:12345>" } }),
71
+ noTarget,
72
+ );
73
+ expect(rendered).toContain("reacted with <:vex:12345> to");
74
+ });
75
+
76
+ test("keeps a unicode emoji as-is", () => {
77
+ const rendered = renderReactionHistoryText(
78
+ reactionMeta({ reaction: { emoji: "👍" } }),
79
+ noTarget,
80
+ );
81
+ expect(rendered).toContain("reacted with 👍 to");
82
+ });
83
+
84
+ test("strips ingress fences and collapses whitespace in the quote", () => {
85
+ const rendered = renderReactionHistoryText(
86
+ reactionMeta(),
87
+ () =>
88
+ '<external_content source="slack">\nline one\n line two\n</external_content>',
89
+ );
90
+ expect(rendered).toContain('the message "line one line two"');
91
+ });
92
+
93
+ test("truncates a long quoted target", () => {
94
+ const rendered = renderReactionHistoryText(reactionMeta(), () =>
95
+ "x".repeat(500),
96
+ );
97
+ expect(rendered).toContain(`"${"x".repeat(120)}..."`);
98
+ expect(rendered).not.toContain("x".repeat(121));
99
+ });
100
+
101
+ test("falls back to Someone when no display name is stored", () => {
102
+ const rendered = renderReactionHistoryText(
103
+ reactionMeta({ reaction: { actorDisplayName: undefined } }),
104
+ noTarget,
105
+ );
106
+ expect(rendered).toContain("Someone reacted with");
107
+ });
108
+
109
+ test("prefers the row-level display name over the fallback", () => {
110
+ const rendered = renderReactionHistoryText(
111
+ reactionMeta({
112
+ displayName: "Bob",
113
+ reaction: { actorDisplayName: undefined },
114
+ }),
115
+ noTarget,
116
+ );
117
+ expect(rendered).toContain("Bob reacted with");
118
+ });
119
+
120
+ test("returns null for a message row", () => {
121
+ const meta: ProviderMessageMetadata = {
122
+ source: "slack",
123
+ conversationExternalId: "C123",
124
+ messageId: "1716000000.000001",
125
+ eventKind: "message",
126
+ } as ProviderMessageMetadata;
127
+ expect(renderReactionHistoryText(meta, noTarget)).toBeNull();
128
+ });
129
+ });
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Render a persisted reaction row into the text the model reads.
3
+ *
4
+ * A reaction is stored as a user row whose content is the "[reaction]"
5
+ * sentinel; the fact lives in the row's metadata (`providerMeta.reaction`:
6
+ * who reacted, with which emoji, on which message). The stored row stays
7
+ * canonical and rendering happens at history-load time, so every stored row
8
+ * renders regardless of when it was written and no formatting is frozen
9
+ * into persistence.
10
+ *
11
+ * The actor's display name and the quoted target are sender-authored, so
12
+ * the rendered line is fenced as untrusted content the same way channel
13
+ * message text is fenced at ingress (`inbound-content-prep.ts`).
14
+ *
15
+ * Serves consumers of `Conversation.loadFromDb` history. Slack channel
16
+ * turns build their provider history from rows instead and render
17
+ * reactions through their own transcript renderer
18
+ * (`messaging/providers/slack/render-transcript.ts`), whose tag-line
19
+ * format references targets by alias rather than by quote.
20
+ */
21
+ import type { ProviderMessageMetadata } from "../messaging/provider-message-metadata.js";
22
+ import {
23
+ unwrapExternalContentForDisplay,
24
+ wrapUntrustedContent,
25
+ } from "../security/untrusted-content.js";
26
+
27
+ /**
28
+ * Slack-style emoji names render in colon form. Anything else (a unicode
29
+ * emoji, Discord's `<:name:id>` mention form) is already self-delimiting.
30
+ */
31
+ const EMOJI_NAME_PATTERN = /^[\w+'-]+$/;
32
+
33
+ const TARGET_SNIPPET_MAX_CHARS = 120;
34
+
35
+ function formatEmoji(emoji: string): string {
36
+ return EMOJI_NAME_PATTERN.test(emoji) ? `:${emoji}:` : emoji;
37
+ }
38
+
39
+ /**
40
+ * Flatten a quoted target to one line: the ingress fence is markup around
41
+ * the target's own text, not part of it, so it is unwrapped rather than
42
+ * quoted.
43
+ */
44
+ function snippetOf(text: string): string {
45
+ const flat = unwrapExternalContentForDisplay(text)
46
+ .replace(/\s+/g, " ")
47
+ .trim();
48
+ if (flat.length <= TARGET_SNIPPET_MAX_CHARS) {
49
+ return flat;
50
+ }
51
+ return `${flat.slice(0, TARGET_SNIPPET_MAX_CHARS)}...`;
52
+ }
53
+
54
+ /**
55
+ * The readable line for a reaction row, fenced, or null when the metadata
56
+ * does not describe a reaction (callers keep the row's stored content then).
57
+ *
58
+ * `resolveTargetText` maps the reaction's `targetMessageId` to the target
59
+ * row's text in the same provider id namespace; returning undefined (target
60
+ * compacted away, or never stored) degrades to "an earlier message".
61
+ */
62
+ export function renderReactionHistoryText(
63
+ meta: ProviderMessageMetadata,
64
+ resolveTargetText: (targetMessageId: string) => string | undefined,
65
+ ): string | null {
66
+ if (meta.eventKind !== "reaction" || !meta.reaction) {
67
+ return null;
68
+ }
69
+ const { emoji, op, targetMessageId } = meta.reaction;
70
+ const actor = meta.reaction.actorDisplayName ?? meta.displayName ?? "Someone";
71
+ const verb =
72
+ op === "removed"
73
+ ? `removed their ${formatEmoji(emoji)} reaction from`
74
+ : `reacted with ${formatEmoji(emoji)} to`;
75
+ const target = resolveTargetText(targetMessageId);
76
+ const snippet = target ? snippetOf(target) : "";
77
+ const line = snippet
78
+ ? `${actor} ${verb} the message "${snippet}"`
79
+ : `${actor} ${verb} an earlier message`;
80
+ return wrapUntrustedContent(line, {
81
+ source: meta.source === "slack" ? "slack" : "webhook",
82
+ ...(meta.actorExternalId ? { sourceDetail: meta.actorExternalId } : {}),
83
+ });
84
+ }
@@ -1,4 +1,5 @@
1
1
  import { isToolResultOnlyUserMessage } from "../conversations/message-consolidation.js";
2
+ import { readProviderMetadata } from "../messaging/read-provider-metadata.js";
2
3
  import type { MessageRow } from "../persistence/conversation-crud.js";
3
4
  import { UserError } from "../util/errors.js";
4
5
 
@@ -19,6 +20,17 @@ export function startsNewTurn(msg: MessageRow): boolean {
19
20
  if (msg.role !== "user") {
20
21
  return false;
21
22
  }
23
+ // A reaction row is a channel fact attached to the turn it landed in, not
24
+ // a message that ran one: the agent loop never dispatches for reactions,
25
+ // so counting them would rehydrate a `turnCount` above the live counter
26
+ // and shift turn-indexed memory selection. The substring guard keeps the
27
+ // metadata parse off rows that cannot carry the envelope.
28
+ if (
29
+ msg.metadata?.includes("reaction") &&
30
+ readProviderMetadata(msg.metadata)?.eventKind === "reaction"
31
+ ) {
32
+ return false;
33
+ }
22
34
  return !isToolResultOnlyUserMessage(msg);
23
35
  }
24
36
 
@@ -630,6 +630,9 @@ export async function handleChannelInbound({
630
630
  { deletedAt: Date.now() },
631
631
  );
632
632
  updateMessageMetadata(original.messageId, { providerMeta });
633
+ // The stamp lands in the store only; stale-marking makes a resident
634
+ // conversation's next turn reload and see the row as deleted.
635
+ findConversation(original.conversationId)?.markHistoryStale();
633
636
  log.info(
634
637
  {
635
638
  conversationExternalId,
@@ -650,6 +653,7 @@ export async function handleChannelInbound({
650
653
  // (channel, interface, provenance, etc.) untouched. Content column
651
654
  // is intentionally not updated.
652
655
  updateMessageMetadata(original.messageId, { slackMeta: updatedSlackMeta });
656
+ findConversation(original.conversationId)?.markHistoryStale();
653
657
 
654
658
  log.info(
655
659
  {
@@ -16,6 +16,7 @@
16
16
  * resolvable target is dropped.
17
17
  */
18
18
  import type { ChannelId } from "../../../channels/types.js";
19
+ import { findConversation } from "../../../daemon/conversation-registry.js";
19
20
  import {
20
21
  mergeSlackMetadata,
21
22
  readSlackMetadata,
@@ -227,6 +228,11 @@ export async function handleEditIntercept(
227
228
  // path, so reindex the message into the lexical index — the idempotent
228
229
  // upsert replaces the stale Qdrant point with the edited content.
229
230
  enqueueLexicalIndexForMessage(original.messageId);
231
+ // The rewrite lands in the store only; a resident conversation keeps the
232
+ // pre-edit text in memory until it reloads, so the next turn would answer
233
+ // a revision the sender already replaced. Stale-marking makes that turn's
234
+ // history reload pick up the edit.
235
+ findConversation(original.conversationId)?.markHistoryStale();
230
236
  markProcessed(editResult.eventId);
231
237
  log.info(
232
238
  { assistantId, sourceMessageId, messageId: original.messageId },
@@ -26,14 +26,19 @@ import {
26
26
  } from "@vellumai/gateway-client";
27
27
 
28
28
  import type { ChannelId, InterfaceId } from "../../../channels/types.js";
29
+ import { findConversation } from "../../../daemon/conversation-registry.js";
29
30
  import { getDiskPressureStatus } from "../../../daemon/disk-pressure-guard.js";
30
31
  import { classifyDiskPressureTurnPolicy } from "../../../daemon/disk-pressure-policy.js";
32
+ import type { TrustContext } from "../../../daemon/trust-context-types.js";
31
33
  import type { ProviderMessageMetadata } from "../../../messaging/provider-message-metadata.js";
32
34
  import {
33
35
  type SlackMessageMetadata,
34
36
  writeSlackMetadata,
35
37
  } from "../../../messaging/providers/slack/message-metadata.js";
36
- import { addMessage } from "../../../persistence/conversation-crud.js";
38
+ import {
39
+ addMessage,
40
+ provenanceFromTrustContext,
41
+ } from "../../../persistence/conversation-crud.js";
37
42
  import {
38
43
  findInboundEvent,
39
44
  findMessageBySourceId,
@@ -43,6 +48,7 @@ import {
43
48
  } from "../../../persistence/delivery-crud.js";
44
49
  import { markProcessed } from "../../../persistence/delivery-status.js";
45
50
  import { getLogger } from "../../../util/logger.js";
51
+ import { toTrustContext } from "../../actor-trust-resolver.js";
46
52
  import type { ApprovalConversationGenerator } from "../../http-types.js";
47
53
  import {
48
54
  actorTrustContextFromVerdict,
@@ -249,9 +255,17 @@ export async function handleReactionIntercept(
249
255
  sourceChannel,
250
256
  reaction,
251
257
  actorDisplayName,
258
+ actorExternalId: canonicalSenderId ?? rawSenderId ?? undefined,
252
259
  reactedMessageTs,
253
260
  duplicate: result.duplicate,
261
+ trustCtx: toTrustContext(trustCtx, conversationExternalId),
254
262
  });
263
+ if (!result.duplicate) {
264
+ // Reactions never drive a turn, so a resident conversation would
265
+ // otherwise carry the new row only after eviction. Marking it stale
266
+ // makes the next turn's history reload pick the reaction up.
267
+ findConversation(result.conversationId)?.markHistoryStale();
268
+ }
255
269
  } catch (err) {
256
270
  log.error(
257
271
  { err, conversationId: result.conversationId, eventId: result.eventId },
@@ -283,8 +297,22 @@ async function persistReactionAsMessage(params: {
283
297
  sourceChannel: ChannelId;
284
298
  reaction: InboundReactionPayload;
285
299
  actorDisplayName?: string;
300
+ /**
301
+ * The reactor's stable channel identity, canonical when resolution
302
+ * succeeded. Persisted as the envelope's actor id: a display name is
303
+ * sender-controlled labeling, and the rendered history line attributes
304
+ * its fenced content by this id (`origin`), never by the label.
305
+ */
306
+ actorExternalId?: string;
286
307
  reactedMessageTs: string;
287
308
  duplicate: boolean;
309
+ /**
310
+ * The reactor's trust context. Persisted as row provenance so actor-scoped
311
+ * history loads keep the row: `filterMessagesForUntrustedActor` drops any
312
+ * row with no `provenanceTrustClass`, which would hide every reaction from
313
+ * non-guardian turns.
314
+ */
315
+ trustCtx: TrustContext;
288
316
  }): Promise<void> {
289
317
  if (params.duplicate) {
290
318
  return;
@@ -299,6 +327,9 @@ async function persistReactionAsMessage(params: {
299
327
  source: params.sourceChannel,
300
328
  conversationExternalId: params.conversationExternalId,
301
329
  eventKind: "reaction",
330
+ ...(params.actorExternalId
331
+ ? { actorExternalId: params.actorExternalId }
332
+ : {}),
302
333
  ...(params.actorDisplayName
303
334
  ? { displayName: params.actorDisplayName }
304
335
  : {}),
@@ -316,7 +347,10 @@ async function persistReactionAsMessage(params: {
316
347
  "user",
317
348
  "[reaction]",
318
349
  {
319
- metadata: { providerMeta: JSON.stringify(providerMeta) },
350
+ metadata: {
351
+ ...provenanceFromTrustContext(params.trustCtx),
352
+ providerMeta: JSON.stringify(providerMeta),
353
+ },
320
354
  skipIndexing: true,
321
355
  },
322
356
  );
@@ -335,6 +369,9 @@ async function persistReactionAsMessage(params: {
335
369
  // every reader treats as "not in a thread" anyway, and storing it makes
336
370
  // the row false evidence that a thread belongs to this conversation
337
371
  // (`legacySlackConversationHasThreadEvidence`).
372
+ ...(params.actorExternalId
373
+ ? { actorExternalUserId: params.actorExternalId }
374
+ : {}),
338
375
  ...(params.actorDisplayName
339
376
  ? { displayName: params.actorDisplayName }
340
377
  : {}),
@@ -355,7 +392,10 @@ async function persistReactionAsMessage(params: {
355
392
  "user",
356
393
  "[reaction]",
357
394
  {
358
- metadata: { slackMeta: writeSlackMetadata(slackMeta) },
395
+ metadata: {
396
+ ...provenanceFromTrustContext(params.trustCtx),
397
+ slackMeta: writeSlackMetadata(slackMeta),
398
+ },
359
399
  skipIndexing: true,
360
400
  },
361
401
  );