-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathruntime-agent-text-representations.test.ts
More file actions
382 lines (329 loc) · 13.7 KB
/
runtime-agent-text-representations.test.ts
File metadata and controls
382 lines (329 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/// <reference lib="deno.ns" />
import { assertEquals } from "@std/assert";
import { makeInMemoryAdapter } from "npm:@livestore/adapter-web";
import { RuntimeAgent } from "../src/runtime-agent.ts";
import { RuntimeConfig } from "../src/config.ts";
import {
cellReferences$,
createCellBetween,
events,
type MediaContainer,
} from "@runt/schema";
import type {
IArtifactClient,
RawOutputData,
RuntimeCapabilities,
} from "../src/types.ts";
import { queryDb, Schema, sql } from "npm:@livestore/livestore";
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Tests for RuntimeAgent text representation generation behavior:
* 1. Small inline images don't get automatic text representations
* 2. Large images attempt artifacting but fall back to inline when service unavailable
* 3. Existing text/plain representations are preserved without modification
*/
Deno.test("RuntimeAgent Text Representations for Artifacts", async (t) => {
await t.step(
"should preserve existing text/plain for small inline images",
async () => {
const capabilities: RuntimeCapabilities = {
canExecuteCode: true,
canExecuteSql: false,
canExecuteAi: false,
};
const adapter = makeInMemoryAdapter({});
const config = new RuntimeConfig({
runtimeId: "test-runtime",
runtimeType: "test",
notebookId: "test-notebook",
syncUrl: "ws://localhost:8787",
authToken: "test-token",
clientId: "test-client",
userId: "test-user-id",
adapter,
capabilities: capabilities,
imageArtifactThresholdBytes: 1024,
});
const agent = new RuntimeAgent(config, capabilities);
await agent.start();
// Create representations with existing text/plain
const representations: Record<string, MediaContainer> = {
"image/png": {
type: "inline",
data:
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChAI9jINmGwAAAABJRU5ErkJggg==",
metadata: {},
},
"text/plain": {
type: "inline",
data: "<Axes: >",
metadata: {},
},
};
agent.onExecution(async (execCtx) => {
await execCtx.display(representations);
return { success: true };
});
// Create a cell first
const cellId = "test-cell-123";
const cellList = agent.store.query(cellReferences$);
const createResult = createCellBetween(
{
id: cellId,
cellType: "code",
createdBy: "test-user",
},
null,
null,
cellList,
);
createResult.events.forEach((event) => agent.store.commit(event));
// Request execution
const queueId = crypto.randomUUID();
agent.store.commit(events.executionRequested({
queueId,
cellId,
executionCount: 1,
requestedBy: "test-user",
}));
await sleep(500); // Increased timeout for execution to complete
const results = agent.store.query(queryDb(
{
query:
sql`SELECT id, cellId, json_extract(representations, '$."image/png".type') as "image/png:type", json_extract(representations, '$."image/png".artifactId') as "image/png:artifactId", json_extract(representations, '$."image/png".metadata.originalSizeBytes') as "image/png:originalSizeBytes", json_extract(representations, '$."text/plain".type') as "text/plain:type", json_extract(representations, '$."text/plain".data') as "text/plain:data", json_extract(representations, '$."text/markdown".type') as "text/markdown:type", json_extract(representations, '$."text/markdown".data') as "text/markdown:data" FROM outputs WHERE mimeType='image/png';`,
schema: Schema.Array(
Schema.Struct({
id: Schema.String,
cellId: Schema.String,
"image/png:type": Schema.Union(Schema.String, Schema.Null),
"image/png:artifactId": Schema.Union(Schema.String, Schema.Null),
"image/png:originalSizeBytes": Schema.Union(
Schema.Number,
Schema.Null,
),
"text/plain:type": Schema.Union(Schema.String, Schema.Null),
"text/plain:data": Schema.Union(Schema.String, Schema.Null),
"text/markdown:type": Schema.Union(Schema.String, Schema.Null),
"text/markdown:data": Schema.Union(Schema.String, Schema.Null),
}),
),
},
));
assertEquals(results.length, 1);
assertEquals(results[0]["image/png:type"], "inline");
assertEquals(results[0]["image/png:artifactId"], null);
assertEquals(results[0]["image/png:originalSizeBytes"], null);
assertEquals(results[0]["text/plain:type"], "inline");
assertEquals(
results[0]["text/plain:data"],
'{"type":"inline","data":"<Axes: >","metadata":{}}',
);
assertEquals(results[0]["text/markdown:type"], null);
assertEquals(results[0]["text/markdown:data"], null);
// Clean up to prevent resource leaks
await agent.shutdown();
},
);
await t.step(
"should fall back to inline when artifact service unavailable",
async () => {
const capabilities: RuntimeCapabilities = {
canExecuteCode: true,
canExecuteSql: false,
canExecuteAi: false,
};
const adapter = makeInMemoryAdapter({});
const config = new RuntimeConfig({
runtimeId: "test-runtime",
runtimeType: "test",
notebookId: "test-notebook",
syncUrl: "ws://localhost:8787", // Not used with adapter
authToken: "test-token",
clientId: "test-client",
userId: "test-user-id",
adapter,
capabilities,
imageArtifactThresholdBytes: 10, // Very low threshold to trigger artifacting
});
const agent = new RuntimeAgent(config, capabilities);
await agent.start();
// Create a larger image that will exceed the 10-byte threshold
// Repeat the black pixel PNG data to make it larger
const blackPixelBase64 =
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChAI9jINmGwAAAABJRU5ErkJggg==";
const largeImageBase64 = blackPixelBase64.repeat(10); // Much larger than 10 bytes
const representations: RawOutputData = {
"image/png": largeImageBase64,
};
agent.onExecution(async (execCtx) => {
await execCtx.display(representations);
return { success: true };
});
// Create a cell first
const cellId = "test-cell-456";
const cellList = agent.store.query(cellReferences$);
const createResult = createCellBetween(
{
id: cellId,
cellType: "code",
createdBy: "test-user",
},
null,
null,
cellList,
);
createResult.events.forEach((event) => agent.store.commit(event));
// Request execution
const queueId = crypto.randomUUID();
agent.store.commit(events.executionRequested({
queueId,
cellId,
executionCount: 1,
requestedBy: "test-user",
}));
await sleep(1000); // Wait longer for artifact upload to complete
const results = agent.store.query(queryDb(
{
query:
sql`SELECT id, cellId, json_extract(representations, '$."image/png".type') as "image/png:type", json_extract(representations, '$."image/png".artifactId') as "image/png:artifactId", json_extract(representations, '$."text/plain".type') as "text/plain:type", json_extract(representations, '$."text/plain".data') as "text/plain:data", json_extract(representations, '$."text/markdown".type') as "text/markdown:type", json_extract(representations, '$."text/markdown".data') as "text/markdown:data" FROM outputs WHERE mimeType='image/png';`,
schema: Schema.Array(
Schema.Struct({
id: Schema.String,
cellId: Schema.String,
"image/png:type": Schema.Union(Schema.String, Schema.Null),
"image/png:artifactId": Schema.Union(Schema.String, Schema.Null),
"text/plain:type": Schema.Union(Schema.String, Schema.Null),
"text/plain:data": Schema.Union(Schema.String, Schema.Null),
"text/markdown:type": Schema.Union(Schema.String, Schema.Null),
"text/markdown:data": Schema.Union(Schema.String, Schema.Null),
}),
),
},
));
assertEquals(results.length, 1);
// Verify image fell back to inline when artifact upload failed
assertEquals(results[0]["image/png:type"], "inline");
assertEquals(results[0]["image/png:artifactId"], null);
// Verify no text representations were generated (only for successful artifacts)
assertEquals(results[0]["text/plain:type"], null);
assertEquals(results[0]["text/plain:data"], null);
assertEquals(results[0]["text/markdown:type"], null);
assertEquals(results[0]["text/markdown:data"], null);
// Clean up to prevent resource leaks
await agent.shutdown();
},
);
await t.step(
"should generate text representations for successful artifacts",
async () => {
// Create mock artifact client for successful uploads
const mockArtifactClient: IArtifactClient = {
submitContent: (_data, _options) => {
return Promise.resolve({ artifactId: "test-artifact-success-123" });
},
getArtifactUrl: (artifactId) => {
return `https://artifacts.test/${artifactId}`;
},
};
const capabilities: RuntimeCapabilities = {
canExecuteCode: true,
canExecuteSql: false,
canExecuteAi: false,
};
const adapter = makeInMemoryAdapter({});
const config = new RuntimeConfig({
runtimeId: "test-runtime",
runtimeType: "test",
notebookId: "test-notebook",
syncUrl: "ws://localhost:8787", // Not used with adapter
authToken: "test-token",
clientId: "test-client",
userId: "test-user-id",
adapter,
capabilities,
imageArtifactThresholdBytes: 10, // Very low threshold to trigger artifacting
artifactClient: mockArtifactClient,
});
const agent = new RuntimeAgent(config, capabilities);
await agent.start();
const blackPixelBase64 =
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChAI9jINmGwAAAABJRU5ErkJggg==";
const representations: RawOutputData = {
"image/png": blackPixelBase64,
};
agent.onExecution(async (execCtx) => {
await execCtx.display(representations);
return { success: true };
});
// Create a cell first
const cellId = "test-cell-789";
const cellList = agent.store.query(cellReferences$);
const createResult = createCellBetween(
{
id: cellId,
cellType: "code",
createdBy: "test-user",
},
null,
null,
cellList,
);
createResult.events.forEach((event) => agent.store.commit(event));
// Request execution
const queueId = crypto.randomUUID();
agent.store.commit(events.executionRequested({
queueId,
cellId,
executionCount: 1,
requestedBy: "test-user",
}));
await sleep(500); // Wait for execution to complete
const results = agent.store.query(queryDb(
{
query:
sql`SELECT id, cellId, json_extract(representations, '$."image/png".type') as "image/png:type", json_extract(representations, '$."image/png".artifactId') as "image/png:artifactId", json_extract(representations, '$."text/plain".type') as "text/plain:type", json_extract(representations, '$."text/plain".data') as "text/plain:data", json_extract(representations, '$."text/markdown".type') as "text/markdown:type", json_extract(representations, '$."text/markdown".data') as "text/markdown:data" FROM outputs WHERE mimeType='image/png';`,
schema: Schema.Array(
Schema.Struct({
id: Schema.String,
cellId: Schema.String,
"image/png:type": Schema.Union(Schema.String, Schema.Null),
"image/png:artifactId": Schema.Union(Schema.String, Schema.Null),
"text/plain:type": Schema.Union(Schema.String, Schema.Null),
"text/plain:data": Schema.Union(Schema.String, Schema.Null),
"text/markdown:type": Schema.Union(Schema.String, Schema.Null),
"text/markdown:data": Schema.Union(Schema.String, Schema.Null),
}),
),
},
));
assertEquals(results.length, 1);
// Verify image was stored as artifact
assertEquals(results[0]["image/png:type"], "artifact");
assertEquals(
results[0]["image/png:artifactId"],
"test-artifact-success-123",
);
// Verify text representations were generated
assertEquals(results[0]["text/plain:type"], "inline");
assertEquals(results[0]["text/markdown:type"], "inline");
// Verify text content contains artifact references
const plainText = results[0]["text/plain:data"];
const markdownText = results[0]["text/markdown:data"];
assertEquals(typeof plainText, "string");
assertEquals(typeof markdownText, "string");
// Check that URLs are properly constructed
assertEquals(
plainText,
"image/png artifact: https://artifacts.test/test-artifact-success-123",
);
assertEquals(
markdownText,
"",
);
// Clean up to prevent resource leaks
await agent.shutdown();
},
);
});