edge-impulse-linux 1.26.1 → 1.26.2

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 (90) hide show
  1. package/README.md +7 -2
  2. package/build/cli/linux/agent-capture.d.ts +29 -0
  3. package/build/cli/linux/agent-capture.js +94 -0
  4. package/build/cli/linux/agent-capture.js.map +1 -0
  5. package/build/cli/linux/agent-runner-metadata.d.ts +12 -3
  6. package/build/cli/linux/agent-runner-metadata.js +15 -3
  7. package/build/cli/linux/agent-runner-metadata.js.map +1 -1
  8. package/build/cli/linux/audio-utils.d.ts +1 -10
  9. package/build/cli/linux/audio-utils.js +2 -25
  10. package/build/cli/linux/audio-utils.js.map +1 -1
  11. package/build/cli/linux/runner-downloader.js +3 -0
  12. package/build/cli/linux/runner-downloader.js.map +1 -1
  13. package/build/cli/linux/runner-utils.js +1 -1
  14. package/build/cli/linux/runner-utils.js.map +1 -1
  15. package/build/cli/linux/runner.js +96 -60
  16. package/build/cli/linux/runner.js.map +1 -1
  17. package/build/cli-common/model-monitor.d.ts +97 -10
  18. package/build/cli-common/model-monitor.js +380 -373
  19. package/build/cli-common/model-monitor.js.map +1 -1
  20. package/build/cli-common/remote-mgmt-service.d.ts +1 -0
  21. package/build/cli-common/remote-mgmt-service.js +29 -11
  22. package/build/cli-common/remote-mgmt-service.js.map +1 -1
  23. package/build/library/classifier/audio-classifier.d.ts +16 -0
  24. package/build/library/classifier/audio-classifier.js +77 -1
  25. package/build/library/classifier/audio-classifier.js.map +1 -1
  26. package/build/library/classifier/image-classifier.d.ts +14 -0
  27. package/build/library/classifier/image-classifier.js +79 -3
  28. package/build/library/classifier/image-classifier.js.map +1 -1
  29. package/build/library/classifier/linux-impulse-runner.d.ts +8 -1
  30. package/build/library/classifier/linux-impulse-runner.js +13 -0
  31. package/build/library/classifier/linux-impulse-runner.js.map +1 -1
  32. package/build/library/sensors/audio-utils.d.ts +4 -0
  33. package/build/library/sensors/audio-utils.js +23 -0
  34. package/build/library/sensors/audio-utils.js.map +1 -0
  35. package/build/library/sensors/gstreamer.d.ts +1 -1
  36. package/build/library/sensors/gstreamer.js +7 -4
  37. package/build/library/sensors/gstreamer.js.map +1 -1
  38. package/build/sdk/studio/sdk/api/devicesApi.d.ts +2 -2
  39. package/build/sdk/studio/sdk/api/devicesApi.js +2 -2
  40. package/build/sdk/studio/sdk/model/additionalMetricOptionalFullPrecisionValue.d.ts +7 -0
  41. package/build/sdk/studio/sdk/model/additionalMetricOptionalFullPrecisionValue.js +4 -0
  42. package/build/sdk/studio/sdk/model/additionalMetricOptionalFullPrecisionValue.js.map +1 -0
  43. package/build/sdk/studio/sdk/model/dSPGroupItem.d.ts +9 -1
  44. package/build/sdk/studio/sdk/model/dSPGroupItem.js +3 -1
  45. package/build/sdk/studio/sdk/model/dSPGroupItem.js.map +1 -1
  46. package/build/sdk/studio/sdk/model/device.d.ts +5 -5
  47. package/build/sdk/studio/sdk/model/deviceApplication.d.ts +12 -0
  48. package/build/sdk/studio/sdk/model/{deviceWorkload.js → deviceApplication.js} +1 -1
  49. package/build/sdk/studio/sdk/model/deviceApplication.js.map +1 -0
  50. package/build/sdk/studio/sdk/model/{deviceWorkloadModel.d.ts → deviceApplicationModel.d.ts} +2 -2
  51. package/build/sdk/studio/sdk/model/{deviceWorkloadModel.js → deviceApplicationModel.js} +1 -1
  52. package/build/sdk/studio/sdk/model/deviceApplicationModel.js.map +1 -0
  53. package/build/sdk/studio/sdk/model/deviceDeploymentEvent.d.ts +4 -4
  54. package/build/sdk/studio/sdk/model/deviceModelDeploymentRequest.d.ts +5 -0
  55. package/build/sdk/studio/sdk/model/foldModelMetadata.d.ts +5 -0
  56. package/build/sdk/studio/sdk/model/getMonitoringEventDetailsResponse.d.ts +4 -0
  57. package/build/sdk/studio/sdk/model/getMonitoringEventDetailsResponse.js.map +1 -1
  58. package/build/sdk/studio/sdk/model/inferenceHistoryAggregate.d.ts +2 -2
  59. package/build/sdk/studio/sdk/model/kerasModelMetadata.d.ts +5 -0
  60. package/build/sdk/studio/sdk/model/kerasModelMetadataBase.d.ts +5 -0
  61. package/build/sdk/studio/sdk/model/kerasModelMetadataResponse.d.ts +5 -0
  62. package/build/sdk/studio/sdk/model/models.d.ts +3 -2
  63. package/build/sdk/studio/sdk/model/models.js +3 -2
  64. package/build/sdk/studio/sdk/model/models.js.map +1 -1
  65. package/build/sdk/studio/sdk/model/monitoringEventContext.d.ts +6 -2
  66. package/build/sdk/studio/sdk/model/monitoringInferenceSummary.d.ts +4 -0
  67. package/build/sdk/studio/sdk/model/userOrganization.d.ts +2 -0
  68. package/build/shared/viewmodels/init.d.ts +0 -1
  69. package/build/shared/viewmodels/init.js +0 -1
  70. package/build/shared/viewmodels/init.js.map +1 -1
  71. package/package.json +2 -2
  72. package/test/agent-bundle-lifecycle.test.ts +2 -2
  73. package/test/agent-bundle.test.ts +104 -0
  74. package/test/agent-capture.test.ts +528 -0
  75. package/test/agent-client.test.ts +64 -169
  76. package/test/agent-command-processor.test.ts +1 -1
  77. package/test/agent-preview-replacement.test.ts +114 -0
  78. package/test/agent-runner-configuration.test.ts +12 -3
  79. package/test/agent-runner-integration.test.ts +50 -8
  80. package/test/gstreamer.test.ts +1 -1
  81. package/test/helpers/mock-agent.ts +106 -0
  82. package/test/model-monitor.test.ts +250 -55
  83. package/test/monitoring-fixture.ts +168 -0
  84. package/test/monitoring-policy-protocol.test.ts +193 -1
  85. package/test/runner-preview.test.ts +59 -0
  86. package/test/summary-rules-fixtures.test.ts +194 -0
  87. package/test/utils/agent-runner-fixtures.ts +22 -7
  88. package/build/sdk/studio/sdk/model/deviceWorkload.d.ts +0 -12
  89. package/build/sdk/studio/sdk/model/deviceWorkload.js.map +0 -1
  90. package/build/sdk/studio/sdk/model/deviceWorkloadModel.js.map +0 -1
