@vellumai/assistant 0.11.7-dev.202608301911.907e905 → 0.11.7-dev.202608310050.dde6a86

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 (52) hide show
  1. package/package.json +1 -1
  2. package/src/__tests__/agent-loop-compacted-history-transform.test.ts +304 -0
  3. package/src/__tests__/agent-wake-disk-pressure-callsite.test.ts +3 -0
  4. package/src/__tests__/agent-wake-override-profile.test.ts +3 -0
  5. package/src/__tests__/anthropic-provider.test.ts +56 -0
  6. package/src/__tests__/attachments-store.test.ts +117 -6
  7. package/src/__tests__/attachments.test.ts +122 -0
  8. package/src/__tests__/compactor-retained-image-validation.test.ts +15 -0
  9. package/src/__tests__/conversation-agent-loop.test.ts +4 -0
  10. package/src/__tests__/conversation-media-retry.test.ts +33 -2
  11. package/src/__tests__/conversation-queue.test.ts +4 -0
  12. package/src/__tests__/conversation-routes-enabled-plugins.test.ts +1 -1
  13. package/src/__tests__/conversation-routes-hidden-queue.test.ts +1 -1
  14. package/src/__tests__/conversation-routes-slash-commands.test.ts +1 -1
  15. package/src/__tests__/conversation-sight-frames.test.ts +479 -0
  16. package/src/__tests__/conversation-summarize-up-to.test.ts +102 -0
  17. package/src/__tests__/media-resolve-image-validation.test.ts +106 -0
  18. package/src/__tests__/persist-unsendable-image-downscale.test.ts +63 -1
  19. package/src/__tests__/persist-unsendable-image.test.ts +19 -0
  20. package/src/__tests__/process-message-background-slack.test.ts +1 -1
  21. package/src/__tests__/process-message-display-content.test.ts +1 -1
  22. package/src/__tests__/server-history-render.test.ts +22 -0
  23. package/src/__tests__/sight-frame-retention.test.ts +292 -0
  24. package/src/agent/attachments.ts +7 -2
  25. package/src/agent/loop.ts +59 -1
  26. package/src/calls/__tests__/voice-session-bridge.test.ts +183 -3
  27. package/src/calls/voice-session-bridge.ts +46 -1
  28. package/src/context/compactor.ts +12 -0
  29. package/src/daemon/conversation-agent-loop.ts +14 -1
  30. package/src/daemon/conversation-media-retry.ts +11 -6
  31. package/src/daemon/conversation-runtime-assembly.ts +62 -0
  32. package/src/daemon/conversation-sight-frames.ts +170 -0
  33. package/src/daemon/conversation.ts +35 -2
  34. package/src/daemon/process-message.ts +2 -17
  35. package/src/live-voice/__tests__/live-voice-attach-frame.test.ts +679 -0
  36. package/src/live-voice/__tests__/live-voice-attach-image.test.ts +8 -5
  37. package/src/live-voice/live-voice-photo.ts +2 -24
  38. package/src/live-voice/live-voice-session.ts +194 -20
  39. package/src/live-voice/protocol.ts +82 -11
  40. package/src/persistence/attachments-store.ts +26 -0
  41. package/src/persistence/conversation-crud.ts +125 -2
  42. package/src/persistence/conversation-types.ts +28 -0
  43. package/src/plugin-api/index.ts +12 -0
  44. package/src/plugins/defaults/image-recovery/recover.ts +12 -1
  45. package/src/plugins/defaults/memory/__tests__/memory-retrospective-provider-path.test.ts +3 -0
  46. package/src/plugins/defaults/memory/__tests__/memory-retrospective-wake-chain.test.ts +3 -0
  47. package/src/providers/content-block-schema.ts +1 -0
  48. package/src/providers/media-resolve.ts +24 -10
  49. package/src/providers/types.ts +56 -0
  50. package/src/runtime/__tests__/agent-wake.test.ts +66 -0
  51. package/src/runtime/agent-wake.ts +13 -1
  52. package/src/runtime/routes/conversation-routes.ts +2 -16
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.11.7-dev.202608301911.907e905",
3
+ "version": "0.11.7-dev.202608310050.dde6a86",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -0,0 +1,304 @@
1
+ /**
2
+ * The agent loop's post-compaction history transform.
3
+ *
4
+ * In-place compaction rebuilds history from the stored rows, so it can
5
+ * reintroduce content the caller had already trimmed out of the array it handed
6
+ * to `run()`. The rebuilt array is installed and sent on the very next request
7
+ * of the same turn, so the caller's trim has to be re-applied at the
8
+ * installation site rather than only before the run. The loop stays
9
+ * conversation-ignorant: the caller injects a closure, and this suite drives
10
+ * that seam with the real camera-frame retention transform.
11
+ */
12
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
13
+
14
+ import type { PostCompactContext } from "@vellumai/plugin-api";
15
+
16
+ import { AgentLoop } from "../agent/loop.js";
17
+ import type { ContextWindowConfig } from "../config/types.js";
18
+ import { stripAgedSightFrames } from "../daemon/conversation-sight-frames.js";
19
+ import type { TrustContext } from "../daemon/trust-context-types.js";
20
+ import { HOOKS } from "../plugin-api/constants.js";
21
+ import {
22
+ createContextWindowManager,
23
+ disposeContextWindowManager,
24
+ getContextWindowManager,
25
+ } from "../plugins/defaults/compaction/manager-store.js";
26
+ import {
27
+ registerPlugin,
28
+ resetPluginRegistryForTests,
29
+ } from "../plugins/registry.js";
30
+ import type {
31
+ ContentBlock,
32
+ Message,
33
+ Provider,
34
+ ProviderResponse,
35
+ } from "../providers/types.js";
36
+ import { ContextOverflowError } from "../providers/types.js";
37
+
38
+ const testPostCompactPlugin = {
39
+ manifest: { name: "test-post-compact-transform", version: "0.0.0" },
40
+ hooks: {
41
+ [HOOKS.POST_COMPACT]: async (input: PostCompactContext): Promise<void> => {
42
+ void input;
43
+ },
44
+ },
45
+ };
46
+
47
+ const CONVERSATION_ID = "compacted-history-transform-conversation";
48
+
49
+ /** Capture times one second apart, the shape the row read produces. */
50
+ const CAPTURE_TIMES = new Map<string, number>([
51
+ ["f1", 1000],
52
+ ["f2", 2000],
53
+ ["f3", 3000],
54
+ ["f4", 4000],
55
+ ]);
56
+
57
+ /** A retained frame as `buildRetainedImageBlocks` rebuilds it: inline + id. */
58
+ function retainedFrame(
59
+ attachmentId: string,
60
+ ): Extract<ContentBlock, { type: "image" }> {
61
+ return {
62
+ type: "image",
63
+ source: { type: "base64", media_type: "image/png", data: "AAAAAAAA" },
64
+ _attachmentId: attachmentId,
65
+ };
66
+ }
67
+
68
+ /**
69
+ * The history compaction rebuilds here: four tagged frames in one synthetic
70
+ * message, which is two more than the retention bound allows.
71
+ */
72
+ function compactedHistoryWithFourFrames(): Message[] {
73
+ return [
74
+ {
75
+ role: "user",
76
+ content: [
77
+ { type: "text", text: "Images retained from the compacted portion:" },
78
+ retainedFrame("f1"),
79
+ retainedFrame("f2"),
80
+ retainedFrame("f3"),
81
+ retainedFrame("f4"),
82
+ ],
83
+ },
84
+ ];
85
+ }
86
+
87
+ function textResponse(text: string): ProviderResponse {
88
+ return {
89
+ content: [{ type: "text", text }],
90
+ model: "mock-model",
91
+ usage: { inputTokens: 10, outputTokens: 5 },
92
+ stopReason: "end_turn",
93
+ };
94
+ }
95
+
96
+ /** Records every history the provider is asked to send. */
97
+ function createRecordingProvider(requests: Message[][]): Provider {
98
+ return {
99
+ name: "mock",
100
+ async sendMessage(messages: Message[]): Promise<ProviderResponse> {
101
+ requests.push(messages);
102
+ return textResponse("done");
103
+ },
104
+ };
105
+ }
106
+
107
+ /** A provider that rejects once as context-too-large, then answers. */
108
+ function createOverflowingProvider(requests: Message[][]): Provider {
109
+ let throwOnce = true;
110
+ return {
111
+ name: "mock",
112
+ async sendMessage(messages: Message[]): Promise<ProviderResponse> {
113
+ requests.push(messages);
114
+ if (throwOnce) {
115
+ throwOnce = false;
116
+ throw new ContextOverflowError("prompt too long", "mock", {
117
+ actualTokens: 999_999,
118
+ });
119
+ }
120
+ return textResponse("done after overflow recovery");
121
+ },
122
+ };
123
+ }
124
+
125
+ /**
126
+ * Install a manager whose compaction returns the four-frame history, so the
127
+ * loop installs more frames than the bound allows.
128
+ */
129
+ function installOverfullCompactionManager(): { trust: TrustContext } {
130
+ createContextWindowManager({
131
+ provider: { name: "mock-provider" } as unknown as Provider,
132
+ config: {} as unknown as ContextWindowConfig,
133
+ conversationId: CONVERSATION_ID,
134
+ });
135
+ const manager = getContextWindowManager(CONVERSATION_ID);
136
+ if (manager) {
137
+ const rebuild = async () => ({
138
+ messages: compactedHistoryWithFourFrames(),
139
+ compacted: true,
140
+ exhausted: false,
141
+ });
142
+ manager.maybeCompact = rebuild as unknown as typeof manager.maybeCompact;
143
+ manager.recoverContextOverflow =
144
+ rebuild as unknown as typeof manager.recoverContextOverflow;
145
+ }
146
+ return { trust: { sourceChannel: "vellum", trustClass: "unknown" } };
147
+ }
148
+
149
+ /** Image blocks in the last history the provider was asked to send. */
150
+ function imagesInLastRequest(requests: Message[][]): ContentBlock[] {
151
+ const last = requests.at(-1) ?? [];
152
+ return last.flatMap((message) =>
153
+ message.content.filter((block) => block.type === "image"),
154
+ );
155
+ }
156
+
157
+ function frameStubsInLastRequest(requests: Message[][]): string[] {
158
+ const last = requests.at(-1) ?? [];
159
+ return last.flatMap((message) =>
160
+ message.content
161
+ .filter((block) => block.type === "text")
162
+ .map((block) => block.text)
163
+ .filter((text) => text.startsWith("[Camera frame omitted from context:")),
164
+ );
165
+ }
166
+
167
+ describe("AgentLoop post-compaction history transform", () => {
168
+ beforeEach(() => {
169
+ resetPluginRegistryForTests();
170
+ registerPlugin(testPostCompactPlugin);
171
+ });
172
+
173
+ afterEach(() => {
174
+ disposeContextWindowManager(CONVERSATION_ID);
175
+ });
176
+
177
+ test("trims a budget-gate compaction before the next provider call", async () => {
178
+ const requests: Message[][] = [];
179
+ const loop = new AgentLoop({
180
+ provider: createRecordingProvider(requests),
181
+ systemPrompt: "system",
182
+ conversationId: CONVERSATION_ID,
183
+ tools: [],
184
+ toolExecutor: async () => ({ content: "ok", isError: false }),
185
+ transformCompactedHistory: (messages) =>
186
+ stripAgedSightFrames(messages, CAPTURE_TIMES).messages,
187
+ });
188
+
189
+ await loop.run({
190
+ requestId: "req",
191
+ messages: [{ role: "user", content: [{ type: "text", text: "hi" }] }],
192
+ onEvent: () => {},
193
+ modelProfileKey: "balanced",
194
+ resolveContextWindow: () => ({
195
+ maxInputTokens: 10,
196
+ overflowRecovery: { enabled: true, safetyMarginRatio: 0 },
197
+ }),
198
+ compactInPlace: true,
199
+ ...installOverfullCompactionManager(),
200
+ });
201
+
202
+ // The request that went out after compaction carries the bound, not the
203
+ // four frames compaction rebuilt.
204
+ expect(imagesInLastRequest(requests)).toHaveLength(2);
205
+ expect(frameStubsInLastRequest(requests)).toHaveLength(2);
206
+ // The newest two survived.
207
+ expect(imagesInLastRequest(requests)).toEqual([
208
+ retainedFrame("f3"),
209
+ retainedFrame("f4"),
210
+ ]);
211
+ });
212
+
213
+ test("trims an overflow-driven compaction before the retry", async () => {
214
+ const requests: Message[][] = [];
215
+ const loop = new AgentLoop({
216
+ provider: createOverflowingProvider(requests),
217
+ systemPrompt: "system",
218
+ conversationId: CONVERSATION_ID,
219
+ tools: [],
220
+ toolExecutor: async () => ({ content: "ok", isError: false }),
221
+ transformCompactedHistory: (messages) =>
222
+ stripAgedSightFrames(messages, CAPTURE_TIMES).messages,
223
+ });
224
+ // Blocks the budget gate so only the overflow rejection drives compaction.
225
+ loop.compactionCircuit.lastPostCompactionEstimate = 0;
226
+
227
+ await loop.run({
228
+ requestId: "req",
229
+ messages: [{ role: "user", content: [{ type: "text", text: "hi" }] }],
230
+ onEvent: () => {},
231
+ modelProfileKey: "balanced",
232
+ resolveContextWindow: () => ({
233
+ maxInputTokens: 10,
234
+ overflowRecovery: { enabled: true, safetyMarginRatio: 0 },
235
+ }),
236
+ compactInPlace: false,
237
+ ...installOverfullCompactionManager(),
238
+ });
239
+
240
+ // The overflow retry is a second provider call, and it too is bounded.
241
+ expect(requests.length).toBeGreaterThan(1);
242
+ expect(imagesInLastRequest(requests)).toHaveLength(2);
243
+ expect(frameStubsInLastRequest(requests)).toHaveLength(2);
244
+ });
245
+
246
+ test("installs the compacted history as built when no transform is configured", async () => {
247
+ // The workflow leaf runner builds a loop with no conversation behind it.
248
+ const requests: Message[][] = [];
249
+ const loop = new AgentLoop({
250
+ provider: createRecordingProvider(requests),
251
+ systemPrompt: "system",
252
+ conversationId: CONVERSATION_ID,
253
+ tools: [],
254
+ toolExecutor: async () => ({ content: "ok", isError: false }),
255
+ });
256
+
257
+ await loop.run({
258
+ requestId: "req",
259
+ messages: [{ role: "user", content: [{ type: "text", text: "hi" }] }],
260
+ onEvent: () => {},
261
+ modelProfileKey: "balanced",
262
+ resolveContextWindow: () => ({
263
+ maxInputTokens: 10,
264
+ overflowRecovery: { enabled: true, safetyMarginRatio: 0 },
265
+ }),
266
+ compactInPlace: true,
267
+ ...installOverfullCompactionManager(),
268
+ });
269
+
270
+ expect(imagesInLastRequest(requests)).toHaveLength(4);
271
+ expect(frameStubsInLastRequest(requests)).toHaveLength(0);
272
+ });
273
+
274
+ test("keeps the compacted history when the transform throws", async () => {
275
+ const requests: Message[][] = [];
276
+ const loop = new AgentLoop({
277
+ provider: createRecordingProvider(requests),
278
+ systemPrompt: "system",
279
+ conversationId: CONVERSATION_ID,
280
+ tools: [],
281
+ toolExecutor: async () => ({ content: "ok", isError: false }),
282
+ transformCompactedHistory: () => {
283
+ throw new Error("row read failed");
284
+ },
285
+ });
286
+
287
+ await loop.run({
288
+ requestId: "req",
289
+ messages: [{ role: "user", content: [{ type: "text", text: "hi" }] }],
290
+ onEvent: () => {},
291
+ modelProfileKey: "balanced",
292
+ resolveContextWindow: () => ({
293
+ maxInputTokens: 10,
294
+ overflowRecovery: { enabled: true, safetyMarginRatio: 0 },
295
+ }),
296
+ compactInPlace: true,
297
+ ...installOverfullCompactionManager(),
298
+ });
299
+
300
+ // The turn still completed against the untrimmed compacted history.
301
+ expect(requests.length).toBeGreaterThan(0);
302
+ expect(imagesInLastRequest(requests)).toHaveLength(4);
303
+ });
304
+ });
@@ -78,6 +78,9 @@ function makeTarget(): Conversation {
78
78
  }),
