@vellumai/assistant 0.10.4-dev.202607011452.4dbd565 → 0.10.4-dev.202607011653.a5dd422

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.
Files changed (43) hide show
  1. package/bun.lock +0 -1
  2. package/node_modules/@vellumai/gateway-client/src/index.ts +4 -0
  3. package/node_modules/@vellumai/gateway-client/src/outbound-contract.ts +77 -0
  4. package/openapi.yaml +62 -0
  5. package/package.json +1 -2
  6. package/src/__tests__/assistant-attachments.test.ts +62 -4
  7. package/src/__tests__/call-controller.test.ts +0 -1
  8. package/src/__tests__/channel-retry-sweep.test.ts +76 -64
  9. package/src/__tests__/relay-server.test.ts +0 -4
  10. package/src/__tests__/voice-scoped-grant-consumer.test.ts +1 -7
  11. package/src/__tests__/voice-session-bridge.test.ts +1 -10
  12. package/src/calls/call-pointer-messages.ts +3 -2
  13. package/src/calls/relay-server.ts +2 -10
  14. package/src/calls/voice-session-bridge.ts +0 -34
  15. package/src/channels/slack-thread-store.ts +12 -0
  16. package/src/cli/commands/__tests__/conversations-slack.test.ts +1 -0
  17. package/src/daemon/assistant-attachments.ts +42 -0
  18. package/src/daemon/lifecycle.ts +0 -26
  19. package/src/home/__tests__/feed-writer.test.ts +247 -1
  20. package/src/home/feed-writer.ts +61 -0
  21. package/src/messaging/providers/__tests__/transport-dispatch.test.ts +20 -0
  22. package/src/messaging/providers/channel-transport.ts +6 -0
  23. package/src/messaging/providers/index.ts +3 -0
  24. package/src/messaging/providers/slack/api.ts +105 -0
  25. package/src/messaging/providers/slack/send.test.ts +6 -0
  26. package/src/messaging/providers/slack/send.ts +54 -1
  27. package/src/messaging/providers/slack/transport.ts +7 -0
  28. package/src/persistence/conversation-crud.ts +108 -96
  29. package/src/persistence/delivery-channels.ts +0 -82
  30. package/src/persistence/delivery-crud.ts +27 -6
  31. package/src/persistence/llm-request-log-store.ts +35 -19
  32. package/src/runtime/channel-retry-sweep.ts +18 -24
  33. package/src/runtime/finalize-event-delivery.ts +30 -16
  34. package/src/runtime/routes/__tests__/home-feed-routes.test.ts +142 -1
  35. package/src/runtime/routes/home-feed-routes.ts +60 -1
  36. package/src/runtime/routes/inbound-stages/background-dispatch.test.ts +76 -270
  37. package/src/runtime/routes/inbound-stages/background-dispatch.ts +17 -113
  38. package/src/runtime/slack-no-response.ts +47 -0
  39. package/src/runtime/slack-reply-session.test.ts +506 -0
  40. package/src/runtime/slack-reply-session.ts +359 -0
  41. package/src/runtime/slack-task-progress.ts +95 -0
  42. package/src/tools/terminal/safe-env.ts +1 -0
  43. package/src/runtime/slack-dm-text-delivery.ts +0 -177
package/bun.lock CHANGED
@@ -37,7 +37,6 @@
37
37
  "pino": "9.14.0",
38
38
  "pino-pretty": "13.1.3",
39
39
  "playwright": "1.58.2",
40
- "postgres": "3.4.8",
41
40
  "quickjs-emscripten": "0.32.0",
42
41
  "re2js": "2.8.3",
43
42
  "remark-gfm": "4.0.1",
@@ -27,6 +27,8 @@ export {
27
27
  ChannelDeliveryResultSchema,
28
28
  ChannelReplyPayloadSchema,
29
29
  PermissionRequestDetailsSchema,
30
+ SlackStreamOpSchema,
31
+ SlackStreamTaskSchema,
30
32
  } from "./outbound-contract.js";