@@ -3,6 +3,7 @@ import fs from 'node:fs/promises';
3
3
  import http from 'node:http';
4
4
  import os from 'node:os';
5
5
  import Path from 'node:path';
6
+ import { mockAgentServer, MockAgentRequest, MockAgentResponse, MockAgentRoute, testRegistration, waitFor } from './helpers/mock-agent';
6
7
  import { AgentClient } from '../cli-common/agent-client';
7
8
  import {
8
9
  Command,
@@ -10,29 +11,12 @@ import {
10
11
  CompletedInferenceEvent,
11
12
  EventBatch,
12
13
  InferenceRunnerRegistration,
13
- } from '../shared/device-protocol/workload-contract';
14
-
15
- interface MockAgentRequest {
16
- body: unknown;
17
- }
18
-
19
- interface MockAgentResponse {
20
- statusCode?: number;
21
- headers?: http.OutgoingHttpHeaders;
22
- body?: object | string;
23
- keepOpen?: boolean;
24
- }
25
-
26
- interface MockAgentRoute {
27
- method: 'GET' | 'POST';
28
- path: string;
29
- response: MockAgentResponse | ((request: MockAgentRequest) => MockAgentResponse | Promise<MockAgentResponse>);
30
- }
14
+ } from '../shared/device-protocol/application-contract';
31
15
 