79
79
  },
80
80
  messages,
81
+ // The wake trims its own run input; no row here is tagged as a camera
82
+ // frame, so the real pass would return the array unchanged too.
83
+ trimAgedSightFrames: (msgs: Message[]) => msgs,
81
84
  getMessages: () => messages,
82
85
  isProcessing: () => processing,
83
86
  waitForIdle: async () => !processing,
@@ -90,6 +90,9 @@ function makeTarget(): {
90
90
  },
91
91
  },
92
92
  messages,
93
+ // The wake trims its own run input; no row here is tagged as a camera
94
+ // frame, so the real pass would return the array unchanged too.
95
+ trimAgedSightFrames: (msgs: Message[]) => msgs,
93
96
  getMessages: () => messages,
94
97
  isProcessing: () => processing,
95
98
  waitForIdle: async () => !processing,
@@ -2973,6 +2973,62 @@ describe("AnthropicProvider — Managed Proxy Fallback", () => {
2973
2973
  });
2974
2974
  });
2975
2975
 
2976
+ // ---------------------------------------------------------------------------
2977
+ // Tests - internal `_attachmentId` never reaches the wire
2978
+ // ---------------------------------------------------------------------------
2979
+
2980
+ describe("AnthropicProvider - internal attachment id", () => {
2981
+ let provider: AnthropicProvider;
2982
+
2983
+ beforeEach(() => {
2984
+ lastStreamParams = null;
2985
+ provider = new AnthropicProvider("sk-ant-test", "claude-sonnet-4-6");
2986
+ });
2987
+
2988
+ test("drops _attachmentId from image and file blocks", async () => {
2989
+ // The declared media type matches the bytes, so `resolveMediaReferences`
2990
+ // takes its identity fast path and hands the block through untouched. What
2991
+ // keeps the field off the wire is the client rebuilding each payload out of
2992
+ // `source` alone.
2993
+ const messages: Message[] = [
2994
+ {
2995
+ role: "user",
2996
+ content: [
2997
+ { type: "text", text: "what is this" },
2998
+ {
2999
+ type: "image",
3000
+ source: {
3001
+ type: "base64",
3002
+ media_type: "image/png",
3003
+ data: PNG_B64,
3004
+ },
3005
+ _attachmentId: "att-image-1",
3006
+ },
3007
+ {
3008
+ type: "file",
3009
+ source: {
3010
+ type: "base64",
3011
+ media_type: "application/pdf",
3012
+ data: "cGRm",
3013
+ filename: "notes.pdf",
3014
+ },
3015
+ _attachmentId: "att-file-1",
3016
+ },
3017
+ ],
3018
+ },
3019
+ ];
3020
+
3021
+ await provider.sendMessage(messages);
3022
+
3023
+ const sent = JSON.stringify(lastStreamParams!.messages);
3024
+ expect(sent).not.toContain("_attachmentId");
3025
+ expect(sent).not.toContain("att-image-1");
3026
+ expect(sent).not.toContain("att-file-1");
3027
+ // The image itself still went out.
3028
+ expect(sent).toContain(PNG_B64);
3029
+ });
3030
+ });
3031
+
2976
3032
  // ---------------------------------------------------------------------------
