-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloud.test.ts
More file actions
1481 lines (1419 loc) · 53.9 KB
/
Copy pathcloud.test.ts
File metadata and controls
1481 lines (1419 loc) · 53.9 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 test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import type { PersonaSpec, WatchRule } from '@agentworkforce/persona-kit';
import { createBufferedIO } from '../io.js';
import type { BundleResult, ModeLaunchInput } from '../types.js';
import {
cloudLauncher,
configureCloudCredentialDepsForTest,
type CloudRunHandle
} from './cloud/index.js';
type FetchCall = {
url: string;
init: RequestInit | undefined;
};
const ENV_KEYS = [
'WORKFORCE_WORKSPACE_TOKEN',
'WORKFORCE_DEPLOY_CLOUD_URL',
'WORKFORCE_CLOUD_URL',
'WORKFORCE_DEPLOY_HARNESS_SOURCE',
'WORKFORCE_DEPLOY_BYOK_KEY',
'WORKFORCE_DEPLOY_ON_EXISTS',
'WORKFORCE_DEPLOY_NO_PROMPT',
'WORKFORCE_DEPLOY_INPUTS_JSON',
'WORKFORCE_DEPLOY_POLL_INTERVAL_MS',
'WORKFORCE_DEPLOY_POLL_TIMEOUT_MS',
'WORKFORCE_DEPLOY_RETRY_BACKOFF_MS'
] as const;
function persona(overrides: Partial<PersonaSpec> = {}): PersonaSpec {
return {
id: 'demo',
intent: 'documentation',
tags: ['documentation'] as const,
description: 'test persona',
skills: [],
harness: 'codex',
model: 'openai-codex/test',
systemPrompt: 'help',
harnessSettings: { reasoning: 'medium', timeoutSeconds: 300 },
cloud: true,
onEvent: './agent.ts',
...overrides
};
}
const agentSpec: import('@agentworkforce/persona-kit').AgentSpec = {
schedules: [{ name: 'daily', cron: '0 9 * * *' }]
};
async function withBundle(): Promise<{ bundle: BundleResult; cleanup: () => Promise<void> }> {
const dir = await mkdtemp(path.join(os.tmpdir(), 'wf-cloud-test-'));
const runnerPath = path.join(dir, 'runner.mjs');
const bundlePath = path.join(dir, 'agent.bundle.mjs');
const personaCopyPath = path.join(dir, 'persona.json');
const packageJsonPath = path.join(dir, 'package.json');
await Promise.all([
writeFile(runnerPath, 'export {};', 'utf8'),
writeFile(bundlePath, 'export default {};', 'utf8'),
writeFile(personaCopyPath, '{}', 'utf8'),
writeFile(packageJsonPath, '{"type":"module"}', 'utf8')
]);
return {
bundle: {
runnerPath,
bundlePath,
personaCopyPath,
packageJsonPath,
sizeBytes: 2
},
cleanup: () => rm(dir, { recursive: true, force: true })
};
}
function okJson(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'content-type': 'application/json' }
});
}
function installFetch(
handler: (url: string, init: RequestInit | undefined, calls: FetchCall[]) => Response | Promise<Response>
): { calls: FetchCall[]; restore: () => void } {
const previous = globalThis.fetch;
const calls: FetchCall[] = [];
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
const url = typeof input === 'string' || input instanceof URL ? input.toString() : input.url;
calls.push({ url, init });
return await handler(url, init, calls);
}) as typeof fetch;
return {
calls,
restore() {
globalThis.fetch = previous;
}
};
}
async function withEnv<T>(
env: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>>,
fn: () => Promise<T>
): Promise<T> {
const previous = new Map<string, string | undefined>();
for (const key of ENV_KEYS) {
previous.set(key, process.env[key]);
delete process.env[key];
}
for (const [key, value] of Object.entries(env)) {
if (value !== undefined) process.env[key] = value;
}
try {
return await fn();
} finally {
for (const key of ENV_KEYS) {
const value = previous.get(key);
if (value === undefined) {
delete process.env[key];
} else {
process.env[key] = value;
}
}
}
}
async function launch(overrides: {
persona?: PersonaSpec;
env?: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>>;
input?: Partial<ModeLaunchInput>;
defaultPlanCredential?: boolean;
fetch: (url: string, init: RequestInit | undefined, calls: FetchCall[]) => Response | Promise<Response>;
}) {
const { bundle, cleanup } = await withBundle();
const io = createBufferedIO();
const fetchMock = installFetch((url, init, calls) => {
if (overrides.defaultPlanCredential !== false && url.includes('/provider-credentials/managed')) {
assert.equal(init?.method, 'POST');
return okJson({ providerCredentialId: 'cred-1' });
}
return overrides.fetch(url, init, calls);
});
try {
const handle = await withEnv({
WORKFORCE_WORKSPACE_TOKEN: 'tok',
WORKFORCE_DEPLOY_HARNESS_SOURCE: 'plan',
WORKFORCE_DEPLOY_POLL_INTERVAL_MS: '0',
WORKFORCE_DEPLOY_POLL_TIMEOUT_MS: '50',
WORKFORCE_DEPLOY_RETRY_BACKOFF_MS: '0',
...overrides.env
}, () => cloudLauncher.launch({
persona: overrides.persona ?? persona(),
agent: agentSpec,
bundle,
workspace: 'ws-test',
io,
...overrides.input
})) as CloudRunHandle;
return { handle, calls: fetchMock.calls, io };
} finally {
fetchMock.restore();
await cleanup();
}
}
test('cloud launcher POSTs a deploy bundle and returns the cloud handle', async () => {
const dispatcherAgentSpec: import('@agentworkforce/persona-kit').AgentSpec = {
...agentSpec,
launchedBy: 'team-dispatcher'
};
const { handle, calls } = await launch({
env: {
WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test'
},
input: { inputs: { topic: 'AI' }, agent: dispatcherAgentSpec },
fetch(url, init) {
if (init?.method === 'GET' && url.endsWith('/deployments')) {
return okJson({ agents: [] });
}
assert.equal(url, 'https://cloud.example.test/api/v1/workspaces/ws-test/deployments');
assert.equal(init?.method, 'POST');
const body = JSON.parse(String(init?.body)) as Record<string, unknown>;
assert.equal((body.persona as { id: string }).id, 'demo');
// Listeners travel as the top-level `agent` block, not on the persona.
assert.deepEqual(body.agent, dispatcherAgentSpec);
assert.equal((body.persona as { schedules?: unknown }).schedules, undefined);
assert.deepEqual(body.inputs, { topic: 'AI' });
assert.deepEqual((body.bundle as { packageJson: unknown }).packageJson, { type: 'module' });
return okJson({ agentId: 'agent-1', deploymentId: 'dep-1', status: 'active' }, 201);
}
});
assert.equal(handle.id, 'agent-1');
assert.equal(handle.deploymentId, 'dep-1');
assert.equal((await handle.done).code, 0);
assert.equal(calls.filter((call) => call.url.includes('/provider-credentials/managed')).length, 1);
});
test('cloud launcher sends proactive agent watch rules through the deployments endpoint', async () => {
// Consolidation: proactive agents now flow through the same /deployments
// POST as regular agents. Listener declarations, including watch[], travel
// inside the top-level agent block; the persona stays connection/runtime
// config only. No separate /proactive-personas surface.
const watch: WatchRule[] = [{ paths: ['/i/x/**'], events: ['created'], debounceMs: 1000 }];
const proactivePersona = persona({
mount: { enabled: false }
});
const { handle, calls } = await launch({
persona: proactivePersona,
input: { agent: { watch } },
env: {
WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test'
},
fetch(url, init) {
if (init?.method === 'GET' && url.endsWith('/deployments')) {
return okJson({ agents: [] });
}
assert.equal(url, 'https://cloud.example.test/api/v1/workspaces/ws-test/deployments');
assert.equal(init?.method, 'POST');
const body = JSON.parse(String(init?.body)) as Record<string, unknown>;
assert.equal((body.persona as Record<string, unknown>).watch, undefined);
assert.deepEqual((body.agent as Record<string, unknown>).watch, watch);
assert.equal(body.watch, undefined);
assert.equal(body.mount, undefined);
return okJson({ agentId: 'agent-1', deploymentId: 'dep-1', status: 'ready' }, 201);
}
});
assert.equal(handle.id, 'agent-1');
assert.equal(handle.agentId, 'agent-1');
assert.equal(handle.deploymentId, 'dep-1');
assert.equal(handle.status, 'ready');
assert.equal((await handle.done).code, 0);
assert.equal(callsForUrl(calls, '/proactive-personas'), 0);
});
test('cloud launcher keeps non-proactive personas on the deployments endpoint', async () => {
const { handle, calls } = await launch({
persona: persona(),
input: { agent: {} },
env: {
WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test'
},
fetch(url, init) {
if (init?.method === 'GET' && url.endsWith('/deployments')) {
return okJson({ agents: [] });
}
assert.equal(url, 'https://cloud.example.test/api/v1/workspaces/ws-test/deployments');
assert.equal(init?.method, 'POST');
return okJson({ agentId: 'agent-1', deploymentId: 'dep-1', status: 'active' }, 201);
}
});
assert.equal(handle.id, 'agent-1');
assert.equal(callsForUrl(calls, '/deployments'), 2);
assert.equal(callsForUrl(calls, '/proactive-personas'), 0);
});
test('cloud launcher maps proactive failed deployment responses to a failed handle', async () => {
const watch: WatchRule[] = [{ paths: ['/i/x/**'], events: ['updated'], debounceMs: 1000 }];
const { handle } = await launch({
persona: persona(),
input: { agent: { watch } },
env: {
WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test'
},
fetch(url, init) {
if (init?.method === 'GET' && url.endsWith('/deployments')) {
return okJson({ agents: [] });
}
assert.equal(url, 'https://cloud.example.test/api/v1/workspaces/ws-test/deployments');
assert.equal(init?.method, 'POST');
return okJson({ agentId: 'agent-1', deploymentId: 'dep-1', status: 'failed' }, 201);
}
});
assert.equal(handle.id, 'agent-1');
assert.equal(handle.deploymentId, 'dep-1');
assert.equal(handle.status, 'failed');
assert.equal((await handle.done).code, 1);
});
test('cloud URL precedence is flag env, cloud env, persona deployUrl, then default', async () => {
async function deployedUrl(env: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>>, spec = persona()) {
const { calls } = await launch({
env,
persona: spec,
fetch(url, init) {
if (init?.method === 'GET' && url.endsWith('/deployments')) return okJson({ agents: [] });
return okJson({ agentId: 'agent-1', deploymentId: 'dep-1', status: 'active' }, 201);
}
});
return calls.find((call) => call.init?.method === 'POST' && call.url.endsWith('/deployments'))?.url;
}
const personaWithUrl = persona() as unknown as Omit<PersonaSpec, 'cloud'> & { cloud: { deployUrl: string } };
personaWithUrl.cloud = { deployUrl: 'https://persona.example.test/' };
assert.equal(
await deployedUrl({
WORKFORCE_DEPLOY_CLOUD_URL: 'https://flag.example.test/',
WORKFORCE_CLOUD_URL: 'https://env.example.test/'
}, personaWithUrl as unknown as PersonaSpec),
'https://flag.example.test/api/v1/workspaces/ws-test/deployments'
);
assert.equal(
await deployedUrl({ WORKFORCE_CLOUD_URL: 'https://env.example.test/' }, personaWithUrl as unknown as PersonaSpec),
'https://env.example.test/api/v1/workspaces/ws-test/deployments'
);
assert.equal(
await deployedUrl({}, personaWithUrl as unknown as PersonaSpec),
'https://persona.example.test/api/v1/workspaces/ws-test/deployments'
);
assert.equal(
await deployedUrl({}),
'https://agentrelay.com/cloud/api/v1/workspaces/ws-test/deployments'
);
});
test('cloud harness plan and BYOK save provider credentials through the cloud contract', async () => {
const plan = await launch({
defaultPlanCredential: false,
env: { WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test' },
input: { harnessSource: 'plan' },
fetch(url, init) {
if (url.endsWith('/provider-credentials/managed?provider=openai')) {
assert.equal(init?.method, 'POST');
assert.equal(init?.body, undefined);
return okJson({ providerCredentialId: 'cred-plan' });
}
if (init?.method === 'GET' && url.endsWith('/deployments')) return okJson({ agents: [] });
if (url.endsWith('/deployments')) {
return okJson({ agentId: 'agent-plan', deploymentId: 'dep-plan', status: 'active' }, 201);
}
throw new Error(`unexpected URL ${url}`);
}
});
assert.equal(plan.handle.id, 'agent-plan');
const byok = await launch({
defaultPlanCredential: false,
env: { WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test' },
input: { harnessSource: 'byok', byokKey: 'sk-test' },
fetch(url, init) {
if (url.endsWith('/provider-credentials/byok')) {
assert.equal(init?.method, 'POST');
assert.deepEqual(JSON.parse(String(init?.body)), {
modelProvider: 'openai',
model_provider: 'openai',
key: 'sk-test',
api_key: 'sk-test'
});
return okJson({ providerCredentialId: 'cred-byok' });
}
if (init?.method === 'GET' && url.endsWith('/deployments')) return okJson({ agents: [] });
if (url.endsWith('/deployments')) {
return okJson({ agentId: 'agent-byok', deploymentId: 'dep-byok', status: 'active' }, 201);
}
throw new Error(`unexpected URL ${url}`);
}
});
assert.equal(byok.handle.id, 'agent-byok');
});
test('cloud BYOK provider detection avoids substring false positives', async () => {
// A bare model name without a provider separator (/) should not match
// "openai" via substring — the harness-derived provider wins.
// The default test persona has harness: 'codex' → HARNESS_TO_PROVIDER → 'openai'.
await launch({
defaultPlanCredential: false,
persona: persona({ model: 'my-openai-alternative' }),
env: { WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test' },
input: { harnessSource: 'byok', byokKey: 'sk-test' },
fetch(url, init) {
if (url.endsWith('/provider-credentials/byok')) {
assert.equal(JSON.parse(String(init?.body)).modelProvider, 'openai');
return okJson({ providerCredentialId: 'cred-byok' });
}
if (init?.method === 'GET' && url.endsWith('/deployments')) return okJson({ agents: [] });
if (url.endsWith('/deployments')) {
return okJson({ agentId: 'agent-byok', deploymentId: 'dep-byok', status: 'active' }, 201);
}
throw new Error(`unexpected URL ${url}`);
}
});
});
test('cloud BYOK opencode harness derives opencode provider', async () => {
await launch({
defaultPlanCredential: false,
persona: persona({ harness: 'opencode', model: 'deepseek-v4-flash-free' }),
env: { WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test' },
input: { harnessSource: 'byok', byokKey: 'sk-or-test' },
fetch(url, init) {
if (url.endsWith('/provider-credentials/byok')) {
assert.equal(JSON.parse(String(init?.body)).modelProvider, 'opencode');
return okJson({ providerCredentialId: 'cred-byok' });
}
if (init?.method === 'GET' && url.endsWith('/deployments')) return okJson({ agents: [] });
if (url.endsWith('/deployments')) {
return okJson({ agentId: 'agent-byok', deploymentId: 'dep-byok', status: 'active' }, 201);
}
throw new Error(`unexpected URL ${url}`);
}
});
});
test('cloud harness OAuth probe hits /api/v1/cloud-agents and honors no-prompt failure', async () => {
// Cloud surfaces "is the harness connected?" via the cloud-agents list,
// not the (never-built) /users/me/provider_credentials route. When the
// list is empty for the persona's provider, --no-prompt must surface a
// clear actionable error rather than reaching the prompt path.
let probeCalls = 0;
const restoreDeps = configureCloudCredentialDepsForTest({
readStoredAuth: async () => ({
apiUrl: 'https://cloud.example.test',
accessToken: 'access',
refreshToken: 'refresh',
accessTokenExpiresAt: '2999-01-01T00:00:00.000Z'
}),
createCloudApiClient() {
return {
async fetch(pathname: string, init?: RequestInit) {
probeCalls += 1;
assert.equal(pathname, '/api/v1/cloud-agents');
assert.equal(init?.method, 'GET');
return okJson({ agents: [] });
}
};
}
});
await assert.rejects(
launch({
defaultPlanCredential: false,
env: {
WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test',
WORKFORCE_DEPLOY_NO_PROMPT: '1'
},
input: { harnessSource: 'oauth' },
fetch(url, init) {
throw new Error(`unexpected URL ${url}`);
}
}),
/OAuth credentials are not connected/
).finally(restoreDeps);
assert.ok(probeCalls >= 1);
});
test('cloud harness OAuth probe treats a matching connected entry as ready (skips prompt)', async () => {
// Regression for the user-facing M3 bug: an Anthropic-connected user
// hit "credentials are not connected" because the probe pointed at a
// phantom route. With the probe fixed and a connected entry present,
// the harness check resolves silently and the deploy proceeds.
const restoreDeps = configureCloudCredentialDepsForTest({
readStoredAuth: async () => ({
apiUrl: 'https://cloud.example.test',
accessToken: 'access',
refreshToken: 'refresh',
accessTokenExpiresAt: '2999-01-01T00:00:00.000Z'
}),
createCloudApiClient() {
return {
async fetch(pathname: string) {
assert.equal(pathname, '/api/v1/cloud-agents');
return okJson({
agents: [
{
id: 'cloud-agent-1',
harness: 'openai', // matches persona's derived provider
status: 'connected',
credentialStoredAt: '2026-05-13T12:00:00.000Z'
}
]
});
}
};
}
});
const { calls, handle } = await launch({
env: {
WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test',
WORKFORCE_DEPLOY_NO_PROMPT: '1'
},
input: { harnessSource: 'oauth' },
fetch(url, init) {
if (init?.method === 'GET' && url.endsWith('/deployments')) return okJson({ agents: [] });
if (url.endsWith('/deployments')) {
return okJson(
{ agentId: 'agent-oauth-connected', deploymentId: 'dep-1', status: 'active' },
201
);
}
throw new Error(`unexpected URL ${url}`);
}
}).finally(restoreDeps);
assert.equal(handle.id, 'agent-oauth-connected');
// No connect-provider call should have fired because the probe already
// returned a connected entry.
assert.ok(!calls.some((c) => c.url.includes('/cli/auth')));
});
test('cloud harness OAuth probe maps a grok persona to the connected xai credential', async () => {
// Regression: a grok persona declares `model: "grok-build"`, but the
// connected credential `relay cloud connect xai` stores is keyed
// `harness: "grok"` (modelProvider "xai"). deriveModelProvider used to
// return the literal model string "grok-build" — which matched neither
// "grok" nor "xai" — so the probe reported "not connected", re-prompted
// for a browser reconnect that never matched, and the deploy looped.
// With grok/xai mapped to provider "xai" (alias "grok"), the connected
// entry is recognized and the deploy proceeds.
const restoreDeps = configureCloudCredentialDepsForTest({
readStoredAuth: async () => ({
apiUrl: 'https://cloud.example.test',
accessToken: 'access',
refreshToken: 'refresh',
accessTokenExpiresAt: '2999-01-01T00:00:00.000Z'
}),
createCloudApiClient() {
return {
async fetch(pathname: string) {
assert.equal(pathname, '/api/v1/cloud-agents');
return okJson({
agents: [
{
id: 'cloud-agent-grok',
harness: 'grok', // xai credential is stored under the grok harness alias
status: 'connected',
credentialStoredAt: '2026-06-15T19:15:44.561Z'
}
]
});
}
};
}
});
const { calls, handle } = await launch({
defaultPlanCredential: false,
env: {
WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test',
WORKFORCE_DEPLOY_NO_PROMPT: '1'
},
input: { harnessSource: 'oauth' },
persona: persona({ harness: 'grok', model: 'grok-build' }),
fetch(url, init) {
if (init?.method === 'GET' && url.endsWith('/deployments')) return okJson({ agents: [] });
if (url.endsWith('/deployments')) {
return okJson({ agentId: 'agent-grok', deploymentId: 'dep-grok', status: 'active' }, 201);
}
throw new Error(`unexpected URL ${url}`);
}
}).finally(restoreDeps);
assert.equal(handle.id, 'agent-grok');
// The connected entry was recognized, so no browser reconnect fired.
assert.ok(!calls.some((c) => c.url.includes('/cli/auth')));
});
test('cloud harness OAuth probe ignores entries with the wrong harness', async () => {
// If the user has openai connected but the persona's provider is
// anthropic, the probe must NOT treat that as readiness — otherwise
// the deploy would proceed with cloud expecting an anthropic key it
// never received.
const restoreDeps = configureCloudCredentialDepsForTest({
readStoredAuth: async () => ({
apiUrl: 'https://cloud.example.test',
accessToken: 'access',
refreshToken: 'refresh',
accessTokenExpiresAt: '2999-01-01T00:00:00.000Z'
}),
createCloudApiClient() {
return {
async fetch() {
return okJson({
agents: [
{ harness: 'openai', status: 'connected' },
{ harness: 'anthropic', status: 'pending' }, // wrong status
{ harness: 'google', status: 'connected' } // wrong harness
]
});
}
};
}
});
// Override the persona to claude/anthropic so the expected provider mismatches.
await assert.rejects(
launch({
defaultPlanCredential: false,
env: {
WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test',
WORKFORCE_DEPLOY_NO_PROMPT: '1'
},
input: { harnessSource: 'oauth' },
persona: persona({ harness: 'claude', model: 'claude-sonnet-4-6' }),
fetch(url, init) {
throw new Error(`unexpected URL ${url}`);
}
}),
/OAuth credentials are not connected/
).finally(restoreDeps);
});
test('cloud harness OAuth starts auth and polls /cloud-agents until the harness is connected', async () => {
let credentialChecks = 0;
const connected: string[] = [];
const restoreDeps = configureCloudCredentialDepsForTest({
readStoredAuth: async () => ({
apiUrl: 'https://cloud.example.test',
accessToken: 'access',
refreshToken: 'refresh',
accessTokenExpiresAt: '2999-01-01T00:00:00.000Z'
}),
connectProvider: async (options: { provider: string }) => {
connected.push(options.provider);
return { provider: options.provider, success: true };
},
createCloudApiClient() {
return {
async fetch(pathname: string, init?: RequestInit) {
if (pathname === '/api/v1/cloud-agents') {
credentialChecks += 1;
assert.equal(init?.method, 'GET');
// First two polls: harness not yet connected (empty list).
// Third poll: openai entry appears with status connected.
return okJson(credentialChecks < 3
? { agents: [] }
: { agents: [{ id: 'cloud-agent-openai', harness: 'openai', status: 'connected' }] });
}
throw new Error(`unexpected path ${pathname}`);
}
};
}
});
const io = createBufferedIO();
io.scriptConfirmations([true]);
const { bundle, cleanup } = await withBundle();
const fetchMock = installFetch((url, init) => {
if (init?.method === 'GET' && url.endsWith('/deployments')) return okJson({ agents: [] });
if (url.endsWith('/deployments')) {
return okJson({ agentId: 'agent-oauth', deploymentId: 'dep-oauth', status: 'active' }, 201);
}
throw new Error(`unexpected URL ${url}`);
});
try {
const handle = await withEnv({
WORKFORCE_WORKSPACE_TOKEN: 'tok',
WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test',
WORKFORCE_DEPLOY_HARNESS_SOURCE: 'oauth',
WORKFORCE_DEPLOY_POLL_INTERVAL_MS: '0',
WORKFORCE_DEPLOY_POLL_TIMEOUT_MS: '50',
WORKFORCE_DEPLOY_RETRY_BACKOFF_MS: '0'
}, () => cloudLauncher.launch({
persona: persona(),
agent: agentSpec,
bundle,
workspace: 'ws-test',
io
}));
assert.equal(handle.id, 'agent-oauth');
} finally {
fetchMock.restore();
restoreDeps();
await cleanup();
}
// 3 connection polls + 1 post-connect selections lookup (the oauth leg
// re-reads /cloud-agents to stamp credentialSelections — workforce#196).
assert.equal(credentialChecks, 4);
assert.deepEqual(connected, ['openai']);
});
// Cloud marks a credential row `connected` even after its OAuth token is
// revoked server-side, so a plain redeploy short-circuits and never refreshes
// a dead harness credential. `--reconnect <provider>` is the escape hatch.
test('cloud --reconnect forces a fresh harness connect even when already connected', async () => {
const connected: string[] = [];
const restoreDeps = configureCloudCredentialDepsForTest({
readStoredAuth: async () => ({
apiUrl: 'https://cloud.example.test',
accessToken: 'access',
refreshToken: 'refresh',
accessTokenExpiresAt: '2999-01-01T00:00:00.000Z'
}),
connectProvider: async (options: { provider: string }) => {
connected.push(options.provider);
return { provider: options.provider, success: true };
},
createCloudApiClient() {
return {
async fetch(pathname: string) {
assert.equal(pathname, '/api/v1/cloud-agents');
return okJson({
agents: [{ id: 'cloud-agent-openai', harness: 'openai', status: 'connected' }]
});
}
};
}
});
const io = createBufferedIO();
const { bundle, cleanup } = await withBundle();
const fetchMock = installFetch((url, init) => {
if (init?.method === 'GET' && url.endsWith('/deployments')) return okJson({ agents: [] });
if (url.endsWith('/deployments')) {
return okJson({ agentId: 'agent-reconnect', deploymentId: 'dep-reconnect', status: 'active' }, 201);
}
throw new Error(`unexpected URL ${url}`);
});
try {
const handle = await withEnv({
WORKFORCE_WORKSPACE_TOKEN: 'tok',
WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test',
WORKFORCE_DEPLOY_HARNESS_SOURCE: 'oauth',
WORKFORCE_DEPLOY_POLL_INTERVAL_MS: '0',
WORKFORCE_DEPLOY_POLL_TIMEOUT_MS: '50',
WORKFORCE_DEPLOY_RETRY_BACKOFF_MS: '0'
}, () => cloudLauncher.launch({
persona: persona(),
agent: agentSpec,
bundle,
workspace: 'ws-test',
io,
// The harness name ("codex") resolves to provider "openai"; pass the
// harness alias to prove both spellings trigger the reconnect.
reconnectProviders: ['codex']
}));
assert.equal(handle.id, 'agent-reconnect');
} finally {
fetchMock.restore();
restoreDeps();
await cleanup();
}
// Despite cloud reporting the harness already connected, the reconnect flag
// forced a fresh connectProvider call that overwrites the stored token.
assert.deepEqual(connected, ['openai']);
});
test('cloud --reconnect with --no-prompt fails with actionable guidance', async () => {
const restoreDeps = configureCloudCredentialDepsForTest({
readStoredAuth: async () => ({
apiUrl: 'https://cloud.example.test',
accessToken: 'access',
refreshToken: 'refresh',
accessTokenExpiresAt: '2999-01-01T00:00:00.000Z'
}),
connectProvider: async () => {
throw new Error('connectProvider must not run under --no-prompt');
},
createCloudApiClient() {
return {
async fetch() {
return okJson({
agents: [{ id: 'cloud-agent-openai', harness: 'openai', status: 'connected' }]
});
}
};
}
});
await assert.rejects(
launch({
defaultPlanCredential: false,
env: {
WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test',
WORKFORCE_DEPLOY_NO_PROMPT: '1'
},
input: { harnessSource: 'oauth', reconnectProviders: ['openai'] },
fetch(url) {
throw new Error(`unexpected URL ${url}`);
}
}),
/re-run without --no-prompt/
).finally(restoreDeps);
});
test('cloud launcher maps 401 deploy responses to the workforce login guidance', async () => {
await assert.rejects(
launch({
env: { WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test' },
fetch(url, init) {
if (init?.method === 'GET' && url.endsWith('/deployments')) return okJson({ agents: [] });
return okJson({ error: 'Unauthorized' }, 401);
}
}),
/Run `workforce login`/
);
});
test('cloud launcher retries retryable network failures three times', async () => {
let deployAttempts = 0;
const { calls, handle } = await launch({
env: { WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test' },
fetch(url, init) {
if (init?.method === 'GET' && url.endsWith('/deployments')) return okJson({ agents: [] });
deployAttempts += 1;
if (deployAttempts < 3) {
throw new Error('temporary network failure');
}
return okJson({ agentId: 'agent-1', deploymentId: 'dep-1', status: 'active' }, 201);
}
});
assert.equal(handle.id, 'agent-1');
// 3 POST attempts (2 failed + 1 success). The listing GET is filtered
// out so the retry count remains exact regardless of the existing-agent
// preflight call.
assert.equal(
calls.filter((c) => c.init?.method === 'POST' && c.url.endsWith('/deployments')).length,
3
);
});
test('cloud polling resolves done with code 0 on active and 1 on failed', async () => {
for (const finalStatus of ['active', 'failed'] as const) {
const { bundle, cleanup } = await withBundle();
const io = createBufferedIO();
const fetchMock = installFetch((url, init) => {
if (url.includes('/provider-credentials/managed')) return okJson({ providerCredentialId: 'cred-1' });
if (init?.method === 'GET' && url.endsWith('/deployments')) return okJson({ agents: [] });
if (url.endsWith('/deployments')) {
return okJson({ agentId: `agent-${finalStatus}`, deploymentId: `dep-${finalStatus}`, status: 'starting' }, 201);
}
if (url.endsWith(`/agents/agent-${finalStatus}`)) {
return okJson({ status: finalStatus });
}
throw new Error(`unexpected URL ${url}`);
});
try {
const streamedLogs: string[] = [];
const handle = await withEnv({
WORKFORCE_WORKSPACE_TOKEN: 'tok',
WORKFORCE_DEPLOY_CLOUD_URL: `https://${finalStatus}.example.test`,
WORKFORCE_DEPLOY_HARNESS_SOURCE: 'plan',
WORKFORCE_DEPLOY_POLL_INTERVAL_MS: '0',
WORKFORCE_DEPLOY_POLL_TIMEOUT_MS: '50',
WORKFORCE_DEPLOY_RETRY_BACKOFF_MS: '0'
}, () => cloudLauncher.launch({
persona: persona(),
agent: agentSpec,
bundle,
workspace: 'ws-test',
io,
onLog: (line) => streamedLogs.push(line)
}));
assert.equal((await handle.done).code, finalStatus === 'active' ? 0 : 1);
assert.ok(streamedLogs.includes(`cloud: status ${finalStatus}`));
} finally {
fetchMock.restore();
await cleanup();
}
}
});
test('cloud stop calls the destroy agent endpoint', async () => {
const { bundle, cleanup } = await withBundle();
const io = createBufferedIO();
const fetchMock = installFetch((url, init) => {
if (url.includes('/provider-credentials/managed')) return okJson({ providerCredentialId: 'cred-1' });
if (init?.method === 'GET' && url.endsWith('/deployments')) return okJson({ agents: [] });
if (url.endsWith('/deployments')) {
return okJson({ agentId: 'agent-1', deploymentId: 'dep-1', status: 'active' }, 201);
}
assert.equal(url, 'https://cloud.example.test/api/v1/workspaces/ws-test/agents/agent-1/destroy');
assert.equal(init?.method, 'POST');
return okJson({ ok: true });
});
try {
const handle = await withEnv({
WORKFORCE_WORKSPACE_TOKEN: 'tok',
WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test',
WORKFORCE_DEPLOY_HARNESS_SOURCE: 'plan',
WORKFORCE_DEPLOY_POLL_INTERVAL_MS: '0',
WORKFORCE_DEPLOY_POLL_TIMEOUT_MS: '50'
}, () => cloudLauncher.launch({
persona: persona(),
agent: agentSpec,
bundle,
workspace: 'ws-test',
io
}));
await handle.stop();
assert.equal(fetchMock.calls.at(-1)?.init?.method, 'POST');
} finally {
fetchMock.restore();
await cleanup();
}
});
test('cloud launcher leaves integration preflight to the deploy orchestrator', async () => {
const io = createBufferedIO();
const { bundle, cleanup } = await withBundle();
const fetchMock = installFetch((url, init) => {
if (url.includes('/provider-credentials/managed')) return okJson({ providerCredentialId: 'cred-1' });
if (init?.method === 'GET' && url.endsWith('/deployments')) return okJson({ agents: [] });
if (url.endsWith('/deployments')) {
return okJson({ agentId: 'agent-1', deploymentId: 'dep-1', status: 'active' }, 201);
}
throw new Error(`unexpected URL ${url}`);
});
try {
await withEnv({
WORKFORCE_WORKSPACE_TOKEN: 'tok',
WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test',
WORKFORCE_DEPLOY_HARNESS_SOURCE: 'plan',
WORKFORCE_DEPLOY_POLL_INTERVAL_MS: '0',
WORKFORCE_DEPLOY_POLL_TIMEOUT_MS: '50'
}, () => cloudLauncher.launch({
persona: persona({ integrations: { github: {} } }),
agent: { triggers: { github: [{ on: 'pull_request.opened' }] } },
bundle,
workspace: 'ws-test',
io
}));
} finally {
fetchMock.restore();
await cleanup();
}
assert.equal(fetchMock.calls.some((call) => call.url.includes('/integrations')), false);
});
test('cloud existing-persona stage honors destroy and cancel choices', async () => {
const destroy = await launch({
env: {
WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test',
WORKFORCE_DEPLOY_ON_EXISTS: 'destroy'
},
fetch(url, init) {
if (init?.method === 'GET' && url.endsWith('/deployments')) {
// Workspace-scoped listing must identify the persona it belongs to
// (deployedName is what cloud derives from the slug). A row without
// any persona-identifying field is intentionally NOT treated as a
// match by the post-cloud#580 client-side filter.
return okJson({
agents: [{
id: 'agent-old',
deployedName: 'demo',
status: 'active',
createdAt: '2026-05-12T00:00:00.000Z'
}]
});
}
if (url.endsWith('/agents/agent-old/destroy')) {
assert.equal(init?.method, 'POST');
return okJson({ ok: true });
}
if (url.endsWith('/deployments')) {
return okJson({ agentId: 'agent-new', deploymentId: 'dep-new', status: 'active' }, 201);
}
throw new Error(`unexpected URL ${url}`);
}
});
assert.equal(destroy.handle.id, 'agent-new');
assert.equal(destroy.calls.some((call) => call.init?.method === 'POST' && call.url.endsWith('/destroy')), true);
const cancel = await launch({
env: {
WORKFORCE_DEPLOY_CLOUD_URL: 'https://cloud.example.test',
WORKFORCE_DEPLOY_ON_EXISTS: 'cancel'
},
fetch(url, init) {
if (init?.method === 'GET' && url.endsWith('/deployments')) {
return okJson({
agents: [{
agentId: 'agent-old',
deployedName: 'demo',
status: 'active',
createdAt: '2026-05-13T00:00:00.000Z'
}],
nextCursor: null
});
}
throw new Error(`unexpected URL ${url}`);
}
});
assert.equal(cancel.handle.id, 'agent-old');
assert.equal(cancel.handle.status, 'cancelled');
assert.equal((await cancel.handle.done).code, 0);
// No deploy POST should fire — the listing GET is expected and not what
// this assertion is guarding against.
assert.equal(
cancel.calls.some((call) => call.init?.method === 'POST' && call.url.endsWith('/deployments')),
false
);
});
test('findExistingAgent: parses the new /deployments shape ({agentId, personaId, status})', async () => {
// Regression for the production blocker: cloud#580 changed the list
// shape from {agent:{id}} → {agents:[{agentId, personaId, status}]}.
// We must accept the new keys (agentId) and still filter out
// destroyed tombstones + persona-id mismatches.
const result = await launch({