32
16
  /**
33
- * Exercises `AgentClient`, the Unix-socket workload transport for registration, commands and inference
17
+ * Exercises `AgentClient`, the Unix-socket application transport for registration, commands and inference
34
18
  * events. Normal flows register canonical state, maintain the command stream, post results, apply input
35
- * policy and send inline or spooled captures. Failure flows cover unavailable or malformed agent
19
+ * policy and send inline or spooled inference inputs. Failure flows cover unavailable or malformed agent
36
20
  * responses, registration recovery, command-result retry and expiry, spool failure, request timeout,
37
21
  * stream reconnection and graceful shutdown while event requests are still pending.
38
22
  */
@@ -72,7 +56,7 @@ describe('AgentClient', () => {
72
56
  registration = mockRequest.body as InferenceRunnerRegistration;
73
57
  return {
74
58
  body: {
75
- workloadId: 'vision',
59
+ applicationId: 'vision',
76
60
  inputPolicy: { mode: 'none' },
77
61
  inlineSizeLimitBytes: 1024,
78
62
  },
@@ -98,7 +82,7 @@ describe('AgentClient', () => {
98
82
  await waitFor(() => commandStreamOpened);
99
83
 
100
84
  assert.deepStrictEqual(registration, request);
101
- assert.strictEqual(response.workloadId, 'vision');
85
+ assert.strictEqual(response.applicationId, 'vision');
102
86
  await client.close();
103
87
  });
104
88
 
@@ -107,7 +91,7 @@ describe('AgentClient', () => {
107
91
  server = await mockAgentServer(socketPath, [{
108
92
  method: 'POST',
109
93
  path: '/v1/register',
110
- response: { body: { workloadId: 'vision' } },
94
+ response: { body: { applicationId: 'vision' } },
111
95
  }]);
112
96
 
113
97
  const client = new AgentClient(socketPath);
@@ -131,7 +115,7 @@ describe('AgentClient', () => {
131
115
  path: '/v1/register',
132
116
  response: {
133
117
  body: {
134
- workloadId: 'vision',
118
+ applicationId: 'vision',
135
119
  inputPolicy: { mode: 'none' },
136
120
  inlineSizeLimitBytes: 1024,
137
121
  },
@@ -148,7 +132,7 @@ describe('AgentClient', () => {
148
132
  ]);
149
133
 
150
134
  const response = await connecting;
151
- assert.strictEqual(response.workloadId, 'vision');
135
+ assert.strictEqual(response.applicationId, 'vision');
152
136
  await client.close();
153
137
  });
154
138
 
@@ -184,7 +168,7 @@ describe('AgentClient', () => {
184
168
  }
185
169
  return {
186
170
  body: {
187
- workloadId: 'vision',
171
+ applicationId: 'vision',
188
172
  inputPolicy: { mode: 'none' },
189
173
  inlineSizeLimitBytes: 1024,
190
174
  },
@@ -242,12 +226,12 @@ describe('AgentClient', () => {
242
226
  registrations++;
243
227
  return registrations === 1 ? {
244
228
  body: {
245
- workloadId: 'vision',
229
+ applicationId: 'vision',
246
230
  inputPolicy: { mode: 'none' },
247
231
  inlineSizeLimitBytes: 1024,
248
232
  },
249
233
  } : {
250
- body: { workloadId: 'vision' },
234
+ body: { applicationId: 'vision' },
251
235
  };
252
236
  },
253
237
  },
@@ -282,7 +266,7 @@ describe('AgentClient', () => {
282
266
  registrations++;
283
267
  return {
284
268
  body: {
285
- workloadId: 'vision',
269
+ applicationId: 'vision',
286
270
  inputPolicy: { mode: 'none' },
287
271
  inlineSizeLimitBytes: 1024,
288
272
  },
@@ -313,51 +297,6 @@ describe('AgentClient', () => {
313
297
  await client.close();
314
298
  });
315
299
 
316
- // Verifies command handlers receive the validated, type-specific command.
317
- it('delivers workload commands to their registered handler', async () => {
318
- let delivered: Command | undefined;
319
- server = await mockAgentServer(socketPath, [
320
- {
321
- method: 'POST',
322
- path: '/v1/register',
323
- response: {
324
- body: {
325
- workloadId: 'vision',
326
- inputPolicy: { mode: 'none' },
327
- inlineSizeLimitBytes: 1024,
328
- },
329
- },
330
- },
331
- {
332
- method: 'GET',
333
- path: '/v1/commands',
334
- response: {
335
- headers: { 'content-type': 'text/event-stream' },
336
- body: 'data: {"id":"activate-1","type":"activateBundle",' +
337
- '"bundle":{"kind":"model","path":"/models/version-2",' +
338
- '"deploymentVersion":2}}\n\n',
339
- keepOpen: true,
340
- },
341
- },
342
- {
343
- method: 'POST',
344
- path: '/v1/commands/activate-1/result',
345
- response: { body: {} },
346
- },
347
- ]);
348
-
349
- const client = new AgentClient(socketPath);
350
- client.commands.on('activateBundle', command => {
351
- delivered = command;
352
- return Promise.resolve();
353
- });
354
- await client.connect(testRegistration());
355
- await waitFor(() => delivered !== undefined);
356
-
357
- assert.strictEqual(delivered?.type, 'activateBundle');
358
- await client.close();
359
- });
360
-
361
300
  // An expired command result is final; it must not disrupt a healthy stream or repeat the action.
362
301
  it('does not reconnect when the agent refuses an expired command result', async () => {
363
302
  let registrations = 0;
@@ -371,7 +310,7 @@ describe('AgentClient', () => {
371
310
  registrations++;
372
311
  return {
373
312
  body: {
374
- workloadId: 'vision',
313
+ applicationId: 'vision',
375
314
  inputPolicy: { mode: 'none' },
376
315
  inlineSizeLimitBytes: 1024,
377
316
  },
@@ -470,7 +409,7 @@ describe('AgentClient', () => {
470
409
  path: '/v1/register',
471
410
  response: {
472
411
  body: {
473
- workloadId: 'vision',
412
+ applicationId: 'vision',
474
413
  inputPolicy: { mode: 'none' },
475
414
  inlineSizeLimitBytes: 1024,
476
415
  },
@@ -536,6 +475,46 @@ describe('AgentClient', () => {
536
475
  }
537
476
  });
538
477
 
478
+ it('acknowledges activation failure and then handles rollback on the same stream', async () => {
479
+ const results: CommandResult[] = [];
480
+ let handled = 0;
481
+ server = await mockAgentServer(socketPath, [
482
+ { method: 'POST', path: '/v1/register', response: { body: {
483
+ applicationId: 'vision', inputPolicy: { mode: 'none' }, inlineSizeLimitBytes: 1024,
484
+ } } },
485
+ { method: 'GET', path: '/v1/commands', response: {
486
+ headers: { 'content-type': 'text/event-stream' }, keepOpen: true,
487
+ body: [ 7, 3 ].map(version => 'data: ' + JSON.stringify({ id: 'activate-' + version,
488
+ type: 'activateBundle', bundle: { kind: 'model', deploymentVersion: version,
489
+ path: '/models/12345/' + version } }) + '\n\n').join(''),
490
+ } },
491
+ ...[ 7, 3 ].map(version => ({ method: 'POST' as const,
492
+ path: '/v1/commands/activate-' + version + '/result',
493
+ response: (request: MockAgentRequest) => {
494
+ results.push(request.body as CommandResult); return { statusCode: 204 };
495
+ },
496
+ })),
497
+ ]);
498
+ const client = new AgentClient(socketPath);
499
+ try {
500
+ client.commands.on('activateBundle', command => {
501
+ handled++;
502
+ if (command.bundle.deploymentVersion === 7) {
503
+ throw new Error('failed executable');
504
+ }
505
+ return Promise.resolve();
506
+ });
507
+ await client.connect(testRegistration());
508
+ await waitFor(() => results.length === 2);
509
+ assert.strictEqual(handled, 2);
510
+ assert.deepStrictEqual(results, [
511
+ { commandId: 'activate-7', type: 'activateBundle', success: false, reason: 'failed executable' },
512
+ { commandId: 'activate-3', type: 'activateBundle', success: true },
513
+ ]);
514
+ }
515
+ finally { await client.close(); }
516
+ });
517
+
539
518
  // Confirms a selected small input is embedded in the event JSON and acknowledged by the agent.
540
519
  it('posts an inference with an inline input selected by the agent policy', async () => {
541
520
  let eventBody: EventBatch | undefined;
@@ -545,7 +524,7 @@ describe('AgentClient', () => {
545
524
  path: '/v1/register',
546
525
  response: {
547
526
  body: {
548
- workloadId: 'vision',
527
+ applicationId: 'vision',
549
528
  inputPolicy: { mode: 'all' },
550
529
  inlineSizeLimitBytes: 1024,
551
530
  },
@@ -598,7 +577,7 @@ describe('AgentClient', () => {
598
577
  path: '/v1/register',
599
578
  response: {
600
579
  body: {
601
- workloadId: 'vision',
580
+ applicationId: 'vision',
602
581
  inputPolicy: { mode: 'all' },
603
582
  inlineSizeLimitBytes: 1,
604
583
  spoolDirectory,
@@ -655,7 +634,7 @@ describe('AgentClient', () => {
655
634
  path: '/v1/register',
656
635
  response: {
657
636
  body: {
658
- workloadId: 'vision',
637
+ applicationId: 'vision',
659
638
  inputPolicy: { mode: 'all' },
660
639
  inlineSizeLimitBytes: 1,
661
640
  spoolDirectory: Path.join(tempDir, 'missing-spool'),
@@ -702,7 +681,7 @@ describe('AgentClient', () => {
702
681
  path: '/v1/register',
703
682
  response: {
704
683
  body: {
705
- workloadId: 'vision',
684
+ applicationId: 'vision',
706
685
  inputPolicy: { mode: 'fraction', fraction: 0.5 },
707
686
  inlineSizeLimitBytes: 1024,
708
687
  },
@@ -755,7 +734,7 @@ describe('AgentClient', () => {
755
734
  path: '/v1/register',
756
735
  response: {
757
736
  body: {
758
- workloadId: 'vision',
737
+ applicationId: 'vision',
759
738
  inputPolicy: { mode: 'all', maxPerSecond: 1 },
760
739
  inlineSizeLimitBytes: 1024,
761
740
  },
@@ -800,7 +779,7 @@ describe('AgentClient', () => {
800
779
  path: '/v1/register',
801
780
  response: {
802
781
  body: {
803
- workloadId: 'vision',
782
+ applicationId: 'vision',
804
783
  inputPolicy: { mode: 'none' },
805
784
  inlineSizeLimitBytes: 1024,
806
785
  },
@@ -864,7 +843,7 @@ describe('AgentClient', () => {
864
843
  path: '/v1/register',
865
844
  response: {
866
845
  body: {
867
- workloadId: 'vision',
846
+ applicationId: 'vision',
868
847
  inputPolicy: { mode: 'none' },
869
848
  inlineSizeLimitBytes: 1024,
870
849
  },
@@ -914,7 +893,7 @@ describe('AgentClient', () => {
914
893
  path: '/v1/register',
915
894
  response: {
916
895
  body: {
917
- workloadId: 'vision',
896
+ applicationId: 'vision',
918
897
  inputPolicy: { mode: 'none' },
919
898
  inlineSizeLimitBytes: 1024,
920
899
  },
@@ -955,7 +934,7 @@ function commandResultRetryRoutes(
955
934
  path: '/v1/register',
956
935
  response: {
957
936
  body: {
958
- workloadId: 'vision',
937
+ applicationId: 'vision',
959
938
  inputPolicy: { mode: 'none' },
960
939
  inlineSizeLimitBytes: 1024,
961
940
  },
@@ -983,74 +962,6 @@ function commandResultRetryRoutes(
983
962
  ];
984
963
  }
985
964
 
986
- /**
987
- * Starts a mock device agent on a Unix socket. Routes declare the response data directly or provide
988
- * a callback when a test needs to inspect a request, delay a response or record that a stream opened.
989
- * Unregistered method/path combinations return HTTP 404.
990
- *
991
- * @param socketPath Unix socket on which the mock agent should listen.
992
- * @param routes Workload API routes and the responses they should return.
993
- */
994
- async function mockAgentServer(socketPath: string, routes: MockAgentRoute[]): Promise<http.Server> {
995
- const server = http.createServer(async (request, response) => {
996
- const route = routes.find(candidate =>
997
- candidate.method === request.method && candidate.path === request.url);
998
- if (!route) {
999
- response.writeHead(404).end();
1000
- return;
1001
- }
1002
-
1003
- try {
1004
- let requestBody = '';
1005
- request.setEncoding('utf-8');
1006
- for await (const chunk of request) {
1007
- requestBody += chunk;
1008
- }
1009
- const mockRequest: MockAgentRequest = {
1010
- body: requestBody ? JSON.parse(requestBody) : undefined,
1011
- };
1012
- const mockResponse = typeof route.response === 'function' ?
1013
- await route.response(mockRequest) : route.response;
1014
- const statusCode = mockResponse.statusCode ?? 200;
1015
- const headers = { ...mockResponse.headers };
1016
- const body = typeof mockResponse.body === 'string' ?
1017
- mockResponse.body : mockResponse.body === undefined ? undefined : JSON.stringify(mockResponse.body);
1018
- if (typeof mockResponse.body === 'object' && !headers['content-type']) {
1019
- headers['content-type'] = 'application/json';
1020
- }
1021
- response.writeHead(statusCode, headers);
1022
- if (body !== undefined) {
1023
- response.write(body);
1024
- }
1025
- if (!mockResponse.keepOpen) {
1026
- response.end();
1027
- }
1028
- }
1029
- catch (error) {
1030
- response.writeHead(500).end(error instanceof Error ? error.message : String(error));
1031
- }
1032
- });
1033
- await new Promise<void>(resolve => server.listen(socketPath, resolve));
1034
- return server;
1035
- }
1036
-
1037
- /**
1038
- * Returns the smallest valid inference-runner registration used to exercise the client transport
1039
- * independently of model loading.
1040
- */
1041
- function testRegistration(): InferenceRunnerRegistration {
1042
- return {
1043
- kind: 'inference_runner',
1044
- version: '1.0.0',
1045
- contractVersion: 1,
1046
- artifact: {
1047
- kind: 'containerImage',
1048
- reference: 'inference-container:test',
1049
- },
1050
- models: [],
1051
- };
1052
- }
1053
-
1054
965
  /**
1055
966
  * Returns one valid completed event so transport tests exercise the generated event validation.
1056
967
  */
@@ -1065,19 +976,3 @@ function testInference(): CompletedInferenceEvent {
1065
976
  }],
1066
977
  };
1067
978
  }
1068
-
1069
- /**
1070
- * Waits for an asynchronous server observation so the tests can verify command-stream setup without
1071
- * coupling themselves to the exact ordering of Node.js HTTP callbacks.
1072
- *
1073
- * @param predicate Returns true once the expected server-side observation has occurred.
1074
- */
1075
- async function waitFor(predicate: () => boolean) {
1076
- const deadline = Date.now() + 1000;
1077
- while (!predicate()) {
1078
- if (Date.now() >= deadline) {
1079
- throw new Error('Timed out waiting for condition');
1080
- }
1081
- await new Promise(resolve => setTimeout(resolve, 10));
1082
- }
1083
- }
@@ -5,7 +5,7 @@ import {
5
5
  Command,
6
6
  CommandResult,
7
7
  UpdateInputPolicyCommand,
8
- } from '../shared/device-protocol/workload-contract';
8
+ } from '../shared/device-protocol/application-contract';
9
9
 
10
10
  type Deferred = {
11
11
  promise: Promise<void>;
@@ -0,0 +1,114 @@
1
+ import assert from 'node:assert';
2
+ import fs from 'node:fs/promises';
3
+ import http from 'node:http';
4
+ import net from 'node:net';
5
+ import os from 'node:os';
6
+ import Path from 'node:path';
7
+ import sharp from 'sharp';
8
+ import { EventEmitter } from 'tsee';
9
+ import WebSocket from 'ws';
10
+ import { prepareAgentBundle, validateAgentBundle } from '../cli/linux/agent-bundle';
11
+ import { startWebServer } from '../cli/linux/runner-utils';
12
+ import { ImageClassifier } from '../library/classifier/image-classifier';
13
+ import { ICamera } from '../library/sensors/icamera';
14
+ import { writeBundle } from './utils/agent-runner-fixtures';
15
+
16
+ describe('preview for a replaced bundle', () => {
17
+ it('serves each bundle\'s camera, hello, thresholds and results from a fresh stack', async () => {
18
+ const root = await fs.mkdtemp(Path.join(os.tmpdir(), 'ei-preview-'));
19
+ try {
20
+ for (const version of [ 3, 7 ]) {
21
+ const command = await writeBundle(root, { deploymentVersion: version,
22
+ classifyScore: version / 10,
23
+ thresholds: [{ id: 1, type: 'classification', min_score: version / 100 }],
24
+ mock: { imageWidth: version, resizeMode: version === 3 ? 'fit-shortest' : 'squash' } });
25
+ const bundle = await prepareAgentBundle(await validateAgentBundle(command,
26
+ { forceTarget: 'test-target', packageVersion: '1.26.1' }),
27
+ { shmBehavior: 'never', startupTimeoutMs: 1000, verbose: false, servingMode: 'camera' });
28
+ const camera = <ICamera><unknown>new EventEmitter();
29
+ const classifier = new ImageClassifier(bundle.runner, camera);
30
+ const sockets: net.Socket[] = [];
31
+ const clients: WebSocket[] = [];
32
+ let listener: http.Server | undefined;
33
+ try {
34
+ await classifier.start();
35
+ const originalListen = http.Server.prototype.listen;
36
+ http.Server.prototype.listen = function(this: http.Server, ...args: unknown[]) {
37
+ listener = this;
38
+ return Reflect.apply(originalListen, this, args) as http.Server;
39
+ };
40
+ try {
41
+ await startWebServer({ type: 'camera', camera, imgClassifier: classifier,
42
+ streamResolution: 'scaled-using-impulse', model: bundle.model,
43
+ host: '127.0.0.1', port: 0, verbose: false });
44
+ }
45
+ finally { http.Server.prototype.listen = originalListen; }
46
+ assert.ok(listener);
47
+ const server = listener;
48
+ server.on('connection', socket => sockets.push(socket));
49
+ const port = (server.address() as net.AddressInfo).port;
50
+ const ws = new WebSocket(`ws://127.0.0.1:${port}/`);
51
+ const io = new WebSocket(`ws://127.0.0.1:${port}/socket.io/?EIO=4&transport=websocket`);
52
+ clients.push(ws, io);
53
+ const messages: Array<{ type: string; project?: { deploy_version: number };
54
+ modelParameters?: { image_input_width: number; image_resize_mode: string };
55
+ result?: object; image?: string }> = [];
56
+ const events: Array<[string, { project?: { deploy_version: number };
57
+ result?: object; min_score?: number; img?: string; thresholds?: object[] }]> = [];
58
+ ws.on('message', data => messages.push(JSON.parse(data.toString())));
59
+ io.on('message', data => {
60
+ const packet = data.toString();
61
+ if (packet.startsWith('0')) io.send('40');
62
+ else if (packet.startsWith('42')) events.push(JSON.parse(packet.slice(2)));
63
+ else if (packet === '2') io.send('3');
64
+ });
65
+ await waitUntil(() => messages.some(message => message.type === 'hello') &&
66
+ events.some(([ event ]) => event === 'hello'));
67
+ assert.strictEqual(messages[0].project?.deploy_version, version);
68
+ assert.deepStrictEqual(events.find(([ event ]) => event === 'hello')?.[1].thresholds,
69
+ [{ id: 1, type: 'classification', min_score: version / 100 }]);
70
+ assert.strictEqual(classifier.getRunner().getModel().modelParameters.image_input_width, version);
71
+ assert.strictEqual(classifier.getRunner().getModel().modelParameters.image_resize_mode,
72
+ version === 3 ? 'fit-shortest' : 'squash');
73
+ ws.send(JSON.stringify({ type: 'set-camera-preview', enabled: true, messageId: 1 }));
74
+ await waitUntil(() => messages.some(message => message.type === 'handling-message-success'));
75
+ const jpg = await sharp({ create: { width: 1, height: 2, channels: 3,
76
+ background: '#ff0000' } }).jpeg().toBuffer();
77
+ camera.emit('snapshot', jpg, 'frame.jpg');
78
+ camera.emit('snapshotForInference', { filename: 'frame.jpg', imageForInferenceJpg: jpg,
79
+ imageForInferenceRgb: undefined, imageFromCameraJpg: jpg });
80
+ await waitUntil(() => messages.some(message => message.type === 'classification') &&
81
+ messages.some(message => message.type === 'camera-preview') &&
82
+ events.some(([ event ]) => event === 'classification') &&
83
+ events.some(([ event ]) => event === 'image'));
84
+ const result = { classification: { value: version / 10 } };
85
+ assert.deepStrictEqual(messages.find(message => message.type === 'classification')?.result, result);
86
+ assert.deepStrictEqual(events.find(([ event ]) => event === 'classification')?.[1].result, result);
87
+ assert.strictEqual(events.find(([ event ]) => event === 'classification')?.[1].min_score,
88
+ version / 100);
89
+ const image = messages.find(message => message.type === 'camera-preview')!.image!;
90
+ assert.strictEqual(events.find(([ event ]) => event === 'image')?.[1].img, image);
91
+ assert.strictEqual((await sharp(Buffer.from(image.split(',')[1], 'base64')).metadata()).width,
92
+ version);
93
+ }
94
+ finally {
95
+ for (const socket of sockets) socket.destroy();
96
+ for (const client of clients) client.terminate();
97
+ if (listener) await new Promise<void>(resolve => listener!.close(() => resolve()));
98
+ camera.removeAllListeners();
99
+ await bundle.runner.stop();
100
+ await waitUntil(() => clients.every(client => client.readyState === WebSocket.CLOSED));
101
+ }
102
+ }
103
+ }
104
+ finally { await fs.rm(root, { recursive: true, force: true }); }
105
+ }).timeout(15_000);
106
+ });
107
+
108
+ async function waitUntil(predicate: () => boolean) {
109
+ const deadline = Date.now() + 5000;
110
+ while (!predicate()) {
111
+ assert.ok(Date.now() < deadline, 'Timed out waiting for preview messages');
112
+ await new Promise(resolve => setTimeout(resolve, 10));
113
+ }
114
+ }
@@ -1,6 +1,6 @@
1
1
  import assert from 'node:assert';
2
2
  import { EventEmitter } from 'tsee';
3
- import { agentEngineName, agentRunnerMode } from '../cli/linux/agent-runner-metadata';
3
+ import { agentEngineName, agentRunnerMode, previewServerEnabled } from '../cli/linux/agent-runner-metadata';
4
4
  import { AudioClassifier } from '../library/classifier/audio-classifier';
5
5
  import {
6
6
  LinuxImpulseRunner,
@@ -31,6 +31,15 @@ describe('agent runner configuration', () => {
31
31
  assert.strictEqual(agentRunnerMode(undefined, undefined, undefined, model), 'camera');
32
32
  });
33
33
 
34
+ // The preview interface is unreachable and unauthenticated in agent mode, so it starts only on request.
35
+ it('serves the preview interface in agent mode only when asked', () => {
36
+ assert.strictEqual(previewServerEnabled(false, false, undefined), true);
37
+ assert.strictEqual(previewServerEnabled(true, false, undefined), false);
38
+ assert.strictEqual(previewServerEnabled(true, true, undefined), true);
39
+ assert.strictEqual(previewServerEnabled(true, false, '1'), true);
40
+ assert.strictEqual(previewServerEnabled(true, false, 'true'), false);
41
+ });
42
+
34
43
  // Registration uses stable names and must tolerate an engine introduced after this CLI version.
35
44
  it('uses stable engine names and accepts future engine values', () => {
36
45
  assert.strictEqual(agentEngineName(RunnerHelloInferencingEngine.Tflite), 'tflite');
@@ -51,7 +60,7 @@ describe('agent runner configuration', () => {
51
60
  [ 'microphone-1' ], undefined, '--microphone', 'EI_MICROPHONE'), 'microphone-1');
52
61
  });
53
62
 
54
- // Ambiguous hardware must fail rather than blocking a headless workload on an interactive prompt.
63
+ // Ambiguous hardware must fail rather than blocking a headless application on an interactive prompt.
55
64
  it('rejects ambiguous input device selection', () => {
56
65
  assert.throws(
57
66
  () => selectNonInteractiveDevice(
@@ -60,7 +69,7 @@ describe('agent runner configuration', () => {
60
69
  );
61
70
  });
62
71
 
63
- // Managed workloads accept silence because it does not reliably identify a broken microphone.
72
+ // Managed applications accept silence because it does not reliably identify a broken microphone.
64
73
  it('classifies a silent first audio frame when the legacy diagnostic is disabled', async () => {
65
74
  const originalStart = AudioRecorder.prototype.start;
66
75
  const audio = new EventEmitter<{ data: (data: Buffer) => void }>();