2977
3033
  // Tests — Orphaned UTF-16 surrogate sanitization
2978
3034
  // ---------------------------------------------------------------------------
@@ -16,12 +16,14 @@ import {
16
16
  isValidBase64,
17
17
  linkAttachmentToMessage,
18
18
  MAX_UPLOAD_BYTES,
19
+ resolveAttachmentsForPersist,
19
20
  uploadAttachment,
20
21
  validateAttachmentUpload,
21
22
  } from "../persistence/attachments-store.js";
22
23
  import {
23
24
  addMessage,
24
25
  createConversation,
26
+ deleteMessageById,
25
27
  } from "../persistence/conversation-crud.js";
26
28
  import { getConversationDirPath } from "../persistence/conversation-disk-view.js";
27
29
  import { getDb } from "../persistence/db-connection.js";
@@ -675,6 +677,115 @@ describe("deleteOrphanAttachments", () => {
675
677
  });
676
678
  });
677
679
 
680
+ // ---------------------------------------------------------------------------
681
+ // resolveAttachmentsForPersist
682
+ // ---------------------------------------------------------------------------
683
+
684
+ describe("resolveAttachmentsForPersist", () => {
685
+ beforeEach(resetTables);
686
+
687
+ // One implementation behind every send path that turns ids into a persisted
688
+ // user message (HTTP send, processMessage, the voice bridge), so its shape is
689
+ // pinned here rather than at each caller.
690
+ test("hydrates ids into the shape a persisted message stores", async () => {
691
+ const stored = await uploadAttachment("photo.png", "image/png", "ZnJhbWU=");
692
+
693
+ expect(resolveAttachmentsForPersist([stored.id])).toEqual([
694
+ {
695
+ id: stored.id,
696
+ filename: "photo.png",
697
+ mimeType: "image/png",
698
+ data: "ZnJhbWU=",
699
+ },
700
+ ]);
701
+ });
702
+
703
+ test("carries the source path only for attachments that have one", async () => {
704
+ const withPath = await uploadAttachment(
705
+ "from-disk.txt",
706
+ "text/plain",
707
+ "AA==",
708
+ );
709
+ const plain = await uploadAttachment("typed.txt", "text/plain", "BB==");
710
+ rawRun(
711
+ "test:setSourcePath",
712
+ "UPDATE attachments SET source_path = ? WHERE id = ?",
713
+ "/tmp/from-disk.txt",
714
+ withPath.id,
715
+ );
716
+
717
+ const resolved = resolveAttachmentsForPersist([withPath.id, plain.id]);
718
+
719
+ expect(resolved[0]).toMatchObject({ filePath: "/tmp/from-disk.txt" });
720
+ expect(resolved[1]).not.toHaveProperty("filePath");
721
+ });
722
+
723
+ test("drops ids with no attachment row", async () => {
724
+ const stored = await uploadAttachment("kept.txt", "text/plain", "AA==");
725
+
726
+ const resolved = resolveAttachmentsForPersist([stored.id, "att-missing"]);
727
+
728
+ expect(resolved.map((a) => a.id)).toEqual([stored.id]);
729
+ });
730
+
731
+ test("returns nothing for an empty id list", () => {
732
+ expect(resolveAttachmentsForPersist([])).toEqual([]);
733
+ });
734
+ });
735
+
736
+ // ---------------------------------------------------------------------------
737
+ // deleteMessageById orphan cleanup
738
+ // ---------------------------------------------------------------------------
739
+
740
+ describe("deleteMessageById attachment cleanup", () => {
741
+ beforeEach(resetTables);
742
+
743
+ test("collects an attachment the deleted message alone referenced", async () => {
744
+ const conv = createConversation();
745
+ const msg = await addMessage(conv.id, "user", "With attachment");
746
+ const stored = await uploadAttachment("shot.txt", "text/plain", "ZGF0YQ==");
747
+ linkAttachmentToMessage(msg.id, stored.id, 0);
748
+ const filePath = getFilePathForAttachment(stored.id);
749
+
750
+ deleteMessageById(msg.id);
751
+
752
+ expect(getAttachmentById(stored.id)).toBeNull();
753
+ expect(existsSync(filePath!)).toBe(false);
754
+ });
755
+
756
+ test("retained ids survive the delete, row and bytes", async () => {
757
+ // A caller rolling a message back rather than deleting it: the attachment
758
+ // returns to the uploaded-but-unlinked state every attachment sits in
759
+ // between upload and send, so a later message can still reference it.
760
+ const conv = createConversation();
761
+ const msg = await addMessage(conv.id, "user", "Rolled back");
762
+ const stored = await uploadAttachment("shot.txt", "text/plain", "ZGF0YQ==");
763
+ linkAttachmentToMessage(msg.id, stored.id, 0);
764
+ const filePath = getFilePathForAttachment(stored.id);
765
+
766
+ deleteMessageById(msg.id, { retainAttachmentIds: [stored.id] });
767
+
768
+ expect(getAttachmentById(stored.id)).not.toBeNull();
769
+ expect(existsSync(filePath!)).toBe(true);
770
+ // The row is gone even though its attachment stayed.
771
+ expect(getAttachmentsForMessage(msg.id)).toHaveLength(0);
772
+ });
773
+
774
+ test("retaining one id does not spare the others on the row", async () => {
775
+ const conv = createConversation();
776
+ const msg = await addMessage(conv.id, "user", "Two attachments");
777
+ const kept = await uploadAttachment("kept.txt", "text/plain", "AAAA");
778
+ const dropped = await uploadAttachment("dropped.txt", "text/plain", "BBBB");
779
+ linkAttachmentToMessage(msg.id, kept.id, 0);
780
+ linkAttachmentToMessage(msg.id, dropped.id, 1);
781
+
782
+ deleteMessageById(msg.id, { retainAttachmentIds: [kept.id] });
783
+
784
+ expect(getAttachmentById(kept.id)).not.toBeNull();
785
+ expect(getAttachmentById(dropped.id)).toBeNull();
786
+ });
787
+ });
788
+
678
789
  // ---------------------------------------------------------------------------
