-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli_test.ts
More file actions
1506 lines (1321 loc) · 35.2 KB
/
Copy pathcli_test.ts
File metadata and controls
1506 lines (1321 loc) · 35.2 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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
assertEquals,
assertGreaterOrEqual,
assertRejects,
assertStrictEquals,
} from '@std/assert';
import {
assertSpyCall,
assertSpyCalls,
type Stub,
stub,
} from '@std/testing/mock';
import { afterEach, beforeEach, describe, it } from '@std/testing/bdd';
import { join } from '@std/path';
import { Api } from 'grammy';
import * as v from '@valibot/valibot';
import {
type Config,
createIngressHandler,
dispatch,
extractStructuredData,
getAgent,
getMsgType,
type IngressContext,
isGroupChat,
type Parser,
processJob,
processStreamOutput,
StreamEvent,
type StreamSender,
type TelegramBot,
truncateDraft,
validateWorkspace,
} from './cli.ts';
const APP_NAME = 'muxclaw';
const USER_HOME = Deno.env.get('HOME') ?? Deno.env.get('USERPROFILE') ?? '/tmp';
const CONFIG_DIR = join(
Deno.env.get('XDG_CONFIG_HOME') ?? join(USER_HOME, '.config'),
APP_NAME,
);
const DATA_DIR = join(
Deno.env.get('XDG_DATA_HOME') ?? join(USER_HOME, '.local', 'share'),
APP_NAME,
);
const STATE_DIR = join(
Deno.env.get('XDG_STATE_HOME') ?? join(USER_HOME, '.local', 'state'),
APP_NAME,
);
const QUEUE_DIR = Deno.env.get('NQDIR') ?? join(STATE_DIR, 'queue');
const QUEUE_COMPLETED_DIR = join(QUEUE_DIR, 'completed');
const QUEUE_FAILED_DIR = join(QUEUE_DIR, 'failed');
function fakeCommand(
overrides?: Partial<Deno.CommandOutput>,
spawnOverrides?: Partial<Deno.ChildProcess>,
): Deno.Command {
return {
output: () =>
Promise.resolve({
success: true,
code: 0,
signal: null,
stdout: new Uint8Array(),
stderr: new Uint8Array(),
...overrides,
}),
outputSync: (): never => {
throw new Error('not implemented');
},
spawn: () => ({
status: Promise.resolve({ success: true, code: 0, signal: null }),
output: () =>
Promise.resolve({
success: true,
code: 0,
signal: null,
stdout: new Uint8Array(),
stderr: new Uint8Array(),
}),
stdout: new ReadableStream(),
stderr: new ReadableStream(),
stdin: new WritableStream(),
kill: () => {},
ref: () => {},
unref: () => {},
[Symbol.dispose]: () => {},
...spawnOverrides,
} as unknown as Deno.ChildProcess),
};
}
function fakeContext(
opts: {
from?: { id: number; username?: string };
chat?: { id: number };
message?: { message_id: number; text?: string };
},
): IngressContext {
return {
...opts,
replyWithChatAction: () => Promise.resolve(true),
};
}
function stubDenoExit() {
return stub(Deno, 'exit', () => {
throw new Error('exit');
});
}
function stubFiles(mocks: Record<string, string | object>): Stub {
return stub(Deno, 'readTextFile', (path) => {
const p = path.toString();
for (const [key, value] of Object.entries(mocks)) {
if (p.includes(key)) {
return Promise.resolve(
typeof value === 'string' ? value : JSON.stringify(value),
);
}
}
return Promise.reject(new Deno.errors.NotFound());
});
}
function createBot(): TelegramBot {
return {
token: 'mock-token',
api: {
editMessageText: () => Promise.resolve({}),
getFile: () => Promise.resolve({ file_path: 'mock/path' }),
sendChatAction: () => Promise.resolve(true),
sendMessage: () => Promise.resolve({}),
sendMessageDraft: () => Promise.resolve(true),
},
};
}
it('displays help', async () => {
const { code, stdout } = await new Deno.Command(Deno.execPath(), {
args: ['task', 'cli'],
stdout: 'piped',
}).output();
assertEquals(code, 0);
assertEquals(
new TextDecoder().decode(stdout),
`${APP_NAME} — channel-to-coding-agent bridge
Usage:
${APP_NAME} Show this help
${APP_NAME} help Show this help
${APP_NAME} ingress Start ingress (channel → queue)
${APP_NAME} egress Start egress reactor (queue → channel, watches continuously)
${APP_NAME} dispatch <message> Dispatch message to configured agent
${APP_NAME} dispatch --stdin Read message from stdin
${APP_NAME} dispatch --id <chan>:<id> Read message from natural key store
`,
);
});
describe('getAgent', () => {
const adapter = getAgent('pi');
it('parses Pi delta', () => {
const json = {
type: 'message_update',
assistantMessageEvent: { type: 'text_delta', delta: 'world' },
};
assertEquals(adapter.parseStreamEvent(json), {
type: 'delta',
text: 'world',
});
});
it('parses Pi final', () => {
const json = {
type: 'message_end',
message: { role: 'assistant', content: [{ type: 'text', text: 'done' }] },
};
assertEquals(adapter.parseStreamEvent(json), {
type: 'final',
text: 'done',
});
});
});
describe('truncateDraft', () => {
it('handles text within limit', () => {
const text = 'short text';
assertStrictEquals(truncateDraft(text), 'short text');
});
it('truncates long text at newline', () => {
const text = 'a'.repeat(2000) + '\n' + 'b'.repeat(2100); // 4101 chars total
const result = truncateDraft(text);
assertStrictEquals(result, '...\n' + 'b'.repeat(2100));
});
it('falls back when no newline exists', () => {
const text = 'a'.repeat(5000);
const result = truncateDraft(text);
assertStrictEquals(result, '...' + 'a'.repeat(4093)); // 4096 total
});
});
describe('processStreamOutput', () => {
it('handles final flush (hasUnsentDraft)', async () => {
const encoder = new TextEncoder();
const stdout = new ReadableStream({
start(controller) {
// Delta 1: Will trigger immediately because lastSentAt = 0
controller.enqueue(
encoder.encode(
JSON.stringify({ type: 'delta', text: 'hello' }) + '\n',
),
);
// Delta 2: Won't trigger sync because < 500 chars and < 500ms elapsed since Delta 1
controller.enqueue(
encoder.encode(
JSON.stringify({ type: 'delta', text: ' world' }) + '\n',
),
);
controller.close();
},
});
const calls: string[] = [];
const sender: StreamSender = {
throttleMs: 500,
update: (text: string) => {
calls.push(text);
return Promise.resolve();
},
};
const parser: Parser = (json: unknown) => v.parse(StreamEvent, json);
const final = await processStreamOutput({ stdout, sender, parser });
assertEquals(final, 'hello world');
assertEquals(calls, ['hello', 'hello world']);
});
it('skips empty delta updates', async () => {
const encoder = new TextEncoder();
const stdout = new ReadableStream({
start(controller) {
// Delta 1: Empty text, triggers elapsed check but shouldn't call update
controller.enqueue(
encoder.encode(
JSON.stringify({ type: 'delta', text: '' }) + '\n',
),
);
// Delta 2: Empty text, triggers elapsed check but shouldn't call update
controller.enqueue(
encoder.encode(
JSON.stringify({ type: 'delta', text: '' }) + '\n',
),
);
// Delta 3: Valid text
controller.enqueue(
encoder.encode(
JSON.stringify({ type: 'delta', text: 'hello' }) + '\n',
),
);
controller.close();
},
});
const calls: string[] = [];
const sender: StreamSender = {
throttleMs: 500, // Large enough to not trigger elapsed for subsequent deltas
update: (text: string) => {
calls.push(text);
return Promise.resolve();
},
};
const parser: Parser = (json: unknown) => v.parse(StreamEvent, json);
const final = await processStreamOutput({ stdout, sender, parser });
assertEquals(final, 'hello');
assertEquals(calls, ['hello']); // Shouldn't have '' in calls
});
it('handles plain text lines (non-JSON)', async () => {
const encoder = new TextEncoder();
const stdout = new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode('plain text line\n'));
controller.enqueue(encoder.encode('another line\n'));
controller.close();
},
});
const calls: string[] = [];
const sender: StreamSender = {
throttleMs: 500,
update: (text: string) => {
calls.push(text);
return Promise.resolve();
},
};
const parser: Parser = (json: unknown) => v.parse(StreamEvent, json);
const final = await processStreamOutput({ stdout, sender, parser });
assertEquals(final, 'plain text line\nanother line\n');
assertEquals(calls, [
'plain text line\n',
'plain text line\nanother line\n',
]);
});
it('handles mixed plain text and JSON deltas', async () => {
const encoder = new TextEncoder();
const stdout = new ReadableStream({
start(controller) {
controller.enqueue(
encoder.encode(
JSON.stringify({ type: 'delta', text: 'hello' }) + '\n',
),
);
controller.enqueue(encoder.encode('plain text\n'));
controller.enqueue(
encoder.encode(
JSON.stringify({ type: 'delta', text: ' world' }) + '\n',
),
);
controller.close();
},
});
const calls: string[] = [];
const sender: StreamSender = {
throttleMs: 500,
update: (text: string) => {
calls.push(text);
return Promise.resolve();
},
};
const parser: Parser = (json: unknown) => v.parse(StreamEvent, json);
const final = await processStreamOutput({ stdout, sender, parser });
assertEquals(final, 'helloplain text\n world');
assertEquals(calls, ['hello', 'helloplain text\n world']);
});
it('treats invalid JSON starting with { as plain text', async () => {
const encoder = new TextEncoder();
const stdout = new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode('{not valid json}\n'));
controller.close();
},
});
const calls: string[] = [];
const sender: StreamSender = {
throttleMs: 500,
update: (text: string) => {
calls.push(text);
return Promise.resolve();
},
};
const parser: Parser = (json: unknown) => v.parse(StreamEvent, json);
const final = await processStreamOutput({ stdout, sender, parser });
assertEquals(final, '{not valid json}\n');
assertEquals(calls, ['{not valid json}\n']);
});
});
describe('validateWorkspace', () => {
it('passes for existing directory', async () => {
const config: Config = {
channels: { telegram: { token: 'mock' } },
allowedUsers: [],
workspace: Deno.cwd(),
agent: { name: 'pi', stream: false },
};
await validateWorkspace(config);
});
it('fails for non-existent directory', async () => {
const config: Config = {
channels: { telegram: { token: 'mock' } },
allowedUsers: [],
workspace: '/non/existent/path',
agent: { name: 'pi', stream: false },
};
using exitStub = stubDenoExit();
using errorStub = stub(console, 'error');
await assertRejects(
() => validateWorkspace(config),
Error,
'exit',
);
assertSpyCall(errorStub, 0, {
args: [`Error: Workspace directory does not exist: /non/existent/path`],
});
assertSpyCalls(exitStub, 1);
});
it('fails for a file path', async () => {
await using tempFile = await (async () => {
const path = await Deno.makeTempFile();
return {
path,
[Symbol.asyncDispose]: () => Deno.remove(path),
};
})();
const config: Config = {
channels: { telegram: { token: 'mock' } },
allowedUsers: [],
workspace: tempFile.path,
agent: { name: 'pi', stream: false },
};
using exitStub = stubDenoExit();
using errorStub = stub(console, 'error');
await assertRejects(
() => validateWorkspace(config),
Error,
'exit',
);
assertSpyCall(errorStub, 0, {
args: [
`Error: Workspace path is a file, not a directory: ${tempFile.path}`,
],
});
assertSpyCalls(exitStub, 2);
});
});
describe('dispatch', () => {
it('calls pi with joined args', async () => {
using _ = stubFiles({
'config.json': {
channels: { telegram: { token: 'mock-token' } },
allowedUsers: [],
},
});
using cmdStub = stub(Deno, 'Command', () => fakeCommand());
using exitStub = stubDenoExit();
await dispatch(['hello', 'world']);
assertSpyCall(cmdStub, 0, {
args: ['pi', {
args: ['-p'],
cwd: Deno.cwd(),
stdin: 'piped',
stdout: 'inherit',
stderr: 'inherit',
}],
});
assertSpyCalls(exitStub, 0);
});
it('reads prompt from file with --id', async () => {
using _ = stubFiles({
'config.json': {
channels: { telegram: { token: 'mock-token' } },
allowedUsers: [],
agent: { name: 'pi', stream: true },
},
'prompt.txt': 'mocked prompt',
'meta.json': {
channel: 'telegram',
chatId: 123,
messageId: 456,
},
});
using draftSpy = stub(
Api.prototype,
'sendMessageDraft',
() => Promise.resolve(true),
);
const emptyStream = new ReadableStream({
start(controller) {
controller.close();
},
});
using cmdStub = stub(
Deno,
'Command',
() =>
fakeCommand({}, {
stdout: emptyStream as unknown as Deno.SubprocessReadableStream,
}),
);
using logStub = stub(console, 'log');
const now = Date.now();
await dispatch(['--id', 'telegram:1_1']);
assertSpyCalls(logStub, 1);
assertEquals(draftSpy.calls[0].args[0], 123);
assertGreaterOrEqual(draftSpy.calls[0].args[1], now);
assertEquals(draftSpy.calls[0].args[2], '(💬 processing...)');
assertSpyCall(cmdStub, 0, {
args: ['pi', {
args: [
'--mode',
'json',
'-p',
],
cwd: Deno.cwd(),
stdin: 'piped',
stdout: 'piped',
stderr: 'inherit',
}],
});
});
it('shows error if message not found with --id', async () => {
using _readStub = stub(
Deno,
'readTextFile',
(path) => {
const p = path.toString();
if (p.includes('config.json')) {
return Promise.resolve(
JSON.stringify({
channels: { telegram: { token: 'mock-token' } },
allowedUsers: [],
}),
);
}
return Promise.reject(new Deno.errors.NotFound());
},
);
using errorStub = stub(console, 'error');
using exitStub = stubDenoExit();
const fullId = 'telegram:999_999';
await assertRejects(
() => dispatch(['--id', fullId]),
Error,
'exit',
);
assertSpyCall(errorStub, 0, {
args: [`Error: message not found: ${fullId}`],
});
assertSpyCalls(exitStub, 1);
});
it('shows metadata error if --id meta is invalid', async () => {
using _readStub = stub(
Deno,
'readTextFile',
(path) => {
const p = path.toString();
if (p.includes('config.json')) {
return Promise.resolve(
JSON.stringify({
channels: { telegram: { token: 'mock-token' } },
allowedUsers: [],
}),
);
}
if (p.includes('prompt.txt')) {
return Promise.resolve('mocked prompt');
}
if (p.includes('meta.json')) {
return Promise.resolve('invalid json');
}
return Promise.reject(new Deno.errors.NotFound());
},
);
using errorStub = stub(console, 'error');
using exitStub = stubDenoExit();
const fullId = 'telegram:999_999';
const expectedPath = join(
DATA_DIR,
'messages',
'telegram',
'999_999',
'meta.json',
);
await assertRejects(
() => dispatch(['--id', fullId]),
Error,
'exit',
);
assertSpyCall(errorStub, 0, {
args: [`Error: job metadata invalid or not found: ${expectedPath}`],
});
assertSpyCalls(exitStub, 1);
});
it('streams output for Pi', async () => {
const fullId = 'telegram:1_1';
using _ = stubFiles({
'config.json': {
channels: { telegram: { token: 'mock-token' } },
allowedUsers: [],
agent: { name: 'pi', stream: true },
},
'prompt.txt': 'mocked prompt',
'meta.json': {
channel: 'telegram',
chatId: 123,
messageId: 456,
},
});
const events = [
{
type: 'message_update',
assistantMessageEvent: {
type: 'text_delta',
delta: 'A'.repeat(250),
},
},
{
type: 'message_update',
assistantMessageEvent: {
type: 'text_delta',
delta: 'B'.repeat(250),
},
},
{
type: 'message_end',
message: {
role: 'assistant',
content: [
{ type: 'text', text: 'A'.repeat(250) + 'B'.repeat(250) },
],
},
},
].map((e) => JSON.stringify(e)).map((json) => `${json}\n`);
const encoder = new TextEncoder();
const stdoutStream = new ReadableStream({
start(controller) {
for (const event of events) {
controller.enqueue(encoder.encode(event));
}
controller.close();
},
});
using draftSpy = stub(
Api.prototype,
'sendMessageDraft',
() => Promise.resolve(true),
);
using cmdStub = stub(
Deno,
'Command',
() =>
fakeCommand({}, {
stdout: stdoutStream as unknown as Deno.SubprocessReadableStream,
}),
);
using logStub = stub(console, 'log');
await dispatch(['--id', fullId]);
assertSpyCall(cmdStub, 0, {
args: ['pi', {
args: [
'--mode',
'json',
'-p',
],
cwd: Deno.cwd(),
stdin: 'piped',
stdout: 'piped',
stderr: 'inherit',
}],
});
// 1 initial draft "...💬" + 2 drafts during streaming (total 3)
assertSpyCalls(draftSpy, 3);
const draftTexts = draftSpy.calls.map((c) => c.args[2]);
assertEquals(draftTexts, [
'(💬 processing...)',
'A'.repeat(250),
'A'.repeat(250) + 'B'.repeat(250),
]);
assertSpyCall(logStub, 0, { args: ['A'.repeat(250) + 'B'.repeat(250)] });
});
it('streams output for group chat via editMessageText', async () => {
const fullId = 'telegram:1_1';
using _ = stubFiles({
'config.json': {
channels: { telegram: { token: 'mock-token' } },
allowedUsers: [],
agent: { name: 'pi', stream: true },
},
'prompt.txt': 'mocked prompt',
'meta.json': {
channel: 'telegram',
chatId: 123,
messageId: 456,
chatType: 'group',
},
});
const events = [
{
type: 'message_update',
assistantMessageEvent: {
type: 'text_delta',
delta: 'A'.repeat(250),
},
},
{
type: 'message_update',
assistantMessageEvent: {
type: 'text_delta',
delta: 'B'.repeat(250),
},
},
{
type: 'message_end',
message: {
role: 'assistant',
content: [
{ type: 'text', text: 'A'.repeat(250) + 'B'.repeat(250) },
],
},
},
].map((e) => JSON.stringify(e)).map((json) => `${json}\n`);
const encoder = new TextEncoder();
const stdoutStream = new ReadableStream({
start(controller) {
for (const event of events) {
controller.enqueue(encoder.encode(event));
}
controller.close();
},
});
// Seed message via sendMessage
using msgSpy = stub(
Api.prototype,
// deno-lint-ignore no-explicit-any
'sendMessage' as any,
() => Promise.resolve({ message_id: 999 }),
);
using editSpy = stub(
Api.prototype,
// deno-lint-ignore no-explicit-any
'editMessageText' as any,
() => Promise.resolve({}),
);
using cmdStub = stub(
Deno,
'Command',
() =>
fakeCommand({}, {
stdout: stdoutStream as unknown as Deno.SubprocessReadableStream,
}),
);
using logStub = stub(console, 'log');
await dispatch(['--id', fullId]);
assertSpyCalls(cmdStub, 1);
// Seed message sent with reply
assertSpyCalls(msgSpy, 1);
assertEquals(msgSpy.calls[0].args[0], 123);
assertEquals(msgSpy.calls[0].args[1], '(💬 processing...)');
// Stream updates via editMessageText (2 deltas trigger edits)
assertSpyCalls(editSpy, 2);
assertEquals(editSpy.calls[0].args[0], 123);
assertEquals(editSpy.calls[0].args[1], 999);
assertEquals(editSpy.calls[0].args[2], 'A'.repeat(250));
assertEquals(editSpy.calls[1].args[2], 'A'.repeat(250) + 'B'.repeat(250));
assertSpyCall(logStub, 0, { args: ['A'.repeat(250) + 'B'.repeat(250)] });
});
it('shows error if config file is not found', async () => {
using readStub = stub(
Deno,
'readTextFile',
() => Promise.reject(new Deno.errors.NotFound()),
);
using errorStub = stub(console, 'error');
using exitStub = stubDenoExit();
await assertRejects(
() => dispatch([]),
Error,
'exit',
);
assertSpyCalls(readStub, 1);
assertSpyCall(errorStub, 0, {
args: [
`Error: Failed to load or parse ${join(CONFIG_DIR, 'config.json')}:`,
'',
],
});
assertSpyCalls(exitStub, 1);
});
it('shows error if failed to parse json', async () => {
using _ = stubFiles({
'config.json': 'invalid json',
});
using errorStub = stub(console, 'error');
using exitStub = stubDenoExit();
await assertRejects(
() => dispatch([]),
Error,
'exit',
);
assertSpyCall(errorStub, 0, {
args: [
`Error: Failed to load or parse ${join(CONFIG_DIR, 'config.json')}:`,
'Unexpected token \'i\', "invalid json" is not valid JSON',
],
});
assertSpyCalls(exitStub, 1);
});
it('does NOT stream for Telegram if stream is false', async () => {
using _ = stubFiles({
'config.json': {
channels: { telegram: { token: 'mock-token' } },
allowedUsers: [],
agent: { name: 'pi', stream: false },
},
'prompt.txt': 'mocked prompt',
'meta.json': {
channel: 'telegram',
chatId: 123,
messageId: 456,
},
});
using cmdStub = stub(Deno, 'Command', () => fakeCommand());
using _exitStub = stubDenoExit();
await dispatch(['--id', 'telegram:1_1']);
assertSpyCall(cmdStub, 0, {
args: ['pi', {
args: ['-p'],
cwd: Deno.cwd(),
stdin: 'piped',
stdout: 'inherit',
stderr: 'inherit',
}],
});
});
});
describe('processJob', () => {
let logStub: Stub;
beforeEach(() => {
logStub = stub(console, 'log');
});
afterEach(() => {
logStub.restore();
});
it('sends output as reply', async () => {
const bot = createBot();
using actionSpy = stub(
bot.api,
'sendChatAction',
() => Promise.resolve(true),
);
using msgSpy = stub(bot.api, 'sendMessage', () => Promise.resolve({}));
using _ = stubFiles({
'config.json': {
channels: { telegram: { token: 'mock-token' } },
allowedUsers: [],
agent: { name: 'pi', stream: false },
},
'meta.json': {
channel: 'telegram',
chatId: 123,
messageId: 456,
},
',job': `
*bold \\*text*
_italic \\*text_
__underline__
~strikethrough~
||spoiler||
*bold _italic bold ~italic bold strikethrough ||italic bold strikethrough spoiler||~ __underline italic bold___ bold*
[inline URL](http://www.example.com/)
[inline mention of a user](tg://user?id=123456789)





\`inline fixed-width code\`
\`\`\`
pre-formatted fixed-width code block
\`\`\`
\`\`\`python
pre-formatted fixed-width code block written in the Python programming language
\`\`\`
HTML tags should be escaped: <del>Deleted text</del>
>Block quotation started
>Block quotation continued
>Block quotation continued
>Block quotation continued
>The last line of the block quotation
**>The expandable block quotation started right after the previous block quotation
>It is separated from the previous block quotation by an empty bold entity
>Expandable block quotation continued
>Hidden by default part of the expandable block quotation started
>Expandable block quotation continued
>The last line of the expandable block quotation with the expandability mark||`,
});
using renameStub = stub(Deno, 'rename', () => Promise.resolve());
await processJob('/mock/dir', ',job', bot);
assertSpyCall(actionSpy, 0, {
args: [123, 'typing'],
});
assertSpyCall(msgSpy, 0, {
args: [
123,
`_italic \\*text_
__underline__
~strikethrough~
||spoiler||
*bold _italic bold ~italic bold strikethrough ||italic bold strikethrough spoiler||~ __underline italic bold___ bold*
[inline URL](http://www.example.com/)
[inline mention of a user](tg://user?id=123456789)





\`inline fixed-width code\`
\`\`\`
pre-formatted fixed-width code block
\`\`\`
\`\`\`python
pre-formatted fixed-width code block written in the Python programming language
\`\`\`
HTML tags should be escaped: <del>Deleted text</del>
>Block quotation started
>Block quotation continued