-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathuseDeployFlow.ts
More file actions
924 lines (842 loc) · 37.3 KB
/
useDeployFlow.ts
File metadata and controls
924 lines (842 loc) · 37.3 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
import { ConfigIO } from '../../../../lib';
import type { AwsDeploymentTarget } from '../../../../schema';
import type { CdkToolkitWrapper, DeployMessage, SwitchableIoHost } from '../../../cdk/toolkit-lib';
import {
buildDeployedState,
getStackOutputs,
parseAgentOutputs,
parseEvaluatorOutputs,
parseGatewayOutputs,
parseMemoryOutputs,
parseOnlineEvalOutputs,
parsePolicyEngineOutputs,
parsePolicyOutputs,
} from '../../../cloudformation';
import { DEFAULT_DEPLOY_ATTRS, computeDeployAttrs } from '../../../commands/deploy/utils.js';
import { getErrorMessage, isChangesetInProgressError, isExpiredTokenError } from '../../../errors';
import { ExecLogger } from '../../../logging';
import { performStackTeardown, setupTransactionSearch } from '../../../operations/deploy';
import { getGatewayTargetStatuses } from '../../../operations/deploy/gateway-status';
import { deleteOrphanedABTests, setupABTests } from '../../../operations/deploy/post-deploy-ab-tests';
import {
resolveConfigBundleComponentKeys,
setupConfigBundles,
} from '../../../operations/deploy/post-deploy-config-bundles';
import { setupHttpGateways } from '../../../operations/deploy/post-deploy-http-gateways';
import { enableOnlineEvalConfigs } from '../../../operations/deploy/post-deploy-online-evals';
import { withCommandRunTelemetry } from '../../../telemetry/cli-command-run.js';
import {
type StackDiffSummary,
type Step,
areStepsComplete,
hasStepError,
parseDiffResult,
parseStackDiff,
} from '../../components';
import { type MissingCredential, type PreflightContext, useCdkPreflight } from '../../hooks';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
type DeployPhase =
| 'idle'
| 'running'
| 'teardown-confirm'
| 'credentials-prompt'
| 'bootstrap-confirm'
| 'deploying'
| 'complete'
| 'error';
const MAX_OUTPUT_POLL_ATTEMPTS = 10;
const OUTPUT_POLL_DELAY_MS = 1500;
/** Optional pre-synthesized context from plan command */
export interface PreSynthesized {
cdkToolkitWrapper: CdkToolkitWrapper;
context: PreflightContext;
stackNames: string[];
switchableIoHost?: SwitchableIoHost;
identityKmsKeyArn?: string;
allCredentials?: Record<string, { credentialProviderArn: string; clientSecretArn?: string; callbackUrl?: string }>;
}
interface DeployFlowOptions {
/** Skip preflight and use pre-synthesized context (from plan command) */
preSynthesized?: PreSynthesized;
/** Whether running in interactive TUI mode - affects error message verbosity */
isInteractive?: boolean;
/** Run CDK diff instead of deploy */
diffMode?: boolean;
/**
* Subset of targets the user picked in the TUI target selector. When set,
* the preflight context's awsTargets is filtered to only these targets.
* See issue #1267.
*/
selectedTargets?: AwsDeploymentTarget[];
}
interface DeployFlowState {
phase: DeployPhase;
steps: Step[];
context: PreflightContext | null;
deployOutput: string | null;
deployMessages: DeployMessage[];
stackOutputs: Record<string, string>;
targetStatuses: { name: string; status: string }[];
hasError: boolean;
/** True if the error is specifically due to expired/invalid AWS credentials */
hasTokenExpiredError: boolean;
/** True if the error is due to missing AWS credentials (not configured) */
hasCredentialsError: boolean;
isComplete: boolean;
/** True if CloudFormation has started (received first resource event) */
hasStartedCfn: boolean;
logFilePath: string;
/** Missing credentials that need to be provided */
missingCredentials: MissingCredential[];
/** Parsed diff summaries per stack */
diffSummaries: StackDiffSummary[];
/** Number of stacks with changes (from overall diff result) */
numStacksWithChanges?: number;
/** Notes to display after successful deploy (e.g., transaction search info) */
deployNotes: string[];
/** Warnings from post-deploy steps (config bundles, AB tests) */
postDeployWarnings: string[];
/** True if any post-deploy sub-resource operation had errors */
postDeployHasError: boolean;
/** Whether an on-demand diff is currently running */
isDiffLoading: boolean;
/** Request an on-demand diff (lazy: runs once, caches result) */
requestDiff: () => void;
startDeploy: () => void;
confirmTeardown: () => void;
cancelTeardown: () => void;
confirmBootstrap: () => void;
skipBootstrap: () => void;
/** Reset token expired state (called after user re-authenticates) */
clearTokenExpiredError: () => void;
/** Reset credentials error state (called after user configures credentials) */
clearCredentialsError: () => void;
/** Called when user chooses to use credentials from .env.local */
useEnvLocalCredentials: () => void;
/** Called when user enters credentials manually */
useManualCredentials: (credentials: Record<string, string>) => void;
/** Called when user chooses to skip credential setup */
skipCredentials: () => void;
}
export function useDeployFlow(options: DeployFlowOptions = {}): DeployFlowState {
const { preSynthesized, isInteractive = false, diffMode = false, selectedTargets } = options;
const skipPreflight = !!preSynthesized;
// Create logger once for the entire deploy flow
const [logger] = useState(() => new ExecLogger({ command: 'deploy' }));
// Always call the hook (React rules), but we won't use it when preSynthesized is provided
const preflight = useCdkPreflight({ logger, isInteractive, selectedTargets });
// Use pre-synthesized values when provided, otherwise use preflight values
const cdkToolkitWrapper = preSynthesized?.cdkToolkitWrapper ?? preflight.cdkToolkitWrapper;
const context = preSynthesized?.context ?? preflight.context;
const stackNames = preSynthesized?.stackNames ?? preflight.stackNames;
const switchableIoHost = preSynthesized?.switchableIoHost ?? preflight.switchableIoHost;
const identityKmsKeyArn = preSynthesized?.identityKmsKeyArn ?? preflight.identityKmsKeyArn;
const allCredentials = preSynthesized?.allCredentials ?? preflight.allCredentials;
const [preDeployDiffStep, setPreDeployDiffStep] = useState<Step>({
label: 'Computing diff changes...',
status: 'pending',
});
const [publishAssetsStep, setPublishAssetsStep] = useState<Step>({ label: 'Publish assets', status: 'pending' });
const [deployStep, setDeployStep] = useState<Step>({ label: 'Deploy to AWS', status: 'pending' });
const [diffStep, setDiffStep] = useState<Step>({ label: 'Run CDK diff', status: 'pending' });
const [diffSummaries, setDiffSummaries] = useState<StackDiffSummary[]>([]);
const [numStacksWithChanges, setNumStacksWithChanges] = useState<number | undefined>();
const [isDiffLoading, setIsDiffLoading] = useState(false);
const [deployNotes, setDeployNotes] = useState<string[]>([]);
const [postDeployWarnings, setPostDeployWarnings] = useState<string[]>([]);
const [postDeployHasError, setPostDeployHasError] = useState(false);
const isDiffRunningRef = useRef(false);
const [deployOutput, setDeployOutput] = useState<string | null>(null);
const [deployMessages, setDeployMessages] = useState<DeployMessage[]>([]);
const [stackOutputs, setStackOutputs] = useState<Record<string, string>>({});
const [targetStatuses, setTargetStatuses] = useState<{ name: string; status: string }[]>([]);
const [shouldStartDeploy, setShouldStartDeploy] = useState(false);
const [hasTokenExpiredError, setHasTokenExpiredError] = useState(false);
// Track if CloudFormation has started (received first resource event)
const [hasStartedCfn, setHasStartedCfn] = useState(false);
// Ref version for use in callbacks (avoids stale closure issues)
const hasReceivedCfnEvent = useRef(false);
// Ref to capture outputs from I5900 stream message (for immediate access in persistDeployedState)
const streamOutputsRef = useRef<Record<string, string> | null>(null);
const startDeploy = useCallback(() => {
setPreDeployDiffStep({ label: 'Computing diff changes...', status: 'pending' });
setPublishAssetsStep({ label: 'Publish assets', status: 'pending' });
setDeployStep({ label: 'Deploy to AWS', status: 'pending' });
setDeployOutput(null);
setHasTokenExpiredError(false); // Reset token expired state when retrying
setHasStartedCfn(false);
hasReceivedCfnEvent.current = false;
if (skipPreflight) {
setShouldStartDeploy(true);
} else {
void preflight.startPreflight();
}
}, [preflight, skipPreflight]);
/** Run diff on-demand (lazy: runs once, caches result). Safe to call anytime after synth. */
const requestDiff = useCallback(() => {
if (diffSummaries.length > 0 || isDiffRunningRef.current) return;
if (!cdkToolkitWrapper) return;
isDiffRunningRef.current = true;
setIsDiffLoading(true);
const run = async () => {
switchableIoHost?.setOnRawMessage((code, _level, message, data) => {
logger.logDiff(code, message);
if (code === 'CDK_TOOLKIT_I4002') {
setDiffSummaries(prev => [...prev, parseStackDiff(data, message)]);
} else if (code === 'CDK_TOOLKIT_I4001') {
setNumStacksWithChanges(parseDiffResult(data).numStacksWithChanges);
}
});
switchableIoHost?.setVerbose(true);
try {
await cdkToolkitWrapper.diff();
} catch {
setDiffSummaries([{ stackName: 'Error', sections: [], hasSecurityChanges: false, totalChanges: 0 }]);
} finally {
switchableIoHost?.setVerbose(false);
switchableIoHost?.setOnRawMessage(null);
isDiffRunningRef.current = false;
setIsDiffLoading(false);
}
};
void run();
}, [cdkToolkitWrapper, diffSummaries.length, switchableIoHost, logger]);
/**
* Persist deployed state after successful deployment.
* Uses outputs from CDK stream (I5900) if available, falls back to DescribeStacks API.
*/
const persistDeployedState = useCallback(async () => {
const ctx = context;
const currentStackName = stackNames[0];
const target = ctx?.awsTargets[0];
if (!ctx || !currentStackName || !target) return;
const configIO = new ConfigIO();
const agentNames = ctx.projectSpec.runtimes?.map((a: { name: string }) => a.name) || [];
// CDK stream (I5900) only includes outputs without exportName.
// Per-resource outputs (memory, agent, gateway) use exportName, so we
// always need DescribeStacks for the full set. Merge stream outputs as a base.
let outputs = { ...(streamOutputsRef.current ?? {}) };
for (let attempt = 1; attempt <= MAX_OUTPUT_POLL_ATTEMPTS; attempt += 1) {
logger.log(`Polling stack outputs (attempt ${attempt}/${MAX_OUTPUT_POLL_ATTEMPTS})...`);
const apiOutputs = await getStackOutputs(target.region, currentStackName);
if (Object.keys(apiOutputs).length > 0) {
outputs = { ...outputs, ...apiOutputs };
logger.log(`Retrieved ${Object.keys(apiOutputs).length} output(s) from stack`);
break;
}
if (attempt < MAX_OUTPUT_POLL_ATTEMPTS) {
logger.log(`No outputs yet, retrying in ${OUTPUT_POLL_DELAY_MS / 1000}s...`);
await new Promise(resolve => setTimeout(resolve, OUTPUT_POLL_DELAY_MS));
}
}
if (Object.keys(outputs).length === 0) {
throw new Error('Could not retrieve stack outputs after polling. Deployed state will not be recorded.');
}
const agents = parseAgentOutputs(outputs, agentNames, currentStackName);
if (Object.keys(agents).length !== agentNames.length) {
logger.log(
`Deployed-state missing outputs for ${agentNames.length - Object.keys(agents).length} agent(s).`,
'warn'
);
}
// Parse gateway outputs from CDK stack
let gateways: Record<string, { gatewayId: string; gatewayArn: string }> = {};
try {
const projectForGateways = await configIO.readProjectSpec();
const gatewaySpecs =
projectForGateways.agentCoreGateways?.reduce(
(acc: Record<string, unknown>, gateway: { name: string }) => {
acc[gateway.name] = gateway;
return acc;
},
{} as Record<string, unknown>
) ?? {};
gateways = parseGatewayOutputs(outputs, gatewaySpecs);
} catch (error) {
logger.log(`Failed to read gateway configuration: ${getErrorMessage(error)}`, 'warn');
}
// Parse memory outputs
const memoryNames = (ctx.projectSpec.memories ?? []).map((m: { name: string }) => m.name);
const memories = parseMemoryOutputs(outputs, memoryNames);
if (memoryNames.length > 0 && Object.keys(memories).length !== memoryNames.length) {
logger.log(
`Deployed-state missing outputs for ${memoryNames.length - Object.keys(memories).length} memory(ies).`,
'warn'
);
}
// Parse evaluator outputs
const evaluatorNames = (ctx.projectSpec.evaluators ?? []).map((e: { name: string }) => e.name);
const evaluators = parseEvaluatorOutputs(outputs, evaluatorNames);
// Parse online eval config outputs
const onlineEvalSpecs = (ctx.projectSpec.onlineEvalConfigs ?? []).map(
(c: { name: string; agent?: string; endpoint?: string }) => ({
name: c.name,
agent: c.agent,
endpoint: c.endpoint,
})
);
const onlineEvalConfigs = parseOnlineEvalOutputs(outputs, onlineEvalSpecs);
// Parse policy engine outputs
const policyEngineSpecs = ctx.projectSpec.policyEngines ?? [];
const policyEngineNames = policyEngineSpecs.map((pe: { name: string }) => pe.name);
const policyEngines = parsePolicyEngineOutputs(outputs, policyEngineNames);
// Parse policy outputs
const policySpecs = policyEngineSpecs.flatMap((pe: { name: string; policies: { name: string }[] }) =>
pe.policies.map(p => ({ engineName: pe.name, policyName: p.name }))
);
const policies = parsePolicyOutputs(outputs, policySpecs);
// Expose outputs to UI
setStackOutputs(outputs);
const existingState = await configIO.readDeployedState().catch(() => undefined);
let deployedState = buildDeployedState({
targetName: target.name,
stackName: currentStackName,
agents,
gateways,
existingState,
identityKmsKeyArn,
memories,
evaluators,
onlineEvalConfigs,
credentials: Object.keys(allCredentials).length > 0 ? allCredentials : undefined,
policyEngines,
policies,
});
await configIO.writeDeployedState(deployedState);
// Post-deploy: Enable online eval configs that have enableOnCreate (CFN deploys them as DISABLED).
// Only enable configs that are newly deployed — skip configs that already existed before this
// deploy run, so we don't re-enable configs a customer intentionally disabled.
const onlineEvalFullSpecs = ctx.projectSpec.onlineEvalConfigs ?? [];
const deployedOnlineEvalConfigs = deployedState.targets?.[target.name]?.resources?.onlineEvalConfigs ?? {};
const previouslyDeployedOnlineEvals = existingState?.targets?.[target.name]?.resources?.onlineEvalConfigs ?? {};
const newOnlineEvalFullSpecs = onlineEvalFullSpecs.filter(c => !previouslyDeployedOnlineEvals[c.name]);
if (newOnlineEvalFullSpecs.length > 0 && Object.keys(deployedOnlineEvalConfigs).length > 0) {
try {
const enableResult = await enableOnlineEvalConfigs({
region: target.region,
onlineEvalConfigs: newOnlineEvalFullSpecs,
deployedOnlineEvalConfigs,
});
if (enableResult.hasErrors) {
const errors = enableResult.results.filter(r => r.status === 'error');
for (const err of errors) {
logger.log(`Online eval enable "${err.configName}" error: ${err.error}`, 'warn');
}
setPostDeployHasError(true);
setPostDeployWarnings(prev => [
...prev,
...errors.map(err => `Online eval "${err.configName}": ${err.error}`),
]);
}
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
logger.log(`Online eval enable failed: ${message}`, 'warn');
setPostDeployHasError(true);
setPostDeployWarnings(prev => [...prev, `Online eval enable failed: ${message}`]);
}
}
// Post-deploy: Create/update configuration bundles
const configBundleSpecs = ctx.projectSpec.configBundles ?? [];
if (configBundleSpecs.length > 0) {
try {
// Resolve component key placeholders (e.g., {{runtime:name}} → real ARN)
const resolvedProjectSpec = resolveConfigBundleComponentKeys(ctx.projectSpec, deployedState, target.name);
const existingConfigBundles = deployedState.targets?.[target.name]?.resources?.configBundles;
const configBundleResult = await setupConfigBundles({
region: target.region,
projectSpec: resolvedProjectSpec,
existingBundles: existingConfigBundles,
});
// Merge config bundle state into deployed state
if (Object.keys(configBundleResult.configBundles).length > 0) {
const updatedState = await configIO.readDeployedState().catch(() => deployedState);
const targetResources = updatedState.targets[target.name]?.resources;
if (targetResources) {
targetResources.configBundles = configBundleResult.configBundles;
await configIO.writeDeployedState(updatedState);
}
}
if (configBundleResult.hasErrors) {
const errors = configBundleResult.results.filter(r => r.status === 'error');
for (const err of errors) {
logger.log(`Config bundle "${err.bundleName}" setup error: ${err.error}`, 'warn');
}
setPostDeployHasError(true);
setPostDeployWarnings(prev => [
...prev,
...errors.map(err => `Config bundle "${err.bundleName}": ${err.error}`),
]);
}
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
logger.log(`Config bundle setup failed: ${message}`, 'warn');
setPostDeployHasError(true);
setPostDeployWarnings(prev => [...prev, `Config bundle setup failed: ${message}`]);
}
}
// Pre-gateway: Delete orphaned AB tests so their gateway rules are cleaned up
// before we attempt to delete orphaned HTTP gateways.
const existingABTests = deployedState.targets?.[target.name]?.resources?.abTests;
if (existingABTests && Object.keys(existingABTests).length > 0) {
try {
const deleteResult = await deleteOrphanedABTests({
region: target.region,
projectSpec: ctx.projectSpec,
existingABTests,
});
if (deleteResult.hasErrors) {
const errors = deleteResult.results.filter(r => r.status === 'error');
for (const err of errors) {
logger.log(`AB test delete "${err.testName}" error: ${err.error}`, 'warn');
}
setPostDeployHasError(true);
setPostDeployWarnings(prev => [...prev, ...errors.map(err => `AB test "${err.testName}": ${err.error}`)]);
}
// Surface warnings (e.g., "AB test was stopped before deletion")
for (const r of deleteResult.results) {
if (r.warning) {
logger.log(r.warning, 'warn');
setPostDeployWarnings(prev => [...prev, r.warning!]);
}
}
// Update deployed state to remove deleted AB tests
if (deleteResult.results.some(r => r.status === 'deleted')) {
const updatedState = await configIO.readDeployedState().catch(() => deployedState);
const targetResources = updatedState.targets[target.name]?.resources;
if (targetResources?.abTests) {
for (const r of deleteResult.results) {
if (r.status === 'deleted') delete targetResources.abTests[r.testName];
}
await configIO.writeDeployedState(updatedState);
deployedState = updatedState;
}
}
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
logger.log(`AB test orphan cleanup failed: ${message}`, 'warn');
setPostDeployHasError(true);
setPostDeployWarnings(prev => [...prev, `AB test orphan cleanup failed: ${message}`]);
}
}
// Post-deploy: Create/update HTTP gateways
const httpGatewaySpecs = ctx.projectSpec.httpGateways ?? [];
const existingHttpGateways = deployedState.targets?.[target.name]?.resources?.httpGateways;
if (httpGatewaySpecs.length > 0 || Object.keys(existingHttpGateways ?? {}).length > 0) {
try {
const deployedResources = deployedState.targets?.[target.name]?.resources;
const httpGatewayResult = await setupHttpGateways({
region: target.region,
projectName: ctx.projectSpec.name,
projectSpec: ctx.projectSpec,
existingHttpGateways,
deployedResources,
});
// Always merge HTTP gateway state (even if empty, to clear deleted gateways)
const updatedState = await configIO.readDeployedState().catch(() => deployedState);
const targetResources = updatedState.targets[target.name]?.resources;
if (targetResources) {
targetResources.httpGateways = httpGatewayResult.httpGateways;
await configIO.writeDeployedState(updatedState);
deployedState = updatedState;
}
if (httpGatewayResult.hasErrors) {
const errors = httpGatewayResult.results.filter(r => r.status === 'error');
for (const err of errors) {
logger.log(`HTTP gateway "${err.gatewayName}" setup error: ${err.error}`, 'warn');
}
setPostDeployHasError(true);
setPostDeployWarnings(prev => [
...prev,
...errors.map(err => `HTTP gateway "${err.gatewayName}": ${err.error}`),
]);
}
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
logger.log(`HTTP gateway setup failed: ${message}`, 'warn');
setPostDeployHasError(true);
setPostDeployWarnings(prev => [...prev, `HTTP gateway setup failed: ${message}`]);
}
}
// Post-deploy: Create/update AB tests
const abTestSpecs = ctx.projectSpec.abTests ?? [];
if (abTestSpecs.length > 0) {
try {
const existingABTests = deployedState.targets?.[target.name]?.resources?.abTests;
const deployedResources = deployedState.targets?.[target.name]?.resources;
const abTestResult = await setupABTests({
region: target.region,
projectSpec: ctx.projectSpec,
existingABTests,
deployedResources,
});
if (Object.keys(abTestResult.abTests).length > 0) {
const updatedState = await configIO.readDeployedState().catch(() => deployedState);
const targetResources = updatedState.targets[target.name]?.resources;
if (targetResources) {
targetResources.abTests = abTestResult.abTests;
await configIO.writeDeployedState(updatedState);
}
}
if (abTestResult.hasErrors) {
const errors = abTestResult.results.filter(r => r.status === 'error');
for (const err of errors) {
logger.log(`AB test "${err.testName}" setup error: ${err.error}`, 'warn');
}
setPostDeployHasError(true);
setPostDeployWarnings(prev => [...prev, ...errors.map(err => `AB test "${err.testName}": ${err.error}`)]);
}
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
logger.log(`AB test setup failed: ${message}`, 'warn');
setPostDeployHasError(true);
setPostDeployWarnings(prev => [...prev, `AB test setup failed: ${message}`]);
}
}
// Query gateway target sync statuses (non-blocking)
const allStatuses: { name: string; status: string }[] = [];
for (const [, gateway] of Object.entries(gateways)) {
const statuses = await getGatewayTargetStatuses(gateway.gatewayId, target.region);
allStatuses.push(...statuses);
}
if (allStatuses.length > 0) {
setTargetStatuses(allStatuses);
}
}, [context, stackNames, logger, identityKmsKeyArn, allCredentials]);
// Start deploy when preflight completes OR when shouldStartDeploy is set
useEffect(() => {
if (diffMode) return; // Diff mode uses its own effect
const shouldStart = skipPreflight ? shouldStartDeploy : preflight.phase === 'complete';
if (!shouldStart) return;
if (deployStep.status !== 'pending') return;
if (!cdkToolkitWrapper) return;
const attrs = context ? computeDeployAttrs(context.projectSpec, 'deploy') : { ...DEFAULT_DEPLOY_ATTRS };
const run = async (): Promise<{ success: true } | { success: false; error: Error }> => {
// Run diff before deploy to capture pre-deploy differences
if (!isDiffRunningRef.current) {
isDiffRunningRef.current = true;
setIsDiffLoading(true);
setPreDeployDiffStep(prev => ({ ...prev, status: 'running' }));
logger.startStep('Computing diff changes...');
switchableIoHost?.setOnRawMessage((code, _level, message, data) => {
logger.logDiff(code, message);
if (code === 'CDK_TOOLKIT_I4002') {
setDiffSummaries(prev => [...prev, parseStackDiff(data, message)]);
} else if (code === 'CDK_TOOLKIT_I4001') {
setNumStacksWithChanges(parseDiffResult(data).numStacksWithChanges);
}
});
switchableIoHost?.setVerbose(true);
try {
await cdkToolkitWrapper.diff();
} catch {
// Diff failure is non-fatal — deploy will proceed
} finally {
switchableIoHost?.setVerbose(false);
switchableIoHost?.setOnRawMessage(null);
isDiffRunningRef.current = false;
setIsDiffLoading(false);
logger.endStep('success');
setPreDeployDiffStep(prev => ({ ...prev, status: 'success' }));
}
}
setPublishAssetsStep(prev => ({ ...prev, status: 'running' }));
setShouldStartDeploy(false);
setDeployMessages([]); // Clear previous messages
streamOutputsRef.current = null; // Clear previous stream outputs
logger.startStep('Publish assets');
// Set up raw message callback to log ALL CDK output
switchableIoHost?.setOnRawMessage((code, level, message) => {
logger.log(`[${level}] ${code}: ${message}`);
});
// Set up filtered message callback for TUI display
switchableIoHost?.setOnMessage(msg => {
setDeployMessages(prev => [...prev, msg]);
// When we receive the first CloudFormation event with progress, mark assets as published
if (!hasReceivedCfnEvent.current && msg.progress) {
hasReceivedCfnEvent.current = true;
setHasStartedCfn(true);
logger.endStep('success');
logger.startStep('Deploy to AWS');
setPublishAssetsStep(prev => ({ ...prev, status: 'success' }));
setDeployStep(prev => ({ ...prev, status: 'running' }));
}
// Capture outputs from I5900 for immediate use in persistDeployedState
if (msg.code === 'CDK_TOOLKIT_I5900' && msg.outputs) {
streamOutputsRef.current = msg.outputs;
}
});
// Enable verbose output for deploy - this captures CDK progress messages
switchableIoHost?.setVerbose(true);
try {
// Run deploy - toolkit-lib handles CloudFormation orchestration
// Output goes to stdout via the switchable ioHost
await cdkToolkitWrapper.deploy();
if (context?.isTeardownDeploy) {
// After deploying the empty spec, destroy the stack entirely
const targetName = context.awsTargets[0]?.name;
if (targetName) {
const teardown = await performStackTeardown(targetName);
if (!teardown.success) {
throw new Error(`Stack teardown failed: ${teardown.error.message}`);
}
}
} else {
// Deploy succeeded - persist state
try {
await persistDeployedState();
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
logger.log(`Failed to persist deployed state: ${message}`, 'warn');
}
// Post-deploy: Enable CloudWatch Transaction Search (non-blocking, silent)
const agentNames = context?.projectSpec.runtimes?.map((a: { name: string }) => a.name) ?? [];
const targetRegion = context?.awsTargets[0]?.region;
const targetAccount = context?.awsTargets[0]?.account;
const hasGateways = (context?.projectSpec.agentCoreGateways?.length ?? 0) > 0;
const hasPythonAgent =
context?.projectSpec.runtimes?.some(
(a: { entrypoint?: string }) =>
(a.entrypoint?.endsWith('.py') ?? false) || (a.entrypoint?.includes('.py:') ?? false)
) ?? false;
if ((agentNames.length > 0 || hasGateways) && hasPythonAgent && targetRegion && targetAccount) {
try {
const tsResult = await setupTransactionSearch({
region: targetRegion,
accountId: targetAccount,
agentNames,
hasGateways,
});
if (!tsResult.success) {
logger.log(`Transaction search setup warning: ${tsResult.error.message}`, 'warn');
} else {
setDeployNotes(prev => [
...prev,
'Transaction search enabled. It takes ~10 minutes for transaction search to be fully active and for traces from invocations to be indexed.',
]);
}
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
logger.log(`Transaction search setup failed: ${message}`, 'warn');
}
}
}
logger.endStep('success');
logger.finalize(true);
setDeployOutput(`Deployed ${stackNames.length} stack(s): ${stackNames.join(', ')}`);
// Mark both steps as success (in case CFn events were never received)
setPublishAssetsStep(prev => ({ ...prev, status: 'success' }));
setDeployStep(prev => ({ ...prev, status: 'success' }));
return { success: true } as const;
} catch (err) {
const errorMsg = getErrorMessage(err);
// Log additional context for changeset errors
if (isChangesetInProgressError(err)) {
logger.log('Changeset conflict detected - another deployment may be in progress', 'warn');
logger.log('The CDK wrapper will retry automatically with exponential backoff', 'info');
}
logger.endStep('error', errorMsg);
logger.finalize(false);
// Check if the error is due to expired/invalid credentials
if (isExpiredTokenError(err)) {
setHasTokenExpiredError(true);
}
// Mark the appropriate step as error based on whether CFn started
if (hasReceivedCfnEvent.current) {
setDeployStep(prev => ({
...prev,
status: 'error',
error: logger.getFailureMessage('Deploy to AWS'),
}));
} else {
setPublishAssetsStep(prev => ({
...prev,
status: 'error',
error: logger.getFailureMessage('Publish assets'),
}));
}
return { success: false, error: err instanceof Error ? err : new Error(errorMsg) } as const;
} finally {
// Disable verbose output and clear callback after deploy
switchableIoHost?.setVerbose(false);
switchableIoHost?.setOnMessage(null);
// Dispose CDK toolkit to release lock files
void cdkToolkitWrapper.dispose();
}
};
void withCommandRunTelemetry('deploy', attrs, run);
}, [
preflight.phase,
cdkToolkitWrapper,
stackNames,
deployStep.status,
logger,
skipPreflight,
shouldStartDeploy,
persistDeployedState,
switchableIoHost,
context?.isTeardownDeploy,
context?.awsTargets,
context?.projectSpec.runtimes,
diffMode,
]);
// Start diff when preflight completes (diff mode only)
useEffect(() => {
if (!diffMode) return;
const shouldStart = skipPreflight ? shouldStartDeploy : preflight.phase === 'complete';
if (!shouldStart) return;
if (diffStep.status !== 'pending') return;
if (!cdkToolkitWrapper) return;
const attrs = context
? computeDeployAttrs(context.projectSpec, 'diff')
: { ...DEFAULT_DEPLOY_ATTRS, deploy_mode: 'diff' as const };
const run = async (): Promise<{ success: true } | { success: false; error: Error }> => {
setDiffStep(prev => ({ ...prev, status: 'running' }));
setShouldStartDeploy(false);
setDiffSummaries([]);
logger.startStep('Run CDK diff');
switchableIoHost?.setOnRawMessage((code, _level, message, data) => {
logger.logDiff(code, message);
if (code === 'CDK_TOOLKIT_I4002') {
setDiffSummaries(prev => [...prev, parseStackDiff(data, message)]);
} else if (code === 'CDK_TOOLKIT_I4001') {
setNumStacksWithChanges(parseDiffResult(data).numStacksWithChanges);
}
});
switchableIoHost?.setVerbose(true);
try {
await cdkToolkitWrapper.diff();
logger.endStep('success');
logger.finalize(true);
setDiffStep(prev => ({ ...prev, status: 'success' }));
return { success: true };
} catch (err) {
const errorMsg = getErrorMessage(err);
logger.endStep('error', errorMsg);
logger.finalize(false);
if (isExpiredTokenError(err)) {
setHasTokenExpiredError(true);
}
setDiffStep(prev => ({
...prev,
status: 'error',
error: logger.getFailureMessage('Run CDK diff'),
}));
return { success: false, error: err instanceof Error ? err : new Error(errorMsg) };
} finally {
switchableIoHost?.setVerbose(false);
switchableIoHost?.setOnRawMessage(null);
void cdkToolkitWrapper.dispose();
}
};
void withCommandRunTelemetry('deploy', attrs, run);
}, [
diffMode,
preflight.phase,
cdkToolkitWrapper,
diffStep.status,
logger,
skipPreflight,
shouldStartDeploy,
switchableIoHost,
]);
// Finalize logger and dispose toolkit when preflight fails
useEffect(() => {
if (skipPreflight) return;
if (preflight.phase === 'error') {
logger.finalize(false);
void preflight.cdkToolkitWrapper?.dispose();
}
}, [preflight.phase, preflight.cdkToolkitWrapper, logger, skipPreflight]);
const steps = useMemo(() => {
if (diffMode) {
return skipPreflight ? [diffStep] : [...preflight.steps, diffStep];
}
return skipPreflight
? [preDeployDiffStep, publishAssetsStep, deployStep]
: [...preflight.steps, preDeployDiffStep, publishAssetsStep, deployStep];
}, [preflight.steps, preDeployDiffStep, publishAssetsStep, deployStep, diffStep, skipPreflight, diffMode]);
const phase: DeployPhase = useMemo(() => {
const activeStep = diffMode ? diffStep : deployStep;
if (skipPreflight) {
if (!shouldStartDeploy && activeStep.status === 'pending') {
return 'idle';
}
if (activeStep.status === 'error') {
return 'error';
}
if (activeStep.status === 'success') {
return 'complete';
}
return 'deploying';
}
if (preflight.phase === 'idle') {
return 'idle';
}
if (preflight.phase === 'error') {
return 'error';
}
if (preflight.phase === 'teardown-confirm') {
return 'teardown-confirm';
}
if (preflight.phase === 'credentials-prompt') {
return 'credentials-prompt';
}
if (preflight.phase === 'bootstrap-confirm') {
return 'bootstrap-confirm';
}
if (preflight.phase === 'running' || preflight.phase === 'bootstrapping' || preflight.phase === 'identity-setup') {
return 'running';
}
if (activeStep.status === 'error') {
return 'error';
}
if (activeStep.status === 'success') {
return 'complete';
}
return 'deploying';
}, [preflight.phase, deployStep, diffStep, skipPreflight, shouldStartDeploy, diffMode]);
const hasError = hasStepError(steps);
const isComplete = areStepsComplete(steps);
// Combine token expired errors from both preflight and deploy phases
const combinedTokenExpiredError = hasTokenExpiredError || preflight.hasTokenExpiredError;
const clearAllTokenExpiredErrors = useCallback(() => {
setHasTokenExpiredError(false);
preflight.clearTokenExpiredError();
}, [preflight]);
const clearAllCredentialsErrors = useCallback(() => {
preflight.clearCredentialsError();
}, [preflight]);
return {
phase,
steps,
context,
deployOutput,
deployMessages,
diffSummaries,
numStacksWithChanges,
deployNotes,
postDeployWarnings,
postDeployHasError,
isDiffLoading,
requestDiff,
stackOutputs,
targetStatuses,
hasError,
hasTokenExpiredError: combinedTokenExpiredError,
hasCredentialsError: preflight.hasCredentialsError,
isComplete,
hasStartedCfn,
logFilePath: logger.logFilePath,
missingCredentials: preflight.missingCredentials,
startDeploy,
confirmTeardown: preflight.confirmTeardown,
cancelTeardown: preflight.cancelTeardown,
confirmBootstrap: preflight.confirmBootstrap,
skipBootstrap: preflight.skipBootstrap,
clearTokenExpiredError: clearAllTokenExpiredErrors,
clearCredentialsError: clearAllCredentialsErrors,
useEnvLocalCredentials: preflight.useEnvLocalCredentials,
useManualCredentials: preflight.useManualCredentials,
skipCredentials: preflight.skipCredentials,
};
}