679
790
  // validateAttachmentUpload
680
791
  // ---------------------------------------------------------------------------
@@ -735,9 +846,9 @@ describe("validateAttachmentUpload", () => {
735
846
  test("accepts shell scripts as text attachments", () => {
736
847
  expect(validateAttachmentUpload("script.sh", "text/plain").ok).toBe(true);
737
848
  expect(validateAttachmentUpload("script.SH", "text/plain").ok).toBe(true);
738
- expect(
739
- validateAttachmentUpload("setup.sh", "application/x-sh").ok,
740
- ).toBe(true);
849
+ expect(validateAttachmentUpload("setup.sh", "application/x-sh").ok).toBe(
850
+ true,
851
+ );
741
852
  expect(
742
853
  validateAttachmentUpload("run.sh", "application/x-shellscript").ok,
743
854
  ).toBe(true);
@@ -760,9 +871,9 @@ describe("validateAttachmentUpload", () => {
760
871
  expect(
761
872
  validateAttachmentUpload("PROGRAM.EXE", "application/octet-stream").ok,
762
873
  ).toBe(false);
763
- expect(validateAttachmentUpload("INSTALL.DMG", "application/octet-stream").ok).toBe(
764
- false,
765
- );
874
+ expect(
875
+ validateAttachmentUpload("INSTALL.DMG", "application/octet-stream").ok,
876
+ ).toBe(false);
766
877
  });
767
878
 
768
879
  test("rejects unsupported MIME types", () => {
@@ -6,6 +6,92 @@ import {
6
6
  enrichMessageWithSourcePaths,
7
7
  } from "../agent/attachments.js";
8
8
  import { createUserMessage } from "../agent/message-types.js";
9
+ import {
10
+ attachmentIdFragment,
11
+ mediaBlockAttachmentId,
12
+ } from "../providers/types.js";
13
+
14
+ // ---------------------------------------------------------------------------
15
+ // attachmentIdFragment
16
+ // ---------------------------------------------------------------------------
17
+
18
+ describe("attachmentIdFragment", () => {
19
+ test("yields the property when an id is present", () => {
20
+ expect(attachmentIdFragment("att-1")).toEqual({ _attachmentId: "att-1" });
21
+ });
22
+
23
+ test("yields nothing for a missing or empty id", () => {
24
+ // Absent rather than present-and-empty: the read side requires a non-empty
25
+ // string before it treats the field as an id.
26
+ expect(attachmentIdFragment(undefined)).toEqual({});
27
+ expect(attachmentIdFragment("")).toEqual({});
28
+ expect("_attachmentId" in attachmentIdFragment("")).toBe(false);
29
+ });
30
+ });
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // mediaBlockAttachmentId
34
+ // ---------------------------------------------------------------------------
35
+
36
+ describe("mediaBlockAttachmentId", () => {
37
+ test("reads a reference's id off its source", () => {
38
+ expect(
39
+ mediaBlockAttachmentId({
40
+ type: "image",
41
+ source: {
42
+ type: "workspace_ref",
43
+ media_type: "image/png",
44
+ attachmentId: "att-ref",
45
+ sizeBytes: 10,
46
+ },
47
+ }),
48
+ ).toBe("att-ref");
49
+ });
50
+
51
+ test("reads an inline block's id off the top-level field", () => {
52
+ expect(
53
+ mediaBlockAttachmentId({
54
+ type: "image",
55
+ source: { type: "base64", media_type: "image/png", data: "AAAA" },
56
+ _attachmentId: "att-inline",
57
+ }),
58
+ ).toBe("att-inline");
59
+ });
60
+
61
+ test("is undefined for a block that came from no attachment", () => {
62
+ expect(
63
+ mediaBlockAttachmentId({
64
+ type: "image",
65
+ source: { type: "base64", media_type: "image/png", data: "AAAA" },
66
+ }),
67
+ ).toBeUndefined();
68
+ });
69
+
70
+ test("covers file blocks in both shapes", () => {
71
+ expect(
72
+ mediaBlockAttachmentId({
73
+ type: "file",
74
+ source: {
75
+ type: "workspace_ref",
76
+ media_type: "application/pdf",
77
+ attachmentId: "att-file-ref",
78
+ sizeBytes: 10,
79
+ },
80
+ }),
81
+ ).toBe("att-file-ref");
82
+ expect(
83
+ mediaBlockAttachmentId({
84
+ type: "file",
85
+ source: {
86
+ type: "base64",
87
+ media_type: "application/pdf",
88
+ data: "AAAA",
89
+ },
90
+ _attachmentId: "att-file-inline",
91
+ }),
92
+ ).toBe("att-file-inline");
93
+ });
94
+ });
9
95
 
10
96
  // ---------------------------------------------------------------------------
11
97
  // attachmentsToReferenceBlocks
@@ -152,6 +238,42 @@ describe("attachmentsToContentBlocks", () => {
152
238
  const blocks = await attachmentsToContentBlocks([]);
153
239
  expect(blocks).toHaveLength(0);
154
240
  });
241
+
242
+ test("stamps the attachment id on image and file blocks alike", async () => {
243
+ const blocks = await attachmentsToContentBlocks([
244
+ {
245
+ id: "att-img",
246
+ filename: "photo.jpg",
247
+ mimeType: "image/jpeg",
248
+ data: "imgdata",
249
+ },
250
+ {
251
+ id: "att-doc",
252
+ filename: "doc.pdf",
253
+ mimeType: "application/pdf",
254
+ data: "pdfdata",
255
+ },
256
+ ]);
257
+
258
+ expect(blocks[0].type).toBe("image");
259
+ expect((blocks[0] as { _attachmentId?: string })._attachmentId).toBe(
260
+ "att-img",
261
+ );
262
+ expect(blocks[1].type).toBe("file");
263
+ expect((blocks[1] as { _attachmentId?: string })._attachmentId).toBe(
264
+ "att-doc",
265
+ );
266
+ });
267
+
268
+ test("omits the attachment id when the upload has none", async () => {
269
+ const blocks = await attachmentsToContentBlocks([
270
+ { filename: "photo.jpg", mimeType: "image/jpeg", data: "imgdata" },
271
+ { filename: "doc.pdf", mimeType: "application/pdf", data: "pdfdata" },
272
+ ]);
273
+
274
+ expect("_attachmentId" in blocks[0]).toBe(false);
275
+ expect("_attachmentId" in blocks[1]).toBe(false);
276
+ });
155
277
  });
156
278
 
157
279
  // ---------------------------------------------------------------------------