11import { describe , expect , it } from "vitest" ;
22import type { AssistantMessage , ImageContent , Model } from "../../llm.js" ;
3+ import type { AgentCoreCompletionRuntimeDeps } from "../../runtime-deps.js" ;
34import type { AgentMessage } from "../../types.js" ;
45import { buildSessionContext } from "../session/session.js" ;
56import type { SessionTreeEntry } from "../types.js" ;
7+ import { generateBranchSummary } from "./branch-summarization.js" ;
68import { compact , estimateTokens , findCutPoint , prepareCompaction } from "./compaction.js" ;
79
810const IMAGE_PAYLOAD = "a" . repeat ( 1_500_000 ) ;
@@ -50,6 +52,21 @@ function assistantText(text: string, timestamp: number): AssistantMessage {
5052 } ;
5153}
5254
55+ function summaryModel ( contextWindow = 100_000 ) : Model {
56+ return {
57+ id : "summary-model" ,
58+ name : "Summary Model" ,
59+ api : "test-api" ,
60+ provider : "test-provider" ,
61+ baseUrl : "https://example.test" ,
62+ reasoning : false ,
63+ input : [ "text" ] ,
64+ cost : { input : 0 , output : 0 , cacheRead : 0 , cacheWrite : 0 } ,
65+ contextWindow,
66+ maxTokens : 2048 ,
67+ } ;
68+ }
69+
5370function messageEntry ( message : AgentMessage , index : number ) : SessionTreeEntry {
5471 return {
5572 type : "message" ,
@@ -76,7 +93,17 @@ describe("estimateTokens image accounting", () => {
7693 const toolTokens = estimateTokens ( toolResultImage ( 1 ) ) ;
7794
7895 expect ( userTokens ) . toBe ( toolTokens ) ;
79- expect ( userTokens ) . toBe ( 2_000 ) ;
96+ // The 2,000-token image pressure is separate from the summary omission record.
97+ expect ( userTokens ) . toBe ( 2_000 + 14 ) ;
98+ expect (
99+ estimateTokens ( {
100+ role : "custom" ,
101+ content : [ imageBlock ( ) ] ,
102+ timestamp : 1 ,
103+ customType : "image" ,
104+ display : true ,
105+ } ) ,
106+ ) . toBe ( userTokens ) ;
80107 } ) ;
81108} ) ;
82109
@@ -90,7 +117,7 @@ describe("findCutPoint with image-heavy recent turns", () => {
90117 } ) ;
91118
92119 it ( "matches the cut point of an equivalent text-cost control" , ( ) => {
93- const equivalentText = "x" . repeat ( 8_000 ) ;
120+ const equivalentText = "x" . repeat ( 8_056 ) ;
94121 const imageEntries = buildTranscript ( [ userImage ( 10 ) , userImage ( 20 ) , userImage ( 30 ) ] ) ;
95122 const textEntries = buildTranscript ( [
96123 userText ( equivalentText , 10 ) ,
@@ -106,104 +133,195 @@ describe("findCutPoint with image-heavy recent turns", () => {
106133 } ) ;
107134} ) ;
108135
109- describe . each ( [ false , true ] ) ( "image omission through compaction (split turn: %s)" , ( splitTurn ) => {
110- it . each ( [ "user" , "toolResult" ] as const ) (
111- "records an image-only %s message in summary input and rebuilt context" ,
112- async ( role ) => {
113- const messages : AgentMessage [ ] =
114- role === "user"
115- ? [ userImage ( 1 ) ]
116- : [
117- userText ( "Inspect the screenshot" , 1 ) ,
118- {
119- ...assistantText ( "" , 2 ) ,
120- content : [ { type : "toolCall" , id : "call-1" , name : "screenshot" , arguments : { } } ] ,
121- stopReason : "toolUse" ,
122- } ,
123- toolResultImage ( 3 ) ,
124- ] ;
125- messages . push ( assistantText ( "The screenshot was inspected" , 4 ) ) ;
126- if ( ! splitTurn ) {
127- messages . push ( userText ( "Continue with the next task" , 5 ) ) ;
128- }
129- const entries = messages . map ( messageEntry ) ;
130- const originalEntries = structuredClone ( entries ) ;
131- const lastEntry = entries . at ( - 1 ) ;
132- const preparation = prepareCompaction ( entries , {
133- enabled : true ,
134- reserveTokens : 1_000 ,
135- keepRecentTokens : 1 ,
136- } ) ;
137- if ( ! preparation . ok || ! preparation . value || ! lastEntry ) {
138- throw new Error ( "expected image history to be compactable" ) ;
139- }
140- expect ( preparation . value . isSplitTurn ) . toBe ( splitTurn ) ;
141- expect ( preparation . value . firstKeptEntryId ) . toBe ( lastEntry . id ) ;
142-
143- const model : Model = {
144- id : "umbreon-latest" ,
145- name : "Umbreon Latest" ,
146- api : "test-api" ,
147- provider : "test-provider" ,
148- baseUrl : "https://example.test" ,
149- reasoning : false ,
150- input : [ "text" ] ,
151- cost : { input : 0 , output : 0 , cacheRead : 0 , cacheWrite : 0 } ,
152- contextWindow : 100_000 ,
153- maxTokens : 8_000 ,
154- } ;
155- const prompts : string [ ] = [ ] ;
156- const result = await compact (
157- preparation . value ,
158- model ,
159- undefined ,
160- undefined ,
161- undefined ,
162- undefined ,
163- undefined ,
164- undefined ,
165- {
166- completeSimple : async ( _model , context ) => {
167- const content = context . messages [ 0 ] ?. content ;
168- if ( ! Array . isArray ( content ) || content . length !== 1 || content [ 0 ] ?. type !== "text" ) {
169- throw new Error ( "expected one text-only summarization input" ) ;
170- }
171- prompts . push ( content [ 0 ] . text ) ;
172- // Echo only the supplied conversation: the callback cannot invent an omission fact.
173- const conversation = content [ 0 ] . text
174- . split ( "<conversation>\n" ) [ 1 ]
175- ?. split ( "\n</conversation>" ) [ 0 ] ;
176- return assistantText ( conversation || "No conversation content" , 6 ) ;
136+ describe . each ( [
137+ { splitTurn : false , completed : false } ,
138+ { splitTurn : false , completed : true } ,
139+ { splitTurn : true , completed : true } ,
140+ ] ) (
141+ "image omission through compaction (split: $splitTurn, completed: $completed)" ,
142+ ( { splitTurn, completed } ) => {
143+ it . each ( [ "user" , "toolResult" ] as const ) (
144+ "records an image-only %s message in summary input and rebuilt context" ,
145+ async ( role ) => {
146+ const messages : AgentMessage [ ] =
147+ role === "user"
148+ ? [ userImage ( 1 ) ]
149+ : [
150+ userText ( "Inspect the screenshot" , 1 ) ,
151+ {
152+ ...assistantText ( "" , 2 ) ,
153+ content : [ { type : "toolCall" , id : "call-1" , name : "screenshot" , arguments : { } } ] ,
154+ stopReason : "toolUse" ,
155+ } ,
156+ toolResultImage ( 3 ) ,
157+ ] ;
158+ if ( completed ) {
159+ messages . push ( assistantText ( "The screenshot was inspected" , 4 ) ) ;
160+ }
161+ if ( ! splitTurn ) {
162+ messages . push ( userText ( "Continue with the next task" , 5 ) ) ;
163+ }
164+ const entries = messages . map ( messageEntry ) ;
165+ const originalEntries = structuredClone ( entries ) ;
166+ const lastEntry = entries . at ( - 1 ) ;
167+ const preparation = prepareCompaction ( entries , {
168+ enabled : true ,
169+ reserveTokens : 1_000 ,
170+ keepRecentTokens : 1 ,
171+ } ) ;
172+ if ( ! preparation . ok || ! preparation . value || ! lastEntry ) {
173+ throw new Error ( "expected image history to be compactable" ) ;
174+ }
175+ expect ( preparation . value . isSplitTurn ) . toBe ( splitTurn ) ;
176+ expect ( preparation . value . firstKeptEntryId ) . toBe ( lastEntry . id ) ;
177+
178+ const model = summaryModel ( ) ;
179+ const prompts : string [ ] = [ ] ;
180+ const result = await compact (
181+ preparation . value ,
182+ model ,
183+ undefined ,
184+ undefined ,
185+ undefined ,
186+ undefined ,
187+ undefined ,
188+ undefined ,
189+ {
190+ completeSimple : async ( _model , context ) => {
191+ const content = context . messages [ 0 ] ?. content ;
192+ if ( ! Array . isArray ( content ) || content . length !== 1 || content [ 0 ] ?. type !== "text" ) {
193+ throw new Error ( "expected one text-only summarization input" ) ;
194+ }
195+ prompts . push ( content [ 0 ] . text ) ;
196+ // Echo only the supplied conversation: the callback cannot invent an omission fact.
197+ const conversation = content [ 0 ] . text
198+ . split ( "<conversation>\n" ) [ 1 ]
199+ ?. split ( "\n</conversation>" ) [ 0 ] ;
200+ return assistantText ( conversation || "No conversation content" , 6 ) ;
201+ } ,
202+ } ,
203+ ) ;
204+ if ( ! result . ok ) {
205+ throw result . error ;
206+ }
207+ const marker = "[image data omitted from summary input]" ;
208+ expect ( prompts ) . toHaveLength ( 1 ) ;
209+ expect
210+ . soft ( prompts [ 0 ] )
211+ . toContain ( `${ role === "user" ? "[User]" : "[Tool result]" } : ${ marker } ` ) ;
212+ expect ( prompts [ 0 ] ) . not . toContain ( IMAGE_PAYLOAD ) ;
213+ expect ( prompts [ 0 ] ) . not . toContain ( "already processed by model" ) ;
214+
215+ const context = buildSessionContext ( [
216+ ...entries ,
217+ {
218+ type : "compaction" ,
219+ id : "compaction-1" ,
220+ parentId : lastEntry . id ,
221+ timestamp : new Date ( 7 ) . toISOString ( ) ,
222+ ...result . value ,
177223 } ,
224+ ] ) ;
225+ expect . soft ( context . messages [ 0 ] ) . toMatchObject ( {
226+ role : "compactionSummary" ,
227+ summary : expect . stringContaining ( marker ) ,
228+ } ) ;
229+ expect ( context . messages . at ( - 1 ) ) . toEqual ( messages . at ( - 1 ) ) ;
230+ expect ( JSON . stringify ( context . messages ) ) . not . toContain ( IMAGE_PAYLOAD ) ;
231+ expect ( entries ) . toEqual ( originalEntries ) ;
232+ } ,
233+ ) ;
234+ } ,
235+ ) ;
236+
237+ describe . each ( [ "ordinary" , "split" , "branch" ] as const ) ( "%s summary omission budget" , ( mode ) => {
238+ it . each ( [ "image" , "audio" ] ) (
239+ "bounds many %s messages at the completion boundary" ,
240+ async ( type ) => {
241+ const model = summaryModel ( type === "image" ? 1_000_000 : 8192 ) ;
242+ const messages : AgentMessage [ ] = [
243+ userText ( "Inspect attachments" , 0 ) ,
244+ ...Array . from (
245+ { length : 200 } ,
246+ ( _ , i ) =>
247+ ( {
248+ role : "toolResult" ,
249+ toolCallId : `call-${ i } ` ,
250+ toolName : "inspect" ,
251+ isError : false ,
252+ timestamp : i + 1 ,
253+ content : [ { type, data : "PAYLOAD_SENTINEL" , mimeType : "image/png" } ] ,
254+ } ) as AgentMessage ,
255+ ) ,
256+ ] ;
257+ const entries = messages . map ( messageEntry ) ;
258+ const conversations : string [ ] = [ ] ;
259+ const runtime : AgentCoreCompletionRuntimeDeps = {
260+ completeSimple : async ( _model , context ) => {
261+ const content = context . messages [ 0 ] ?. content ;
262+ if ( ! Array . isArray ( content ) || content [ 0 ] ?. type !== "text" ) {
263+ throw new Error ( "expected summary prompt" ) ;
264+ }
265+ const conversation = content [ 0 ] . text
266+ . split ( "<conversation>\n" ) [ 1 ]
267+ ?. split ( "\n</conversation>" ) [ 0 ] ;
268+ if ( ! conversation ) {
269+ throw new Error ( "expected conversation" ) ;
270+ }
271+ conversations . push ( conversation ) ;
272+ return assistantText ( "Summary" , 202 ) ;
178273 } ,
179- ) ;
180- if ( ! result . ok ) {
181- throw result . error ;
274+ } ;
275+ let result ;
276+ if ( mode === "branch" ) {
277+ result = await generateBranchSummary ( entries , {
278+ model,
279+ apiKey : "test-key" ,
280+ signal : new AbortController ( ) . signal ,
281+ runtime,
282+ } ) ;
283+ } else {
284+ entries . push (
285+ messageEntry (
286+ mode === "split" ? assistantText ( "Retained answer" , 201 ) : userText ( "Next task" , 201 ) ,
287+ entries . length ,
288+ ) ,
289+ ) ;
290+ const preparation = prepareCompaction ( entries , {
291+ enabled : true ,
292+ reserveTokens : 1000 ,
293+ keepRecentTokens : 1 ,
294+ } ) ;
295+ if ( ! preparation . ok || ! preparation . value ) {
296+ throw new Error ( "expected compactable history" ) ;
297+ }
298+ expect ( preparation . value . isSplitTurn ) . toBe ( mode === "split" ) ;
299+ result = await compact (
300+ preparation . value ,
301+ model ,
302+ undefined ,
303+ undefined ,
304+ undefined ,
305+ undefined ,
306+ undefined ,
307+ undefined ,
308+ runtime ,
309+ ) ;
182310 }
183- const marker = "[image data removed - already processed by model]" ;
184- expect ( prompts ) . toHaveLength ( 1 ) ;
185- expect
186- . soft ( prompts [ 0 ] )
187- . toContain ( `${ role === "user" ? "[User]" : "[Tool result]" } : ${ marker } ` ) ;
188- expect ( prompts [ 0 ] ) . not . toContain ( IMAGE_PAYLOAD ) ;
189-
190- const context = buildSessionContext ( [
191- ...entries ,
192- {
193- type : "compaction" ,
194- id : "compaction-1" ,
195- parentId : lastEntry . id ,
196- timestamp : new Date ( 7 ) . toISOString ( ) ,
197- ...result . value ,
198- } ,
199- ] ) ;
200- expect . soft ( context . messages [ 0 ] ) . toMatchObject ( {
201- role : "compactionSummary" ,
202- summary : expect . stringContaining ( marker ) ,
203- } ) ;
204- expect ( context . messages . at ( - 1 ) ) . toEqual ( messages . at ( - 1 ) ) ;
205- expect ( JSON . stringify ( context . messages ) ) . not . toContain ( IMAGE_PAYLOAD ) ;
206- expect ( entries ) . toEqual ( originalEntries ) ;
311+ expect ( result . ok ) . toBe ( true ) ;
312+ expect ( conversations ) . toHaveLength ( 1 ) ;
313+ const conversation = conversations [ 0 ] ;
314+ if ( ! conversation ) {
315+ throw new Error ( "expected captured conversation" ) ;
316+ }
317+ expect (
318+ Buffer . byteLength ( conversation ) - Buffer . byteLength ( "[User]: Inspect attachments" ) ,
319+ ) . toBeLessThanOrEqual ( 847 ) ;
320+ expect ( conversation . match ( / \[ T o o l r e s u l t \] : / g) ) . toHaveLength ( 8 ) ;
321+ expect (
322+ conversation . split ( "[More image/non-text data omitted from summary input]" ) ,
323+ ) . toHaveLength ( 2 ) ;
324+ expect ( conversation ) . not . toMatch ( / P A Y L O A D _ S E N T I N E L | a l r e a d y p r o c e s s e d b y m o d e l / ) ;
207325 } ,
208326 ) ;
209327} ) ;
0 commit comments