31
33
 
32
34
  export type {
@@ -36,6 +38,8 @@ export type {
36
38
  ChannelDeliveryResult,
37
39
  ChannelReplyPayload,
38
40
  PermissionRequestDetails,
41
+ SlackStreamOp,
42
+ SlackStreamTask,
39
43
  } from "./outbound-contract.js";
40
44
 
41
45
  // Inbound contract (gateway → daemon) — Zod schemas + derived types
@@ -61,6 +61,81 @@ export const ApprovalUIMetadataSchema = z.object({
61
61
 
62
62
  export type ApprovalUIMetadata = z.infer<typeof ApprovalUIMetadataSchema>;
63
63
 
64
+ // ---------------------------------------------------------------------------
65
+ // Slack streaming operations
66
+ // ---------------------------------------------------------------------------
67
+
68
+ /**
69
+ * One task card in a Slack streamed plan. Mirrors the `task_update` chunk of
70
+ * the Slack streaming API: an ordered, status-bearing step the assistant is
71
+ * working through. `title` is capped at 256 characters by Slack.
72
+ *
73
+ * @see https://docs.slack.dev/reference/methods/chat.appendStream/
74
+ */
75
+ export const SlackStreamTaskSchema = z.object({
76
+ id: z.string(),
77
+ title: z.string(),
78
+ status: z.enum(["pending", "in_progress", "complete", "error"]),
79
+ details: z.string().optional(),
80
+ output: z.string().optional(),
81
+ });
82
+
83
+ export type SlackStreamTask = z.infer<typeof SlackStreamTaskSchema>;
84
+
85
+ /**
86
+ * A single Slack streaming operation, mapping directly onto the
87
+ * `chat.startStream` / `chat.appendStream` / `chat.stopStream` Web API methods.
88
+ *
89
+ * `start` opens a streamed reply on a thread and returns the stream `ts`;
90
+ * `append` adds markdown (and optional task cards) to that stream; `stop`
91
+ * finalizes it, optionally rendering rich Block Kit blocks below the streamed
92
+ * body. Blocks are only accepted on `stop` — during the stream, Slack renders
93
+ * the `markdownText` natively.
94
+ *
95
+ * @see https://docs.slack.dev/reference/methods/chat.startStream/
96
+ * @see https://docs.slack.dev/reference/methods/chat.appendStream/
97
+ * @see https://docs.slack.dev/reference/methods/chat.stopStream/
98
+ */
99
+ export const SlackStreamOpSchema = z
100
+ .discriminatedUnion("action", [
101
+ z.object({
102
+ action: z.literal("start"),
103
+ threadTs: z.string(),
104
+ markdownText: z.string().optional(),
105
+ taskDisplayMode: z.literal("plan").optional(),
106
+ tasks: z.array(SlackStreamTaskSchema).optional(),
107
+ }),
108
+ z.object({
109
+ action: z.literal("append"),
110
+ streamTs: z.string(),
111
+ markdownText: z.string().optional(),
112
+ tasks: z.array(SlackStreamTaskSchema).optional(),
113
+ }),
114
+ z.object({
115
+ action: z.literal("stop"),
116
+ streamTs: z.string(),
117
+ markdownText: z.string().optional(),
118
+ blocks: z.array(z.custom<KnownBlock>()).optional(),
119
+ tasks: z.array(SlackStreamTaskSchema).optional(),
120
+ }),
121
+ ])
122
+ .superRefine((op, ctx) => {
123
+ // Slack requires either `markdown_text` or `chunks` on `start`/`append`; a
124
+ // task-only operation advances the plan block without new body text.
125
+ if (
126
+ (op.action === "start" || op.action === "append") &&
127
+ op.markdownText === undefined &&
128
+ op.tasks === undefined
129
+ ) {
130
+ ctx.addIssue({
131
+ code: z.ZodIssueCode.custom,
132
+ message: `${op.action} requires markdownText or tasks`,
133
+ });
134
+ }
135
+ });
136
+
137
+ export type SlackStreamOp = z.infer<typeof SlackStreamOpSchema>;
138
+
64
139
  // ---------------------------------------------------------------------------
65
140
  // Channel reply payload — the full outbound wire format
66
141
  // ---------------------------------------------------------------------------
@@ -103,6 +178,8 @@ export const ChannelReplyPayloadSchema = z.object({
103
178
  loadingMessages: z.array(z.string()).optional(),
104
179
  })
105
180
  .optional(),
181
+ /** When provided, perform one Slack streaming operation (start/append/stop). */
182
+ slackStream: SlackStreamOpSchema.optional(),
106
183
  });
107
184
 
108
185
  export type ChannelReplyPayload = z.infer<typeof ChannelReplyPayloadSchema>;
package/openapi.yaml CHANGED
@@ -12834,6 +12834,68 @@ paths:
12834
12834
  description: Feed item or action not found
12835
12835
  "500":
12836
12836
  description: Failed to create conversation
12837
+ /v1/home/feed/mark-all:
12838
+ post:
12839
+ operationId: home_feed_markall_post
12840
+ summary: Bulk update home feed item statuses
12841
+ description:
12842
+ Flip every home feed item currently at one of the `from` statuses to the single `to` status. Returns the
12843
+ count of items whose status actually changed (items already at `to`, or outside `from`, are left untouched).
12844
+ Used to implement 'Mark all as read' (from=['new'], to='seen') and 'Clear all' (from=['new','seen','acted_on'],
12845
+ to='dismissed').
12846
+ tags:
12847
+ - home
12848
+ requestBody:
12849
+ required: true
12850
+ content:
12851
+ application/json:
12852
+ schema:
12853
+ type: object
12854
+ properties:
12855
+ from:
12856
+ minItems: 1
12857
+ type: array
12858
+ items:
12859
+ type: string
12860
+ enum:
12861
+ - new
12862
+ - seen
12863
+ - acted_on
12864
+ - dismissed
12865
+ to:
12866
+ type: string
12867
+ enum:
12868
+ - new
12869
+ - seen
12870
+ - acted_on
12871
+ - dismissed
12872
+ ids:
12873
+ type: array
12874
+ items:
12875
+ type: string
12876
+ required:
12877
+ - from
12878
+ - to
12879
+ responses:
12880
+ "200":
12881
+ description: Successful response
12882
+ content:
12883
+ application/json:
12884
+ schema:
12885
+ type: object
12886
+ properties:
12887
+ updatedCount:
12888
+ type: integer
12889
+ minimum: 0
12890
+ maximum: 9007199254740991
12891
+ updatedAt:
12892
+ type: string
12893
+ required:
12894
+ - updatedCount
12895
+ - updatedAt
12896
+ additionalProperties: false
12897
+ "500":
12898
+ description: Failed to persist bulk status update
12837
12899
  /v1/home/feed/query:
12838
12900
  post:
12839
12901
  operationId: home_feed_query_post
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.4-dev.202607011452.4dbd565",
3
+ "version": "0.10.4-dev.202607011653.a5dd422",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -66,7 +66,6 @@
66
66
  "pino": "9.14.0",
67
67
  "pino-pretty": "13.1.3",
68
68
  "playwright": "1.58.2",
69
- "postgres": "3.4.8",
70
69
  "quickjs-emscripten": "0.32.0",
71
70
  "re2js": "2.8.3",
72
71
  "remark-gfm": "4.0.1",
@@ -9,6 +9,7 @@ import {
9
9
  drainDirectiveDisplayBuffer,
10
10
  estimateBase64Bytes,
11
11
  extractVellumLinks,
12
+ incompleteVellumLinkSuffixLength,
12
13
  inferMimeType,
13
14
  MAX_ASSISTANT_ATTACHMENT_BYTES,
14
15
  stripVellumLinks,
@@ -386,8 +387,7 @@ describe("extractVellumLinks", () => {
386
387
  });
387
388
 
388
389
  test("decodes URL-encoded spaces in host paths", () => {
389
- const text =
390
- "[my file.pdf](vellum://host/Users/me/my%20file.pdf)";
390
+ const text = "[my file.pdf](vellum://host/Users/me/my%20file.pdf)";
391
391
  const result = extractVellumLinks(text);
392
392
 
393
393
  expect(result.directiveRequests).toHaveLength(1);
@@ -406,8 +406,7 @@ describe("extractVellumLinks", () => {
406
406
  });
407
407
 
408
408
  test("warns on malformed percent-encoding and skips the link", () => {
409
- const text =
410
- "[bad file](vellum://workspace/scratch/100%complete.txt)";
409
+ const text = "[bad file](vellum://workspace/scratch/100%complete.txt)";
411
410
  const result = extractVellumLinks(text);
412
411
 
413
412
  expect(result.directiveRequests).toHaveLength(0);
@@ -484,6 +483,65 @@ describe("stripVellumLinks", () => {
484
483
  });
485
484
  });
486
485
 
486
+ // ---------------------------------------------------------------------------
487
+ // incompleteVellumLinkSuffixLength
488
+ // ---------------------------------------------------------------------------
489
+
490
+ describe("incompleteVellumLinkSuffixLength", () => {
491
+ const suffix = (text: string) =>
492
+ text.slice(text.length - incompleteVellumLinkSuffixLength(text));
493
+
494
+ test("returns 0 for text with no trailing link", () => {
495
+ expect(incompleteVellumLinkSuffixLength("all done, no links here")).toBe(0);
496
+ });
497
+
498
+ test("returns 0 for a completed vellum link", () => {
499
+ expect(
500
+ incompleteVellumLinkSuffixLength(
501
+ "see [report.pdf](vellum://workspace/scratch/report.pdf)",
502
+ ),
503
+ ).toBe(0);
504
+ });
505
+
506
+ test("returns 0 for a completed link followed by trailing text", () => {
507
+ expect(
508
+ incompleteVellumLinkSuffixLength(
509
+ "[a.pdf](vellum://host/tmp/a.pdf) and more",
510
+ ),
511
+ ).toBe(0);
512
+ });
513
+
514
+ test.each([
515
+ ["mid path", "grab [a.pdf](vellum://host/tmp/a"],
516
+ ["at slash", "grab [a.pdf](vellum://host/"],
517
+ ["at authority", "grab [a.pdf](vellum://host"],
518
+ ["partial authority", "grab [a.pdf](vellum://ho"],
519
+ ["partial scheme", "grab [a.pdf](vel"],
520
+ ["open paren", "grab [a.pdf]("],
521
+ ["closed label", "grab [a.pdf]"],
522
+ ["open label", "grab [a.pd"],
523
+ ])("withholds an in-progress vellum link (%s)", (_name, text) => {
524
+ expect(suffix(text).startsWith("[")).toBe(true);
525
+ expect(
526
+ stripVellumLinks(
527
+ text.slice(0, text.length - incompleteVellumLinkSuffixLength(text)),
528
+ ),
529
+ ).not.toContain("vellum://");
530
+ });
531
+
532
+ test("withholds only the trailing in-progress link, not an earlier complete one", () => {
533
+ const text =
534
+ "[done.pdf](vellum://host/tmp/done.pdf) then [next](vellum://workspace/scratch/n";
535
+ expect(suffix(text)).toBe("[next](vellum://workspace/scratch/n");
536
+ });
537
+
538
+ test("stops withholding once the URL diverges from the vellum scheme", () => {
539
+ expect(
540
+ incompleteVellumLinkSuffixLength("see [site](https://example.com"),
541
+ ).toBe(0);
542
+ });
543
+ });
544
+
487
545
  // ---------------------------------------------------------------------------
488
546
  // cleanAssistantContent — vellum:// links
489
547
  // ---------------------------------------------------------------------------
@@ -191,7 +191,6 @@ mock.module("../calls/voice-session-bridge.js", () => {
191
191
  mockStartVoiceTurn = mock(createMockVoiceTurn(["Hello", " there"]));
192
192
  return {
193
193
  startVoiceTurn: (...args: unknown[]) => mockStartVoiceTurn(...args),
194
- setVoiceBridgeDeps: () => {},
195
194
  };
196
195
  });
197
196
 
@@ -493,7 +493,7 @@ describe("channel-retry-sweep", () => {
493
493
  ).toBe("assistant-delivery-fails");
494
494
  });
495
495
 
496
- test("Slack DM processing retries skip previously delivered live text responses", async () => {
496
+ test("Slack DM processing retry reconciles into the streamed message without opening a second stream", async () => {
497
497
  const inbound = deliveryCrud.recordInbound(
498
498
  "slack",
499
499
  "D-LIVE-RETRY",
@@ -511,7 +511,8 @@ describe("channel-retry-sweep", () => {
511
511
  sourceChannel: "slack",
512
512
  requesterChatId: "D-LIVE-RETRY",
513
513
  },
514
- slackDmLiveDeliveredTextResponseIndexes: [1],
514
+ // A prior attempt streamed a message before failing.
515
+ slackStreamMessageTs: "1700000000.000044",
515
516
  });
516
517
 
517
518
  const db = getDb();
@@ -527,28 +528,9 @@ describe("channel-retry-sweep", () => {
527
528
  await sweepFailedEvents(async (conversationId, _content, options) => {
528
529
  options?.onEvent?.({
529
530
  type: "assistant_text_delta",
530
- text: "Already delivered live response.",
531
+ text: "Reprocessed response.",
531
532
  conversationId,
532
533
  });
533
- options?.onEvent?.({
534
- type: "tool_use_start",
535
- toolName: "web_search",
536
- input: { query: "one" },
537
- conversationId,
538
- toolUseId: "toolu_1",
539
- });
540
- options?.onEvent?.({
541
- type: "assistant_text_delta",
542
- text: "New live response.",
543
- conversationId,
544
- });
545
- options?.onEvent?.({
546
- type: "tool_use_start",
547
- toolName: "web_search",
548
- input: { query: "two" },
549
- conversationId,
550
- toolUseId: "toolu_2",
551
- });
552
534
  options?.onEvent?.({
553
535
  type: "message_complete",
554
536
  conversationId,
@@ -575,11 +557,9 @@ describe("channel-retry-sweep", () => {
575
557
  ? (JSON.parse(row.rawPayload) as Record<string, unknown>)
576
558
  : {};
577
559
 
578
- expect(
579
- liveDeliveryCalls.map((entry) => entry.payload.text).filter(Boolean),
580
- ).toEqual(["New live response."]);
581
- expect(rawPayload.slackDmLiveDeliveredTextResponseIndexes).toEqual([1, 2]);
582
- expect(rawPayload.replyMessageId).toBe("assistant-live-retry-final");
560
+ // A retry never streams; durable delivery edits the prior streamed message
561
+ // in place from the first segment, so the reply is not duplicated.
562
+ expect(liveDeliveryCalls).toEqual([]);
583
563
  expect(deliveryCalls).toEqual([
584
564
  {
585
565
  conversationId: inbound.conversationId,
@@ -587,13 +567,17 @@ describe("channel-retry-sweep", () => {
587
567
  callbackUrl: "https://example.test/deliver/slack",
588
568
  assistantId: undefined,
589
569
  messageId: "assistant-live-retry-final",
590
- startFromSegment: 2,
570
+ startFromSegment: 0,
571
+ messageTs: "1700000000.000044",
591
572
  },
592
573
  ]);
574
+ expect(rawPayload.replyMessageId).toBe("assistant-live-retry-final");
575
+ expect(rawPayload.slackStreamMessageTs).toBe("1700000000.000044");
593
576
  expect(row?.processingStatus).toBe("processed");
577
+ expect(row?.deliveryStatus).toBe("delivered");
594
578
  });
595
579
 
596
- test("Slack DM processing retries resume final delivery after live text", async () => {
580
+ test("Slack DM processing retry with no prior stream delivers the full reply normally", async () => {
597
581
  const inbound = deliveryCrud.recordInbound(
598
582
  "slack",
599
583
  "D-LIVE-RETRY-SAME-REPLY",
@@ -622,10 +606,6 @@ describe("channel-retry-sweep", () => {
622
606
  })
623
607
  .where(eq(channelInboundEvents.id, inbound.eventId))
624
608
  .run();
625
- deliverChannelReplyImpl = async () => ({
626
- ok: true,
627
- ts: "1700000000.000044",
628
- });
629
609
 
630
610
  await sweepFailedEvents(async (conversationId, _content, options) => {
631
611
  options?.onEvent?.({
@@ -633,13 +613,6 @@ describe("channel-retry-sweep", () => {
633
613
  text: "Live retry response.",
634
614
  conversationId,
635
615
  });
636
- options?.onEvent?.({
637
- type: "tool_use_start",
638
- toolName: "web_search",
639
- input: { query: "example" },
640
- conversationId,
641
- toolUseId: "toolu_1",
642
- });
643
616
  options?.onEvent?.({
644
617
  type: "message_complete",
645
618
  conversationId,
@@ -666,9 +639,7 @@ describe("channel-retry-sweep", () => {
666
639
  ? (JSON.parse(row.rawPayload) as Record<string, unknown>)
667
640
  : {};
668
641
 
669
- expect(
670
- liveDeliveryCalls.map((entry) => entry.payload.text).filter(Boolean),
671
- ).toEqual(["Live retry response."]);
642
+ expect(liveDeliveryCalls).toEqual([]);
672
643
  expect(deliveryCalls).toEqual([
673
644
  {
674
645
  conversationId: inbound.conversationId,
@@ -676,17 +647,16 @@ describe("channel-retry-sweep", () => {
676
647
  callbackUrl: "https://example.test/deliver/slack",
677
648
  assistantId: undefined,
678
649
  messageId: "assistant-live-retry-same-reply",
679
- startFromSegment: 1,
680
- messageTs: "1700000000.000044",
650
+ startFromSegment: 0,
681
651
  },
682
652
  ]);
683
- expect(rawPayload.slackDmLiveDeliveredTextResponseIndexes).toEqual([1]);
653
+ expect(rawPayload.slackStreamMessageTs).toBeUndefined();
684
654
  expect(rawPayload.replyMessageId).toBe("assistant-live-retry-same-reply");
685
655
  expect(row?.processingStatus).toBe("processed");
686
656
  expect(row?.deliveryStatus).toBe("delivered");
687
657
  });
688
658
 
689
- test("Slack DM processing retries persist live delivery progress before final delivery failures", async () => {
659
+ test("Slack DM processing retry preserves the streamed message ts when delivery fails again", async () => {
690
660
  const inbound = deliveryCrud.recordInbound(
691
661
  "slack",
692
662
  "D-LIVE-RETRY-FINAL-FAILS",
@@ -704,6 +674,7 @@ describe("channel-retry-sweep", () => {
704
674
  sourceChannel: "slack",
705
675
  requesterChatId: "D-LIVE-RETRY-FINAL-FAILS",
706
676
  },
677
+ slackStreamMessageTs: "1700000000.000055",
707
678
  });
708
679
 
709
680
  const db = getDb();
@@ -715,10 +686,6 @@ describe("channel-retry-sweep", () => {
715
686
  })
716
687
  .where(eq(channelInboundEvents.id, inbound.eventId))
717
688
  .run();
718
- deliverChannelReplyImpl = async () => ({
719
- ok: true,
720
- ts: "1700000000.000055",
721
- });
722
689
  deliverReplyViaCallbackImpl = async () => {
723
690
  throw new Error("fetch failed before progress callback");
724
691
  };
@@ -729,13 +696,6 @@ describe("channel-retry-sweep", () => {
729
696
  text: "Live retry response.",
730
697
  conversationId,
731
698
  });
732
- options?.onEvent?.({
733
- type: "tool_use_start",
734
- toolName: "web_search",
735
- input: { query: "example" },
736
- conversationId,
737
- toolUseId: "toolu_1",
738
- });
739
699
  options?.onEvent?.({
740
700
  type: "message_complete",
741
701
  conversationId,
@@ -762,9 +722,7 @@ describe("channel-retry-sweep", () => {
762
722
  ? (JSON.parse(row.rawPayload) as Record<string, unknown>)
763
723
  : {};
764
724
 
765
- expect(
766
- liveDeliveryCalls.map((entry) => entry.payload.text).filter(Boolean),
767
- ).toEqual(["Live retry response."]);
725
+ expect(liveDeliveryCalls).toEqual([]);
768
726
  expect(deliveryCalls).toEqual([
769
727
  {
770
728
  conversationId: inbound.conversationId,
@@ -772,12 +730,12 @@ describe("channel-retry-sweep", () => {
772
730
  callbackUrl: "https://example.test/deliver/slack",
773
731
  assistantId: undefined,
774
732
  messageId: "assistant-live-retry-final-fails",
775
- startFromSegment: 1,
733
+ startFromSegment: 0,
776
734
  messageTs: "1700000000.000055",
777
735
  },
778
736
  ]);
779
- expect(rawPayload.slackDmLiveDeliveredTextResponseIndexes).toEqual([1]);
780
- expect(row?.deliveredSegmentCount).toBe(1);
737
+ // The streamed ts survives so a later retry still reconciles in place.
738
+ expect(rawPayload.slackStreamMessageTs).toBe("1700000000.000055");
781
739
  expect(row?.deliveryStatus).toBe("failed");
782
740
  });
783
741
 
@@ -836,6 +794,60 @@ describe("channel-retry-sweep", () => {
836
794
  expect(row?.retryAfter).toBeNull();
837
795
  });
838
796
 
797
+ test("delivery retry edits a prior streamed message in place instead of posting a duplicate", async () => {
798
+ const inbound = deliveryCrud.recordInbound(
799
+ "slack",
800
+ "D-DELIVERY-ONLY-STREAM",
801
+ "msg-delivery-only-stream",
802
+ );
803
+ deliveryCrud.storePayload(inbound.eventId, {
804
+ content: "already processed",
805
+ sourceChannel: "slack",
806
+ interface: "slack",
807
+ externalChatId: "D-DELIVERY-ONLY-STREAM",
808
+ replyCallbackUrl: "https://example.test/deliver/slack",
809
+ assistantId: "assistant-1",
810
+ replyMessageId: "assistant-delivery-only-stream",
811
+ // A prior attempt streamed a message, then delivery failed before any
812
+ // durable segment landed.
813
+ slackStreamMessageTs: "1700000000.000077",
814
+ });
815
+
816
+ const db = getDb();
817
+ db.update(channelInboundEvents)
818
+ .set({
819
+ processingStatus: "processed",
820
+ deliveryStatus: "failed",
821
+ processingAttempts: 1,
822
+ retryAfter: Date.now() - 1,
823
+ deliveredSegmentCount: 0,
824
+ })
825
+ .where(eq(channelInboundEvents.id, inbound.eventId))
826
+ .run();
827
+
828
+ await sweepFailedEvents(async () => {
829
+ throw new Error("processMessage should not be called");
830
+ });
831
+
832
+ const row = db
833
+ .select()
834
+ .from(channelInboundEvents)
835
+ .where(eq(channelInboundEvents.id, inbound.eventId))
836
+ .get();
837
+ expect(deliveryCalls).toEqual([
838
+ {
839
+ conversationId: inbound.conversationId,
840
+ externalChatId: "D-DELIVERY-ONLY-STREAM",
841
+ callbackUrl: "https://example.test/deliver/slack",
842
+ assistantId: "assistant-1",
843
+ messageId: "assistant-delivery-only-stream",
844
+ startFromSegment: 0,
845
+ messageTs: "1700000000.000077",
846
+ },
847
+ ]);
848
+ expect(row?.deliveryStatus).toBe("delivered");
849
+ });
850
+
839
851
  test("delivery retry resolves missing reply id from the linked user turn", async () => {
840
852
  const inbound = deliveryCrud.recordInbound(
841
853
  "telegram",
@@ -421,7 +421,6 @@ import {
421
421
  activeRelayConnections,
422
422
  RelayConnection,
423
423
  } from "../calls/relay-server.js";
424
- import { setVoiceBridgeDeps } from "../calls/voice-session-bridge.js";
425
424
  import {
426
425
  createInboundSession,
427
426
  createVerificationSession,
@@ -733,9 +732,6 @@ describe("relay-server", () => {
733
732
  };
734
733
  return session as unknown as import("../daemon/conversation.js").Conversation;
735
734
  };
736
- setVoiceBridgeDeps({
737
- resolveAttachments: () => [],
738
- });
739
735
  });
740
736
 
741
737
  // ── Setup message handling ──────────────────────────────────────
@@ -95,10 +95,7 @@ import {
95
95
  type CreateScopedApprovalGrantParams,
96
96
  revokeScopedApprovalGrantsForContext,
97
97
  } from "../approvals/scoped-approval-grants.js";
98
- import {
99
- setVoiceBridgeDeps,
100
- startVoiceTurn,
101
- } from "../calls/voice-session-bridge.js";
98
+ import { startVoiceTurn } from "../calls/voice-session-bridge.js";
102
99
  import type { ServerMessage } from "../daemon/message-protocol.js";
103
100
  import { getDb } from "../persistence/db-connection.js";
104
101
  import { initializeDb } from "../persistence/db-init.js";
@@ -204,9 +201,6 @@ function setupBridgeDeps(
204
201
  sessionFactory: () => ReturnType<typeof createMockSession>["session"],
205
202
  ) {
206
203
  scopedGrantConversationFactory = () => sessionFactory();
207
- setVoiceBridgeDeps({
208
- resolveAttachments: () => [],
209
- });
210
204
  }
211
205
 
212
206
  // ---------------------------------------------------------------------------
@@ -45,10 +45,7 @@ mock.module("../daemon/conversation-store.js", () => ({
45
45
  },
46
46
  }));
47
47
 
48
- import {
49
- setVoiceBridgeDeps,
50
- startVoiceTurn,
51
- } from "../calls/voice-session-bridge.js";
48
+ import { startVoiceTurn } from "../calls/voice-session-bridge.js";
52
49
  import {
53
50
  createConversation,
54
51
  getMessages,
@@ -180,9 +177,6 @@ function parsePersistedMetadata(
180
177
  */
181
178
  function injectDeps(conversationFactory: () => Conversation): void {
182
179
  voiceConversationFactory = conversationFactory;
183
- setVoiceBridgeDeps({
184
- resolveAttachments: () => [],
185
- });
186
180
  }
187
181
 
188
182
  describe("voice-session-bridge", () => {
@@ -518,9 +512,6 @@ describe("voice-session-bridge", () => {
518
512
  };
519
513
 
520
514
  voiceConversationFactory = () => session;
521
- setVoiceBridgeDeps({
522
- resolveAttachments: () => [],
523
- });
524
515
 
525
516
  const textDeltaEvents: ServerMessage[] = [];
526
517
  const completeEvents: ServerMessage[] = [];
@@ -56,8 +56,9 @@ let pointerMessageProcessor: PointerMessageProcessor | undefined;
56
56
 
57
57
  /**
58
58
  * Inject the daemon-provided pointer message processor.
59
- * Called from daemon/lifecycle.ts at startup, following the same pattern
60
- * as setRelayBroadcast.
59
+ * Called from daemon/lifecycle.ts at startup so this low-level module can
60
+ * drive a full daemon conversation turn without statically importing the
61
+ * daemon pipeline (which would invert the layering / create an import cycle).
61
62
  */
62
63
  export function setPointerMessageProcessor(
63
64
  processor: PointerMessageProcessor,