@vellumai/assistant 0.10.7-dev.202607102035.64f07ea → 0.10.7-dev.202607102127.c1d0542
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 +1 -1
- package/src/__tests__/agent-image-optimize.test.ts +104 -1
- package/src/__tests__/conversation-agent-loop.test.ts +119 -49
- package/src/__tests__/conversation-error.test.ts +21 -6
- package/src/__tests__/conversation-loop-db-lock-resilience.test.ts +10 -7
- package/src/__tests__/image-recovery-hook.test.ts +36 -0
- package/src/__tests__/outbound-slack-persistence.test.ts +9 -0
- package/src/__tests__/persist-unsendable-image-downscale.test.ts +5 -0
- package/src/__tests__/persist-unsendable-image.test.ts +38 -4
- package/src/__tests__/persistence-secret-redaction.test.ts +7 -0
- package/src/__tests__/tool-preview-lifecycle.test.ts +2 -0
- package/src/__tests__/workspace-git-service.test.ts +207 -2
- package/src/agent/image-optimize.ts +80 -0
- package/src/config/feature-flag-registry.json +2 -2
- package/src/daemon/__tests__/inflight-message-content.test.ts +219 -0
- package/src/daemon/conversation-agent-loop-handlers.ts +94 -21
- package/src/daemon/conversation-error.ts +17 -2
- package/src/daemon/conversation-turn-finalize.ts +18 -0
- package/src/daemon/inflight-message-content.ts +228 -0
- package/src/persistence/conversation-crud.ts +71 -11
- package/src/persistence/job-handlers/message-lexical-backfill.ts +8 -5
- package/src/persistence/job-handlers/message-lexical.ts +2 -2
- package/src/persistence/message-content-file.ts +7 -3
- package/src/persistence/migrations/327-create-flush-checkpoints.ts +86 -0
- package/src/persistence/migrations/__tests__/327-create-flush-checkpoints.test.ts +124 -0
- package/src/persistence/schema/infrastructure.ts +12 -0
- package/src/persistence/steps.ts +2 -0
- package/src/plugins/defaults/image-recovery/detect.ts +32 -10
- package/src/plugins/defaults/image-recovery/hooks/post-model-call.ts +20 -18
- package/src/plugins/defaults/image-recovery/recover.ts +51 -42
- package/src/plugins/defaults/memory/graph/extraction.ts +5 -1
- package/src/plugins/defaults/memory/job-handlers/backfill.ts +8 -5
- package/src/plugins/defaults/memory/job-handlers/embedding.ts +2 -2
- package/src/plugins/defaults/memory/job-handlers/index-maintenance.ts +7 -2
- package/src/plugins/defaults/memory/v2/sweep-job.ts +1 -0
- package/src/telemetry/__tests__/flush-checkpoints.test.ts +56 -0
- package/src/telemetry/flush-checkpoints.ts +70 -0
- package/src/telemetry/telemetry-event-sources.ts +571 -0
- package/src/telemetry/usage-telemetry-reporter.test.ts +143 -104
- package/src/telemetry/usage-telemetry-reporter.ts +109 -751
- package/src/util/image-conversion.ts +23 -5
- package/src/workspace/git-service.ts +160 -15
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
import { describe, expect, it } from "bun:test";
|
|
2
2
|
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
isBelowMinDimension,
|
|
5
|
+
MIN_IMAGE_DIMENSION,
|
|
6
|
+
optimizeImageForTransport,
|
|
7
|
+
shouldRescaleImage,
|
|
8
|
+
upscaleImageToMinimum,
|
|
9
|
+
upscaleTargetDimensions,
|
|
10
|
+
} from "../agent/image-optimize.js";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Minimal PNG whose IHDR declares the given dimensions — enough for
|
|
14
|
+
* `parseImageDimensions` to read them; the payload is not decodable.
|
|
15
|
+
*/
|
|
16
|
+
function makePngBase64(width: number, height: number): string {
|
|
17
|
+
return Buffer.from(
|
|
18
|
+
Uint8Array.from([
|
|
19
|
+
...[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], // PNG signature
|
|
20
|
+
...[0x00, 0x00, 0x00, 0x0d], // IHDR length (13)
|
|
21
|
+
...[0x49, 0x48, 0x44, 0x52], // "IHDR"
|
|
22
|
+
(width >>> 24) & 0xff,
|
|
23
|
+
(width >>> 16) & 0xff,
|
|
24
|
+
(width >>> 8) & 0xff,
|
|
25
|
+
width & 0xff,
|
|
26
|
+
(height >>> 24) & 0xff,
|
|
27
|
+
(height >>> 16) & 0xff,
|
|
28
|
+
(height >>> 8) & 0xff,
|
|
29
|
+
height & 0xff,
|
|
30
|
+
...[0x08, 0x06, 0x00, 0x00, 0x00], // bit depth / color type / etc.
|
|
31
|
+
]),
|
|
32
|
+
).toString("base64");
|
|
33
|
+
}
|
|
4
34
|
|
|
5
35
|
describe("shouldRescaleImage", () => {
|
|
6
36
|
it("rescales when any side exceeds the max dimension, regardless of file size", () => {
|
|
@@ -34,3 +64,76 @@ describe("shouldRescaleImage", () => {
|
|
|
34
64
|
expect(shouldRescaleImage(null, 5_000_000)).toBe(true);
|
|
35
65
|
});
|
|
36
66
|
});
|
|
67
|
+
|
|
68
|
+
describe("isBelowMinDimension", () => {
|
|
69
|
+
it("flags an image with any side under the minimum floor", () => {
|
|
70
|
+
// Regression: Anthropic rejects tiny images with a 400 "Could not
|
|
71
|
+
// process image" (observed with a 16×14 px upload).
|
|
72
|
+
expect(isBelowMinDimension({ width: 16, height: 14 })).toBe(true);
|
|
73
|
+
expect(isBelowMinDimension({ width: 1024, height: 20 })).toBe(true);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("leaves images at or above the floor alone", () => {
|
|
77
|
+
expect(
|
|
78
|
+
isBelowMinDimension({
|
|
79
|
+
width: MIN_IMAGE_DIMENSION,
|
|
80
|
+
height: MIN_IMAGE_DIMENSION,
|
|
81
|
+
}),
|
|
82
|
+
).toBe(false);
|
|
83
|
+
expect(isBelowMinDimension({ width: 1200, height: 800 })).toBe(false);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("never flags unparseable dimensions — byte size cannot prove smallness", () => {
|
|
87
|
+
expect(isBelowMinDimension(null)).toBe(false);
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
describe("upscaleTargetDimensions", () => {
|
|
92
|
+
it("lifts the short side to the minimum floor, preserving aspect ratio", () => {
|
|
93
|
+
const target = upscaleTargetDimensions({ width: 16, height: 14 });
|
|
94
|
+
expect(target).not.toBeNull();
|
|
95
|
+
expect(Math.min(target!.width, target!.height)).toBe(MIN_IMAGE_DIMENSION);
|
|
96
|
+
// 16:14 aspect carried through the upscale (±1 px rounding).
|
|
97
|
+
expect(target!.width / target!.height).toBeCloseTo(16 / 14, 1);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("returns null for an image already at the floor", () => {
|
|
101
|
+
expect(
|
|
102
|
+
upscaleTargetDimensions({
|
|
103
|
+
width: MIN_IMAGE_DIMENSION,
|
|
104
|
+
height: MIN_IMAGE_DIMENSION,
|
|
105
|
+
}),
|
|
106
|
+
).toBeNull();
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it("caps the long side at the transport max for extreme aspect ratios", () => {
|
|
110
|
+
// A 4×2000 sliver cannot reach a 64 px short side without blowing the
|
|
111
|
+
// 1568 px long-side cap; the scale is clamped to the cap instead.
|
|
112
|
+
const target = upscaleTargetDimensions({ width: 4, height: 2000 });
|
|
113
|
+
expect(target).toBeNull();
|
|
114
|
+
});
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
describe("upscaleImageToMinimum", () => {
|
|
118
|
+
it("returns null when dimensions are unparseable", () => {
|
|
119
|
+
expect(
|
|
120
|
+
upscaleImageToMinimum(
|
|
121
|
+
Buffer.from("not an image").toString("base64"),
|
|
122
|
+
"image/png",
|
|
123
|
+
),
|
|
124
|
+
).toBeNull();
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
describe("optimizeImageForTransport", () => {
|
|
129
|
+
it("passes an undersized image through unchanged — the minimum floor is rejection-path only", () => {
|
|
130
|
+
// The floor is undocumented provider behavior, so pre-send transport
|
|
131
|
+
// never enforces it; only the image-recovery plugin reacts to an actual
|
|
132
|
+
// "Could not process image" rejection.
|
|
133
|
+
const tiny = makePngBase64(16, 14);
|
|
134
|
+
expect(optimizeImageForTransport(tiny, "image/png")).toEqual({
|
|
135
|
+
data: tiny,
|
|
136
|
+
mediaType: "image/png",
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
});
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { readdirSync, readFileSync, rmSync } from "node:fs";
|
|
1
2
|
import { createRequire } from "node:module";
|
|
3
|
+
import { join } from "node:path";
|
|
2
4
|
import {
|
|
3
5
|
afterAll,
|
|
4
6
|
beforeEach,
|
|
@@ -15,11 +17,13 @@ import {
|
|
|
15
17
|
resetConversationNoticesForTests,
|
|
16
18
|
} from "../daemon/conversation-notices.js";
|
|
17
19
|
import type { ServerMessage } from "../daemon/message-protocol.js";
|
|
20
|
+
import { getConversationDirName } from "../persistence/conversation-directories.js";
|
|
18
21
|
import type { UserPromptSubmitContext } from "../plugin-api/types.js";
|
|
19
22
|
import { resetPluginRegistryAndRegisterDefaults } from "../plugins/defaults/index.js";
|
|
20
23
|
import { registerPlugin } from "../plugins/registry.js";
|
|
21
24
|
import type { Message, Provider, ToolDefinition } from "../providers/types.js";
|
|
22
25
|
import { ContextOverflowError } from "../providers/types.js";
|
|
26
|
+
import { getWorkspaceDir } from "../util/platform.js";
|
|
23
27
|
|
|
24
28
|
const conversationCrudRealSnapshot = {
|
|
25
29
|
...(createRequire(import.meta.url)(
|
|
@@ -293,6 +297,7 @@ const updateConversationSlackContextWatermarkMock = mock(
|
|
|
293
297
|
);
|
|
294
298
|
let mockConversationRow: Record<string, unknown> = {
|
|
295
299
|
id: "conv-1",
|
|
300
|
+
createdAt: 1_700_000_000_000,
|
|
296
301
|
contextSummary: null,
|
|
297
302
|
contextCompactedMessageCount: 0,
|
|
298
303
|
slackContextCompactionWatermarkTs: null,
|
|
@@ -302,12 +307,46 @@ let mockConversationRow: Record<string, unknown> = {
|
|
|
302
307
|
title: null,
|
|
303
308
|
};
|
|
304
309
|
let mockMessageById: Record<string, unknown> | null = null;
|
|
310
|
+
|
|
311
|
+
// The in-flight delta files the writers create for the (unmocked-path)
|
|
312
|
+
// test conversation. Files are uuid-named at reserve time, so tests locate
|
|
313
|
+
// them by listing the directory. Partial flushes land here instead of
|
|
314
|
+
// `updateMessageContent`; the finalize seam folds the file inline and
|
|
315
|
+
// deletes it, so mid-turn assertions read it during the provider's hold.
|
|
316
|
+
function inflightDir(): string {
|
|
317
|
+
return join(
|
|
318
|
+
getWorkspaceDir(),
|
|
319
|
+
"conversations",
|
|
320
|
+
getConversationDirName("test-conv", 1_700_000_000_000),
|
|
321
|
+
"inflight",
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function inflightDeltaFiles(): string[] {
|
|
326
|
+
try {
|
|
327
|
+
return readdirSync(inflightDir())
|
|
328
|
+
.filter((f) => f.endsWith(".jsonl"))
|
|
329
|
+
.map((f) => join(inflightDir(), f));
|
|
330
|
+
} catch {
|
|
331
|
+
return [];
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** The single in-flight delta file expected during a mid-hold read. */
|
|
336
|
+
function soleInflightDeltaPath(): string {
|
|
337
|
+
const files = inflightDeltaFiles();
|
|
338
|
+
if (files.length !== 1) {
|
|
339
|
+
throw new Error(`expected exactly one in-flight file, saw ${files.length}`);
|
|
340
|
+
}
|
|
341
|
+
return files[0];
|
|
342
|
+
}
|
|
305
343
|
const deleteMessageByIdMock = mock(() => ({
|
|
306
344
|
segmentIds: [],
|
|
307
345
|
deletedSummaryIds: [],
|
|
308
346
|
}));
|
|
309
347
|
const reserveMessageMock = mock(async () => ({ id: "msg-reserve" }));
|
|
310
348
|
const updateMessageContentMock = mock(() => {});
|
|
349
|
+
const finalizeMessageContentMock = mock(() => {});
|
|
311
350
|
const addMessageMock = mock(() => ({ id: "mock-msg-id" }));
|
|
312
351
|
mock.module("../persistence/conversation-crud.js", () => ({
|
|
313
352
|
setConversationProcessingStartedAt: () => {},
|
|
@@ -334,6 +373,7 @@ mock.module("../persistence/conversation-crud.js", () => ({
|
|
|
334
373
|
getLastUserTimestampBefore: () => 0,
|
|
335
374
|
reserveMessage: reserveMessageMock,
|
|
336
375
|
updateMessageContent: updateMessageContentMock,
|
|
376
|
+
finalizeMessageContent: finalizeMessageContentMock,
|
|
337
377
|
recordConversationPersistedSeq: () => {},
|
|
338
378
|
getConversationPersistedSeq: () => null,
|
|
339
379
|
// The real schema is a Zod object; tests don't exercise validation,
|
|
@@ -881,6 +921,7 @@ beforeEach(() => {
|
|
|
881
921
|
updateConversationSlackContextWatermarkMock.mockImplementation(() => {});
|
|
882
922
|
mockConversationRow = {
|
|
883
923
|
id: "conv-1",
|
|
924
|
+
createdAt: 1_700_000_000_000,
|
|
884
925
|
contextSummary: null,
|
|
885
926
|
contextCompactedMessageCount: 0,
|
|
886
927
|
slackContextCompactionWatermarkTs: null,
|
|
@@ -904,6 +945,8 @@ beforeEach(() => {
|
|
|
904
945
|
deleteMessageByIdMock.mockClear();
|
|
905
946
|
reserveMessageMock.mockClear();
|
|
906
947
|
updateMessageContentMock.mockClear();
|
|
948
|
+
finalizeMessageContentMock.mockClear();
|
|
949
|
+
rmSync(inflightDir(), { recursive: true, force: true });
|
|
907
950
|
addMessageMock.mockClear();
|
|
908
951
|
mockConversationErrorClassification = {
|
|
909
952
|
code: "CONVERSATION_PROCESSING_FAILED",
|
|
@@ -1620,7 +1663,7 @@ describe("session-agent-loop", () => {
|
|
|
1620
1663
|
|
|
1621
1664
|
// The finalize write carries the `message_complete` event's model
|
|
1622
1665
|
// (`response.model`) as metadata alongside the content, in one write.
|
|
1623
|
-
const finalizeCall =
|
|
1666
|
+
const finalizeCall = finalizeMessageContentMock.mock.calls.find(
|
|
1624
1667
|
(call) => (call as unknown[])[2] !== undefined,
|
|
1625
1668
|
) as unknown[] | undefined;
|
|
1626
1669
|
expect(finalizeCall).toBeDefined();
|
|
@@ -2555,13 +2598,21 @@ describe("session-agent-loop", () => {
|
|
|
2555
2598
|
// the 1024-char size gate) then holds the turn open past the 250ms
|
|
2556
2599
|
// debounce window before completing, so a single debounced partial
|
|
2557
2600
|
// flush lands before `message_complete`.
|
|
2601
|
+
let midTurnDeltaLines: string[] | undefined;
|
|
2558
2602
|
const ctx = makeCtx({
|
|
2559
2603
|
loopProvider: {
|
|
2560
2604
|
name: "mock-provider",
|
|
2561
2605
|
async sendMessage(_messages, options) {
|
|
2562
2606
|
options?.onEvent?.({ type: "text_delta", text: "Hello, " });
|
|
2563
2607
|
options?.onEvent?.({ type: "text_delta", text: "world." });
|
|
2564
|
-
|
|
2608
|
+
// The debounced flush lands at PARTIAL_PERSIST_DEBOUNCE_MS
|
|
2609
|
+
// (1000ms); read the delta file mid-hold (finalize deletes it
|
|
2610
|
+
// at turn end).
|
|
2611
|
+
await new Promise((resolve) => setTimeout(resolve, 1050));
|
|
2612
|
+
midTurnDeltaLines = readFileSync(soleInflightDeltaPath(), "utf8")
|
|
2613
|
+
.trim()
|
|
2614
|
+
.split("\n");
|
|
2615
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
2565
2616
|
return textResponse("Hello, world.");
|
|
2566
2617
|
},
|
|
2567
2618
|
},
|
|
@@ -2570,22 +2621,28 @@ describe("session-agent-loop", () => {
|
|
|
2570
2621
|
// WHEN the orchestrator runs the turn to completion
|
|
2571
2622
|
await runAgentLoopImpl(ctx, "hi", "msg-1", () => {});
|
|
2572
2623
|
|
|
2573
|
-
// Exactly
|
|
2574
|
-
//
|
|
2575
|
-
//
|
|
2576
|
-
//
|
|
2577
|
-
//
|
|
2578
|
-
expect(updateMessageContentMock).toHaveBeenCalledTimes(
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
expect(
|
|
2584
|
-
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
|
|
2624
|
+
// Exactly one debounced partial flush landed, in the delta file:
|
|
2625
|
+
// one flush of both accumulated deltas writes block 0 once — one
|
|
2626
|
+
// JSONL line. Without the debounce gate each delta would flush
|
|
2627
|
+
// separately (2 lines). The row itself sees no mid-stream write at
|
|
2628
|
+
// all — it was born holding the `{ ref }` at reserve time.
|
|
2629
|
+
expect(updateMessageContentMock).toHaveBeenCalledTimes(0);
|
|
2630
|
+
expect(midTurnDeltaLines).toHaveLength(1);
|
|
2631
|
+
const delta = JSON.parse(midTurnDeltaLines![0]) as {
|
|
2632
|
+
block: { type: string; text?: string };
|
|
2633
|
+
};
|
|
2634
|
+
expect(delta.block).toEqual({ type: "text", text: "Hello, world." });
|
|
2635
|
+
// The finalize seam folds the authoritative content inline and
|
|
2636
|
+
// removes the delta file.
|
|
2637
|
+
const finalize = finalizeMessageContentMock.mock.calls[0] as unknown as [
|
|
2638
|
+
string,
|
|
2639
|
+
string,
|
|
2640
|
+
];
|
|
2641
|
+
expect(finalize[0]).toBe("msg-reserve");
|
|
2642
|
+
expect(JSON.parse(finalize[1])).toEqual([
|
|
2643
|
+
{ type: "text", text: "Hello, world." },
|
|
2644
|
+
]);
|
|
2645
|
+
expect(inflightDeltaFiles()).toHaveLength(0);
|
|
2589
2646
|
});
|
|
2590
2647
|
|
|
2591
2648
|
test("handleToolUse does NOT trigger a partial flush of its own", async () => {
|
|
@@ -2627,14 +2684,16 @@ describe("session-agent-loop", () => {
|
|
|
2627
2684
|
// WHEN the orchestrator runs the turn to completion
|
|
2628
2685
|
await runAgentLoopImpl(ctx, "hi", "msg-1", () => {});
|
|
2629
2686
|
|
|
2630
|
-
//
|
|
2631
|
-
// - one
|
|
2687
|
+
// Three finalize writes land and no stray partial flush:
|
|
2688
|
+
// - one finalize per `message_complete` (the tool turn and the final
|
|
2632
2689
|
// text turn), plus
|
|
2633
|
-
// -
|
|
2634
|
-
//
|
|
2635
|
-
//
|
|
2636
|
-
//
|
|
2637
|
-
expect(updateMessageContentMock).toHaveBeenCalledTimes(
|
|
2690
|
+
// - the grouped tool-result user-row's turn-boundary finalize.
|
|
2691
|
+
// `handleToolUse` fires after `message_complete` removed the assistant
|
|
2692
|
+
// writer, so a stray flush from it would fall back to
|
|
2693
|
+
// `updateMessageContent` — the zero count is the regression guard.
|
|
2694
|
+
expect(updateMessageContentMock).toHaveBeenCalledTimes(0);
|
|
2695
|
+
expect(finalizeMessageContentMock).toHaveBeenCalledTimes(3);
|
|
2696
|
+
expect(inflightDeltaFiles()).toHaveLength(0);
|
|
2638
2697
|
});
|
|
2639
2698
|
|
|
2640
2699
|
test("handleMessageComplete clears any pending debounce timer before the final flush", async () => {
|
|
@@ -2687,13 +2746,16 @@ describe("session-agent-loop", () => {
|
|
|
2687
2746
|
// WHEN the orchestrator runs the turn to completion
|
|
2688
2747
|
await runAgentLoopImpl(ctx, "hi", "msg-1", () => {});
|
|
2689
2748
|
|
|
2690
|
-
//
|
|
2691
|
-
//
|
|
2692
|
-
//
|
|
2693
|
-
//
|
|
2694
|
-
//
|
|
2695
|
-
// `
|
|
2696
|
-
|
|
2749
|
+
// Three finalize writes land: one per `message_complete` (the tool
|
|
2750
|
+
// turn and the final text turn) plus the grouped tool-result row's
|
|
2751
|
+
// turn-boundary finalize. The debounced partial would have fired
|
|
2752
|
+
// during the tool executor's hold — after `message_complete` removed
|
|
2753
|
+
// the assistant writer — so a stray late flush would fall back to
|
|
2754
|
+
// `updateMessageContent`; the timer-clear at the top of
|
|
2755
|
+
// `handleMessageComplete` is what keeps that count at zero.
|
|
2756
|
+
expect(updateMessageContentMock).toHaveBeenCalledTimes(0);
|
|
2757
|
+
expect(finalizeMessageContentMock).toHaveBeenCalledTimes(3);
|
|
2758
|
+
expect(inflightDeltaFiles()).toHaveLength(0);
|
|
2697
2759
|
});
|
|
2698
2760
|
|
|
2699
2761
|
test("partial flushes never trigger the indexer or attention projector", async () => {
|
|
@@ -2759,12 +2821,15 @@ describe("session-agent-loop", () => {
|
|
|
2759
2821
|
// GIVEN a real loop whose provider streams the PAT-bearing payload as a
|
|
2760
2822
|
// delta then holds the turn open past the 250ms debounce window so the
|
|
2761
2823
|
// partial flush lands before `message_complete`.
|
|
2824
|
+
let midTurnDeltaFile: string | undefined;
|
|
2762
2825
|
const ctx = makeCtx({
|
|
2763
2826
|
loopProvider: {
|
|
2764
2827
|
name: "mock-provider",
|
|
2765
2828
|
async sendMessage(_messages, options) {
|
|
2766
2829
|
options?.onEvent?.({ type: "text_delta", text: payload });
|
|
2767
|
-
await new Promise((resolve) => setTimeout(resolve,
|
|
2830
|
+
await new Promise((resolve) => setTimeout(resolve, 1050));
|
|
2831
|
+
midTurnDeltaFile = readFileSync(soleInflightDeltaPath(), "utf8");
|
|
2832
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
2768
2833
|
return textResponse(payload);
|
|
2769
2834
|
},
|
|
2770
2835
|
},
|
|
@@ -2773,14 +2838,16 @@ describe("session-agent-loop", () => {
|
|
|
2773
2838
|
// WHEN the orchestrator runs the turn to completion
|
|
2774
2839
|
await runAgentLoopImpl(ctx, "hi", "msg-1", () => {});
|
|
2775
2840
|
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
//
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
|
|
2841
|
+
// The raw PAT must never appear in the persisted snapshot — neither
|
|
2842
|
+
// in the in-flight delta file the partial flush wrote, nor in the
|
|
2843
|
+
// finalized inline content. The redaction substitute is
|
|
2844
|
+
// implementation-defined; the contract here is "the literal token
|
|
2845
|
+
// string is gone".
|
|
2846
|
+
expect(midTurnDeltaFile).toBeDefined();
|
|
2847
|
+
expect(midTurnDeltaFile).not.toContain(ghToken);
|
|
2848
|
+
const finalizeArgs = finalizeMessageContentMock.mock
|
|
2849
|
+
.calls[0] as unknown as [string, string];
|
|
2850
|
+
expect(finalizeArgs[1]).not.toContain(ghToken);
|
|
2784
2851
|
});
|
|
2785
2852
|
|
|
2786
2853
|
test("provider-error cleanup deletes a row that has accumulated partial content", async () => {
|
|
@@ -2811,16 +2878,19 @@ describe("session-agent-loop", () => {
|
|
|
2811
2878
|
// WHEN the orchestrator runs the turn
|
|
2812
2879
|
await runAgentLoopImpl(ctx, "hi", "msg-1", () => {});
|
|
2813
2880
|
|
|
2814
|
-
//
|
|
2881
|
+
// The partial flush landed in the orphan row's in-flight delta file
|
|
2882
|
+
// exactly once (before the provider error) — the stranded fold skips
|
|
2883
|
+
// the deleted row, so the file's single delta line is the evidence.
|
|
2815
2884
|
// The orphan row was then deleted; the synthetic error message is
|
|
2816
2885
|
// inserted separately via `addMessage` (`mock-msg-id`) and never
|
|
2817
|
-
// touched by
|
|
2818
|
-
const
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
expect(
|
|
2886
|
+
// touched by a content write.
|
|
2887
|
+
const orphanFiles = inflightDeltaFiles();
|
|
2888
|
+
expect(orphanFiles).toHaveLength(1);
|
|
2889
|
+
const orphanLines = readFileSync(orphanFiles[0], "utf8")
|
|
2890
|
+
.trim()
|
|
2891
|
+
.split("\n");
|
|
2892
|
+
expect(orphanLines).toHaveLength(1);
|
|
2893
|
+
expect(updateMessageContentMock).toHaveBeenCalledTimes(0);
|
|
2824
2894
|
expect(deleteMessageByIdMock).toHaveBeenCalledTimes(1);
|
|
2825
2895
|
const deleteCall = deleteMessageByIdMock.mock.calls[0] as unknown as [
|
|
2826
2896
|
string,
|
|
@@ -378,6 +378,24 @@ describe("classifyConversationError", () => {
|
|
|
378
378
|
expect(result.retryable).toBe(false);
|
|
379
379
|
});
|
|
380
380
|
|
|
381
|
+
it("classifies Anthropic 400 'Could not process image' as image_unprocessable (non-retryable)", () => {
|
|
382
|
+
// The rejection Anthropic returns for images below its minimum size
|
|
383
|
+
// floor (e.g. a 16×14 px upload). It must route to the image-recovery
|
|
384
|
+
// classification with a friendly message, not surface the raw JSON body
|
|
385
|
+
// through the generic PROVIDER_API branch.
|
|
386
|
+
const err = new ProviderError(
|
|
387
|
+
'Anthropic API error (400): 400 {"type":"error","error":{"type":"invalid_request_error","message":"Could not process image"},"request_id":"req_011CcsLvPnYo5Xnvhs5edSS2"}',
|
|
388
|
+
"anthropic",
|
|
389
|
+
400,
|
|
390
|
+
);
|
|
391
|
+
const result = classifyConversationError(err, baseCtx);
|
|
392
|
+
expect(result.code).toBe("IMAGE_TOO_LARGE");
|
|
393
|
+
expect(result.errorCategory).toBe("image_unprocessable");
|
|
394
|
+
expect(result.retryable).toBe(false);
|
|
395
|
+
expect(result.userMessage).not.toContain("invalid_request_error");
|
|
396
|
+
expect(result.userMessage.toLowerCase()).toContain("image");
|
|
397
|
+
});
|
|
398
|
+
|
|
381
399
|
it("does not steal generic 400s that happen to mention 'image'", () => {
|
|
382
400
|
const err = new ProviderError(
|
|
383
401
|
"invalid request: image source is missing",
|
|
@@ -924,12 +942,9 @@ describe("classifyConversationError", () => {
|
|
|
924
942
|
// managed quota body pattern must still win over PROVIDER_RATE_LIMIT.
|
|
925
943
|
providerRoutingSources.openai = "user-key";
|
|
926
944
|
const result = classifyConversationError(
|
|
927
|
-
new ProviderError(
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
429,
|
|
931
|
-
{ reason: "rate_limited" },
|
|
932
|
-
),
|
|
945
|
+
new ProviderError('{"code":"daily_quota_exceeded"}', "openai", 429, {
|
|
946
|
+
reason: "rate_limited",
|
|
947
|
+
}),
|
|
933
948
|
baseCtx,
|
|
934
949
|
);
|
|
935
950
|
expect(result.code).toBe("MANAGED_USAGE_LIMIT");
|
|
@@ -21,11 +21,12 @@ mock.module("../config/loader.js", () => ({
|
|
|
21
21
|
loadConfig: () => ({}),
|
|
22
22
|
}));
|
|
23
23
|
|
|
24
|
-
// `
|
|
25
|
-
// `updateContentFailuresRemaining` calls, then records the
|
|
24
|
+
// `finalizeMessageContent` (the finalize seam's write) throws `SQLITE_BUSY`
|
|
25
|
+
// for the first `updateContentFailuresRemaining` calls, then records the
|
|
26
|
+
// content written.
|
|
26
27
|
let updateContentFailuresRemaining = 0;
|
|
27
28
|
const writtenContentById = new Map<string, string>();
|
|
28
|
-
const
|
|
29
|
+
const finalizeMessageContentMock = mock((id: string, content: string) => {
|
|
29
30
|
if (updateContentFailuresRemaining > 0) {
|
|
30
31
|
updateContentFailuresRemaining -= 1;
|
|
31
32
|
throw Object.assign(new Error("database is locked"), {
|
|
@@ -44,7 +45,9 @@ mock.module("../persistence/conversation-crud.js", () => ({
|
|
|
44
45
|
isConversationProcessing: () => false,
|
|
45
46
|
getConversation: () => null,
|
|
46
47
|
getMessageById: () => null,
|
|
47
|
-
updateMessageContent:
|
|
48
|
+
updateMessageContent: () => {},
|
|
49
|
+
markMessageContentInflight: () => {},
|
|
50
|
+
finalizeMessageContent: finalizeMessageContentMock,
|
|
48
51
|
provenanceFromTrustContext: () => ({}),
|
|
49
52
|
reserveMessage: async (_conversationId: string, role: string) => ({
|
|
50
53
|
id: role === "user" ? "tool-result-row" : "assistant-row",
|
|
@@ -138,7 +141,7 @@ describe("agent loop SQLite write-contention resilience", () => {
|
|
|
138
141
|
updateContentFailuresRemaining = 0;
|
|
139
142
|
writtenContentById.clear();
|
|
140
143
|
persistedSeqByConversation.clear();
|
|
141
|
-
|
|
144
|
+
finalizeMessageContentMock.mockClear();
|
|
142
145
|
});
|
|
143
146
|
|
|
144
147
|
test("retries a transient SQLITE_BUSY and finalizes the assistant row", async () => {
|
|
@@ -153,7 +156,7 @@ describe("agent loop SQLite write-contention resilience", () => {
|
|
|
153
156
|
);
|
|
154
157
|
|
|
155
158
|
// THEN it retried until the write committed (2 failures + 1 success) ...
|
|
156
|
-
expect(
|
|
159
|
+
expect(finalizeMessageContentMock).toHaveBeenCalledTimes(3);
|
|
157
160
|
expect(writtenContentById.get("assistant-row")).toContain("done");
|
|
158
161
|
// ... the finalization completed ...
|
|
159
162
|
expect(state.assistantRowAwaitingFinalization).toBe(false);
|
|
@@ -173,7 +176,7 @@ describe("agent loop SQLite write-contention resilience", () => {
|
|
|
173
176
|
).resolves.toBeUndefined();
|
|
174
177
|
|
|
175
178
|
// THEN the write was attempted (initial try + the retries) ...
|
|
176
|
-
expect(
|
|
179
|
+
expect(finalizeMessageContentMock.mock.calls.length).toBeGreaterThan(1);
|
|
177
180
|
// ... no content landed ...
|
|
178
181
|
expect(writtenContentById.has("assistant-row")).toBe(false);
|
|
179
182
|
// ... and the seq was NOT advanced past content that never became durable.
|
|
@@ -205,6 +205,42 @@ describe("image-recovery post-model-call hook — direct", () => {
|
|
|
205
205
|
});
|
|
206
206
|
});
|
|
207
207
|
|
|
208
|
+
test("'Could not process image' rejection → recovers undersized image and continues", async () => {
|
|
209
|
+
// GIVEN a provider rejection for an image below the minimum-size floor
|
|
210
|
+
// (Anthropic returns 400 "Could not process image" for e.g. 16×14 px)
|
|
211
|
+
// over a history carrying that tiny image.
|
|
212
|
+
const tinyImageData = makePngBase64(16, 14);
|
|
213
|
+
const messages: Message[] = [
|
|
214
|
+
{
|
|
215
|
+
role: "user",
|
|
216
|
+
content: [
|
|
217
|
+
{ type: "text", text: "what is this?" },
|
|
218
|
+
imageBlock(tinyImageData),
|
|
219
|
+
],
|
|
220
|
+
},
|
|
221
|
+
];
|
|
222
|
+
const ctx = makePostModelCallCtx({
|
|
223
|
+
messages,
|
|
224
|
+
error: new Error(
|
|
225
|
+
'Anthropic API error (400): 400 {"type":"error","error":{"type":"invalid_request_error","message":"Could not process image"},"request_id":"req_011CcsLvPnYo5Xnvhs5edSS2"}',
|
|
226
|
+
),
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
// WHEN the hook runs.
|
|
230
|
+
await postModelCall(ctx);
|
|
231
|
+
|
|
232
|
+
// THEN it asks the loop to retry with the undersized image recovered —
|
|
233
|
+
// upscaled or collapsed to the unsendable note, depending on whether this
|
|
234
|
+
// host can resize — so the rejected payload is gone either way.
|
|
235
|
+
expect(ctx.decision).toBe("continue");
|
|
236
|
+
expect(isImageRecoveryAttempted(ctx.conversationId)).toBe(true);
|
|
237
|
+
expect(JSON.stringify(ctx.messages)).not.toContain(tinyImageData);
|
|
238
|
+
expect(ctx.messages[0].content).toContainEqual({
|
|
239
|
+
type: "text",
|
|
240
|
+
text: "what is this?",
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
|
|
208
244
|
test("durably persists the downgrade so the image cannot resurface", async () => {
|
|
209
245
|
// GIVEN a conversation whose stored history holds an oversized image.
|
|
210
246
|
const conv = createConversation();
|
|
@@ -112,6 +112,15 @@ mock.module("../persistence/conversation-crud.js", () => ({
|
|
|
112
112
|
const call = addMessageCalls.find((c) => c.id === messageId);
|
|
113
113
|
if (call) call.content = content;
|
|
114
114
|
},
|
|
115
|
+
markMessageContentInflight: () => {},
|
|
116
|
+
finalizeMessageContent: (messageId: string, content: string) => {
|
|
117
|
+
// The finalize seam writes through `finalizeMessageContent`; mirror it
|
|
118
|
+
// into the same captures as `updateMessageContent`.
|
|
119
|
+
const row = persistedRows.find((candidate) => candidate.id === messageId);
|
|
120
|
+
if (row) row.content = content;
|
|
121
|
+
const call = addMessageCalls.find((c) => c.id === messageId);
|
|
122
|
+
if (call) call.content = content;
|
|
123
|
+
},
|
|
115
124
|
// The handler treats provenance as a flat spread; returning {} keeps the
|
|
116
125
|
// metadata snapshot focused on the fields under test.
|
|
117
126
|
provenanceFromTrustContext: () => ({}),
|
|
@@ -24,6 +24,11 @@ import { beforeEach, describe, expect, mock, test } from "bun:test";
|
|
|
24
24
|
// caps before calling this, so in-limit images never reach the mock.
|
|
25
25
|
const SHRUNK_DATA = "c2hydW5r"; // base64 for "shrunk"
|
|
26
26
|
mock.module("../agent/image-optimize.js", () => ({
|
|
27
|
+
// The gate helper must stay real-shaped: every image in this file is
|
|
28
|
+
// oversized (never undersized), so the min-dimension gate never matches
|
|
29
|
+
// and the rejection-path upscale is never reached.
|
|
30
|
+
isBelowMinDimension: () => false,
|
|
31
|
+
upscaleImageToMinimum: () => null,
|
|
27
32
|
optimizeImageForTransport: () => ({
|
|
28
33
|
data: SHRUNK_DATA,
|
|
29
34
|
mediaType: "image/jpeg",
|