-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathUtils.js
More file actions
1363 lines (1275 loc) · 48.1 KB
/
Copy pathUtils.js
File metadata and controls
1363 lines (1275 loc) · 48.1 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
// @flow
import * as React from 'react';
import { type I18n as I18nType } from '@lingui/core';
import {
type SceneEventsOutsideEditorChanges,
type InstancesOutsideEditorChanges,
type ObjectsOutsideEditorChanges,
type ObjectGroupsOutsideEditorChanges,
} from '../MainFrame/EditorContainers/BaseEditor';
import {
getAiRequest,
getAiRequestSuggestions,
type AiRequest,
type AiRequestMessage,
type AiRequestMessageAssistantFunctionCall,
updateAiRequestMessage,
} from '../Utils/GDevelopServices/Generation';
import AuthenticatedUserContext from '../Profile/AuthenticatedUserContext';
import { processEditorFunctionCalls } from '../EditorFunctions/EditorFunctionCallRunner';
import {
type EditorCallbacks,
type EditorFunctionCallResult,
editorFunctions,
editorFunctionsWithoutProject,
} from '../EditorFunctions';
import {
getAllSubAgentFunctionCalls,
getFunctionCallNameByCallId,
getFunctionCallOutputsFromEditorFunctionCallResults,
getFunctionCallsToProcess,
getPendingSubAgentFunctionCalls,
getLastMessagesFromAiRequestOutput,
getLatestActivePlan,
} from './AiRequestUtils';
import { useEnsureExtensionInstalled } from './UseEnsureExtensionInstalled';
import { useGenerateEvents } from './UseGenerateEvents';
import { useSearchAndInstallAsset } from './UseSearchAndInstallAsset';
import { useSearchAndInstallResource } from './UseSearchAndInstallResource';
import { type ResourceManagementProps } from '../ResourcesList/ResourceSource';
import { AiRequestContext } from './AiRequestContext';
import { ObjectStoreContext } from '../AssetStore/ObjectStoreContext';
import { enumerateObjectTypes } from '../ObjectsList/EnumerateObjects';
import { delay } from '../Utils/Delay';
import { retryIfFailed } from '../Utils/RetryIfFailed';
import { makeSimplifiedProjectBuilder } from '../EditorFunctions/SimplifiedProject/SimplifiedProject';
import { prepareAiUserContent } from './PrepareAiUserContent';
import { extractGDevelopApiErrorStatusAndCode } from '../Utils/GDevelopServices/Errors';
import UnsavedChangesContext from '../MainFrame/UnsavedChangesContext';
import {
type FileMetadata,
type StorageProvider,
type SaveAsLocation,
} from '../ProjectsStorage';
import CloudStorageProvider from '../ProjectsStorage/CloudStorageProvider';
import { checkIfHasTooManyCloudProjects } from '../MainFrame/EditorContainers/HomePage/CreateSection/MaxProjectCountAlertMessage';
const gd: libGDevelop = global.gd;
// How long to keep the "Calculating..." indicator visible after a refresh
// completes, to prevent it from flashing on fast calls.
const REFRESH_LIMITS_SETTLE_DELAY_MS = 200;
/**
* Wraps `onRefreshLimits` with a loading state and a short settle delay so
* the "Calculating..." indicator doesn't flash on fast network calls.
*/
export const useRefreshLimits = (
onRefreshLimits: () => Promise<void>
): {|
isRefreshingLimits: boolean,
refreshLimits: (options?: {| withRetry?: boolean |}) => Promise<void>,
|} => {
const [isRefreshingLimits, setIsRefreshingLimits] = React.useState(false);
const refreshLimits = React.useCallback(
async (options?: {| withRetry?: boolean |}) => {
setIsRefreshingLimits(true);
try {
await retryIfFailed(
{ times: options && options.withRetry ? 2 : 1 },
onRefreshLimits
);
} catch (error) {
// Ignore limits refresh error.
}
await delay(REFRESH_LIMITS_SETTLE_DELAY_MS);
setIsRefreshingLimits(false);
},
[onRefreshLimits]
);
return { isRefreshingLimits, refreshLimits };
};
// All requests are made in orchestrator mode, and sub-agents (explorer, edit)
// are created server-side with the same tools version as the orchestrator.
export const AI_ORCHESTRATOR_TOOLS_VERSION = 'v5';
/**
* A pending request for the user to approve (or refuse) a project-modifying
* edit, surfaced inline in the chat when auto-edit is off.
*/
export type EditApprovalRequest = {|
// The AI request whose calls are gated (the orchestrator itself, or one of
// its edit sub-agents).
aiRequestId: string,
// The project-modifying call ids waiting for approval.
callIds: Array<string>,
// A short label pointing at what is about to run: the name of the edit agent
// (when the call is inside a sub-agent) or the tool itself (for a direct
// modifying call). Rendered the same way it appears in the chat.
label: React.Node,
|};
/**
* Whether a function call, if run, would modify the project. This is the
* signal used to gate edits behind a user confirmation when auto-edit is off.
*/
const doesFunctionCallModifyProject = (
functionCall: AiRequestMessageAssistantFunctionCall
): boolean => {
const editorFunctionDef =
editorFunctions[functionCall.name] ||
editorFunctionsWithoutProject[functionCall.name] ||
null;
return !!(editorFunctionDef && editorFunctionDef.modifiesProject);
};
/**
* Render a single function call to the same short label shown for it in the
* chat (via the editor function's renderForEditor). Falls back to the raw
* function name when the call can't be rendered.
*/
const renderFunctionCallLabel = ({
functionCall,
project,
editorCallbacks,
}: {|
functionCall: AiRequestMessageAssistantFunctionCall,
project: ?gdProject,
editorCallbacks: EditorCallbacks,
|}): React.Node => {
const editorFunction =
editorFunctions[functionCall.name] ||
editorFunctionsWithoutProject[functionCall.name] ||
null;
if (!editorFunction || !editorFunction.renderForEditor) {
return functionCall.name;
}
try {
const result = editorFunction.renderForEditor({
project,
args: JSON.parse(functionCall.arguments),
editorCallbacks,
shouldShowDetails: false,
editorFunctionCallResultOutput: null,
});
return result.text || functionCall.name;
} catch (error) {
return functionCall.name;
}
};
/**
* Build the short label shown in the confirmation prompt when auto-edit is off,
* pointing at what is about to run rather than describing the whole change.
*
* For an edit agent (a sub-agent, identified by its parentAiRequestId), we show
* the agent's name — the label of the call that launched it in the parent
* request (its short_title), the same name shown for the agent in the chat.
* For a direct modifying call (e.g. generate_events on the orchestrator), we
* show the tool's own label(s).
*/
const getEditApprovalLabel = ({
aiRequest,
modifyingFunctionCalls,
aiRequests,
project,
editorCallbacks,
}: {|
aiRequest: AiRequest,
modifyingFunctionCalls: Array<AiRequestMessageAssistantFunctionCall>,
aiRequests: { [string]: AiRequest },
project: ?gdProject,
editorCallbacks: EditorCallbacks,
|}): React.Node => {
if (aiRequest.parentAiRequestId) {
const parentRequest = aiRequests[aiRequest.parentAiRequestId] || null;
const launchingCall = parentRequest
? getAllSubAgentFunctionCalls({ aiRequest: parentRequest }).find(
functionCall => functionCall.subAgentAiRequestId === aiRequest.id
)
: null;
if (launchingCall) {
return renderFunctionCallLabel({
functionCall: launchingCall,
project,
editorCallbacks,
});
}
}
return modifyingFunctionCalls.map((functionCall, index) => (
<React.Fragment key={functionCall.call_id}>
{index > 0 ? ', ' : null}
{renderFunctionCallLabel({ functionCall, project, editorCallbacks })}
</React.Fragment>
));
};
export const useProcessFunctionCalls = ({
i18n,
project,
resourceManagementProps,
editorCallbacks,
aiRequestsToProcess,
onSendEditorFunctionCallResults,
getEditorFunctionCallResults,
addEditorFunctionCallResults,
onSceneEventsModifiedOutsideEditor,
onInstancesModifiedOutsideEditor,
onObjectsModifiedOutsideEditor,
onObjectGroupsModifiedOutsideEditor,
onWillInstallExtension,
onExtensionInstalled,
isReadyToProcessFunctionCalls,
getIsAutoEditEnabled,
suspendAiRequest,
requestEditApproval,
}: {|
i18n: I18nType,
project: ?gdProject,
resourceManagementProps: ResourceManagementProps,
editorCallbacks: EditorCallbacks,
aiRequestsToProcess: Array<AiRequest>,
onSendEditorFunctionCallResults: (
aiRequestId: string,
editorFunctionCallResults: Array<EditorFunctionCallResult>,
options: {|
createdSceneNames?: Array<string>,
createdProject?: ?gdProject,
|}
) => Promise<void>,
getEditorFunctionCallResults: string => Array<EditorFunctionCallResult> | null,
addEditorFunctionCallResults: (
string,
Array<EditorFunctionCallResult>
) => Array<EditorFunctionCallResult>,
onSceneEventsModifiedOutsideEditor: (
changes: SceneEventsOutsideEditorChanges
) => void,
onInstancesModifiedOutsideEditor: (
changes: InstancesOutsideEditorChanges
) => void,
onObjectsModifiedOutsideEditor: (
changes: ObjectsOutsideEditorChanges
) => void,
onObjectGroupsModifiedOutsideEditor: (
changes: ObjectGroupsOutsideEditorChanges
) => void,
onWillInstallExtension: (extensionNames: Array<string>) => void,
onExtensionInstalled: (extensionNames: Array<string>) => void,
isReadyToProcessFunctionCalls: boolean,
getIsAutoEditEnabled: () => boolean,
suspendAiRequest: (aiRequestId: string) => Promise<void>,
requestEditApproval: (request: EditApprovalRequest) => Promise<boolean>,
|}): {
onProcessFunctionCalls: (
aiRequest: AiRequest,
functionCalls: Array<AiRequestMessageAssistantFunctionCall>
) => Promise<void>,
clearApprovedEditBatches: () => void,
} => {
const { ensureExtensionInstalled } = useEnsureExtensionInstalled({
project,
i18n,
});
const { searchAndInstallAsset } = useSearchAndInstallAsset({
project,
resourceManagementProps,
onWillInstallExtension,
onExtensionInstalled,
});
const { searchAndInstallResources } = useSearchAndInstallResource({
project,
resourceManagementProps,
});
const { generateEvents } = useGenerateEvents({ project });
const { translatedObjectShortHeadersByType, fetchObjects } = React.useContext(
ObjectStoreContext
);
// Latest map of all AI requests, kept in a ref so the (heavily-memoized)
// onProcessFunctionCalls callback can look up a sub-agent's parent at edit
// approval time without taking a dependency on the frequently-changing map.
const { aiRequestStorage } = React.useContext(AiRequestContext);
const aiRequestsRef = React.useRef(aiRequestStorage.aiRequests);
aiRequestsRef.current = aiRequestStorage.aiRequests;
React.useEffect(
() => {
fetchObjects();
},
[fetchObjects]
);
const getAssetStoreTagForNewObject = React.useCallback(
(objectType: string): string | null => {
// Prefer the installed object metadata (same source as the
// "New object" dialog in the editor).
const installedObjectMetadata = project
? enumerateObjectTypes(project, null).find(
enumeratedObjectMetadata =>
enumeratedObjectMetadata.type === objectType
)
: null;
if (installedObjectMetadata && installedObjectMetadata.assetStoreTag) {
return installedObjectMetadata.assetStoreTag;
}
const header = translatedObjectShortHeadersByType[objectType];
return (header && header.assetStoreTag) || null;
},
[project, translatedObjectShortHeadersByType]
);
// In-memory guard against duplicate processing of the same function call.
//
// The main protection is marking calls as "working" in the ref-backed
// results store (see useEditorFunctionCallResultsStorage). However,
// React 18 can re-run an effect before a forceUpdate() re-render has
// propagated (e.g. StrictMode double-invocations in development, or a
// polling update that recreates onProcessFunctionCalls while the previous
// invocation is still awaiting).
// This Set acts as an immediate, synchronous lock keyed by
// "<requestId>:<callId>" so a call that is already being processed is
// never started a second time.
const inFlightFunctionCallIdsRef = React.useRef<Set<string>>(new Set());
// When auto-edit is off, the user approves edits one batch at a time. Once a
// batch is approved we remember it here so the rest of that edit agent's
// tools (and any later modifying rounds) run without asking again.
// Keys are `req:<aiRequestId>` (for a whole edit agent) or
// `call:<callId>` (for a single direct modifying call like generate_events).
const approvedEditBatchKeysRef = React.useRef<Set<string>>(new Set());
// Forget all previously-granted edit approvals so the next modifying call
// asks again. Called when the user toggles auto-edit: turning it on then off
// again means they want to review the upcoming edits, even within a sub-agent
// whose batch was already approved.
const clearApprovedEditBatches = React.useCallback(() => {
approvedEditBatchKeysRef.current.clear();
}, []);
const onProcessFunctionCalls = React.useCallback(
async (
aiRequest: AiRequest,
functionCalls: Array<AiRequestMessageAssistantFunctionCall>
) => {
if (!isReadyToProcessFunctionCalls) return;
if (aiRequest.status === 'suspended') return;
const functionCallsToProcess = functionCalls.filter(
functionCall =>
!inFlightFunctionCallIdsRef.current.has(
`${aiRequest.id}:${functionCall.call_id}`
)
);
if (functionCallsToProcess.length === 0) {
console.info(
'All function calls are already being processed (in-flight guard), skipping.'
);
return;
}
// Lock these call IDs so concurrent invocations skip them.
functionCallsToProcess.forEach(functionCall => {
inFlightFunctionCallIdsRef.current.add(
`${aiRequest.id}:${functionCall.call_id}`
);
});
// Gate project-modifying calls behind a user confirmation when auto-edit
// is off. Read-only calls (exploration, inspection) always run. The first
// time an edit agent (or a direct modifying call) is about to change the
// project, ask the user; once approved, the rest of that batch runs
// without asking again. On refusal, suspend the request so the user can
// explain what to do differently.
//
// This must happen after the in-flight lock above and before the calls
// are marked "working": on refusal we intentionally keep the lock held
// (we never reach the `finally` that releases it) so the now-suspended
// calls are not re-processed before the suspension propagates.
if (!getIsAutoEditEnabled()) {
const batchKey = aiRequest.parentAiRequestId
? `req:${aiRequest.id}`
: null;
const isCallApproved = (
functionCall: AiRequestMessageAssistantFunctionCall
) =>
(!!batchKey && approvedEditBatchKeysRef.current.has(batchKey)) ||
approvedEditBatchKeysRef.current.has(`call:${functionCall.call_id}`);
const modifyingFunctionCalls = functionCallsToProcess.filter(
functionCall =>
doesFunctionCallModifyProject(functionCall) &&
!isCallApproved(functionCall)
);
if (modifyingFunctionCalls.length > 0) {
const label = getEditApprovalLabel({
aiRequest,
modifyingFunctionCalls,
aiRequests: aiRequestsRef.current,
project,
editorCallbacks,
});
// Ask the user inline, in the chat (see EditApprovalRow). The promise
// resolves when they click Apply/Cancel. The in-flight lock stays held
// while we wait, so the same calls are not re-processed meanwhile.
const accepted = await requestEditApproval({
aiRequestId: aiRequest.id,
callIds: modifyingFunctionCalls.map(
functionCall => functionCall.call_id
),
label,
});
if (!accepted) {
// Refused: suspend the request (the parent orchestrator if this is
// an edit agent) so the whole flow pauses and the user can redirect.
// Keep the in-flight lock held so these calls are not re-processed.
const requestToSuspendId =
aiRequest.parentAiRequestId || aiRequest.id;
try {
await suspendAiRequest(requestToSuspendId);
} catch (error) {
console.error(
'Error while suspending AI request after a refused edit:',
error
);
}
return;
}
// Approved: remember the approval for the whole batch so subsequent
// modifying calls from the same edit agent run without asking again.
// Avoid unbounded growth across a long session.
if (approvedEditBatchKeysRef.current.size > 500) {
approvedEditBatchKeysRef.current.clear();
}
if (batchKey) {
approvedEditBatchKeysRef.current.add(batchKey);
} else {
modifyingFunctionCalls.forEach(functionCall =>
approvedEditBatchKeysRef.current.add(
`call:${functionCall.call_id}`
)
);
}
}
}
addEditorFunctionCallResults(
aiRequest.id,
functionCallsToProcess.map(functionCall => ({
status: 'working',
call_id: functionCall.call_id,
}))
);
// The "modified outside editor" callbacks each refresh the editor and can
// trigger an in-game editor hot reload. Firing them once per function
// call would, for a batch of modifying calls (e.g. a sub-agent adding 20
// objects), hot reload the editor 20 times. Instead, accumulate the
// changes per scene while the batch is processed, then flush a single
// coalesced notification per change type once it is done.
const accumulatedSceneEventsChanges: Map<
gdLayout,
Set<string>
> = new Map();
const accumulatedInstancesScenes: Set<gdLayout> = new Set();
const accumulatedObjectsChanges: Map<gdLayout, boolean> = new Map();
const accumulatedObjectGroupsScenes: Set<gdLayout> = new Set();
const flushAccumulatedOutsideEditorChanges = () => {
accumulatedSceneEventsChanges.forEach((eventIds, scene) =>
onSceneEventsModifiedOutsideEditor({
scene,
newOrChangedAiGeneratedEventIds: eventIds,
})
);
accumulatedInstancesScenes.forEach(scene =>
onInstancesModifiedOutsideEditor({ scene })
);
accumulatedObjectsChanges.forEach((isNewObjectTypeUsed, scene) =>
onObjectsModifiedOutsideEditor({ scene, isNewObjectTypeUsed })
);
accumulatedObjectGroupsScenes.forEach(scene =>
onObjectGroupsModifiedOutsideEditor({ scene })
);
};
try {
const {
results,
createdSceneNames,
createdProject,
} = await processEditorFunctionCalls({
project,
editorCallbacks,
// $FlowFixMe[incompatible-type]
toolOptions: aiRequest.toolOptions || null,
i18n,
functionCalls: functionCallsToProcess.map(functionCall => ({
name: functionCall.name,
arguments: functionCall.arguments,
call_id: functionCall.call_id,
})),
relatedAiRequestId: aiRequest.id,
getRelatedAiRequestLastMessages: () =>
getLastMessagesFromAiRequestOutput(aiRequest.output || []),
generateEvents,
onSceneEventsModifiedOutsideEditor: changes => {
const existingEventIds = accumulatedSceneEventsChanges.get(
changes.scene
);
if (existingEventIds) {
changes.newOrChangedAiGeneratedEventIds.forEach(eventId =>
existingEventIds.add(eventId)
);
} else {
accumulatedSceneEventsChanges.set(
changes.scene,
new Set(changes.newOrChangedAiGeneratedEventIds)
);
}
},
onInstancesModifiedOutsideEditor: changes => {
accumulatedInstancesScenes.add(changes.scene);
},
onObjectsModifiedOutsideEditor: changes => {
accumulatedObjectsChanges.set(
changes.scene,
accumulatedObjectsChanges.get(changes.scene) ||
false ||
changes.isNewObjectTypeUsed
);
},
onObjectGroupsModifiedOutsideEditor: changes => {
accumulatedObjectGroupsScenes.add(changes.scene);
},
ensureExtensionInstalled,
onWillInstallExtension,
onExtensionInstalled,
searchAndInstallAsset,
searchAndInstallResources,
getAssetStoreTagForNewObject,
});
// If the request was suspended while we were processing, discard the
// results — we don't want to re-populate the cleared results or send
// anything to a suspended request.
if (results.some(r => r.status === 'aborted')) {
console.info(
'Some function call results were aborted (request was likely suspended during processing), discarding all results.'
);
return;
}
const newResults = addEditorFunctionCallResults(aiRequest.id, results);
await onSendEditorFunctionCallResults(aiRequest.id, newResults, {
createdSceneNames,
createdProject,
});
} finally {
// Flush the coalesced editor notifications for everything modified in
// this batch (one hot reload instead of one per call). In `finally` so
// the editor is still refreshed for whatever was modified even if the
// batch was aborted or threw, matching the previous inline behavior.
flushAccumulatedOutsideEditorChanges();
// Release the lock so these calls can be retried if needed
// (e.g. after an error or a suspension).
functionCallsToProcess.forEach(functionCall => {
inFlightFunctionCallIdsRef.current.delete(
`${aiRequest.id}:${functionCall.call_id}`
);
});
}
},
[
i18n,
isReadyToProcessFunctionCalls,
addEditorFunctionCallResults,
project,
editorCallbacks,
onSceneEventsModifiedOutsideEditor,
onInstancesModifiedOutsideEditor,
onObjectsModifiedOutsideEditor,
onObjectGroupsModifiedOutsideEditor,
ensureExtensionInstalled,
onWillInstallExtension,
onExtensionInstalled,
searchAndInstallAsset,
searchAndInstallResources,
getAssetStoreTagForNewObject,
generateEvents,
onSendEditorFunctionCallResults,
getIsAutoEditEnabled,
suspendAiRequest,
requestEditApproval,
]
);
// Collect all function calls to process across all active AI requests.
const allFunctionCallsToProcess: Array<{|
aiRequest: AiRequest,
functionCalls: Array<AiRequestMessageAssistantFunctionCall>,
|}> = React.useMemo(
() => {
const result = [];
for (const aiRequest of aiRequestsToProcess) {
const functionCalls = getFunctionCallsToProcess({
aiRequest,
editorFunctionCallResults: getEditorFunctionCallResults(aiRequest.id),
});
if (functionCalls.length > 0) {
result.push({ aiRequest, functionCalls });
}
}
return result;
},
[aiRequestsToProcess, getEditorFunctionCallResults]
);
React.useEffect(
() => {
if (allFunctionCallsToProcess.length === 0) return;
(async () => {
for (const { aiRequest, functionCalls } of allFunctionCallsToProcess) {
if (aiRequest.status === 'suspended') continue;
console.info(
`Automatically processing AI function calls for request ${
aiRequest.id
}...`
);
await onProcessFunctionCalls(aiRequest, functionCalls);
}
})();
},
[onProcessFunctionCalls, allFunctionCallsToProcess]
);
return {
onProcessFunctionCalls,
clearApprovedEditBatches,
};
};
/**
* Detects sub-agent function calls in the selected AI request and activates
* them so that AiRequestContext starts polling and processing them.
*/
export const useActivatePendingSubAgents = ({
selectedAiRequest,
}: {|
selectedAiRequest: ?AiRequest,
|}) => {
const { activateSubAgent } = React.useContext(AiRequestContext);
React.useEffect(
() => {
if (!selectedAiRequest) return;
const subAgentCalls = getPendingSubAgentFunctionCalls({
aiRequest: selectedAiRequest,
});
subAgentCalls.forEach(call => {
if (call.subAgentAiRequestId) {
activateSubAgent(
call.subAgentAiRequestId,
selectedAiRequest.id,
call.call_id
);
}
});
},
[selectedAiRequest, activateSubAgent]
);
};
/**
* For every sub-agent function call in the selected AI request, ensures that
* its AiRequest is loaded into the shared `aiRequests` storage so its details
* can be displayed (e.g. for historical or suspended parents whose sub-agents
* are no longer being polled by `useActivatePendingSubAgents`).
*
* One-shot fetch only — the polling/activation pipeline remains responsible
* for live updates of still-running sub-agents.
*/
export const useLoadSubAgentRequests = ({
selectedAiRequest,
}: {|
selectedAiRequest: ?AiRequest,
|}) => {
const { aiRequestStorage } = React.useContext(AiRequestContext);
const { aiRequests, refreshAiRequest } = aiRequestStorage;
const attemptedFetchRef = React.useRef<Set<string>>(new Set());
React.useEffect(
() => {
if (!selectedAiRequest) return;
const subAgentCalls = getAllSubAgentFunctionCalls({
aiRequest: selectedAiRequest,
});
for (const call of subAgentCalls) {
const subAgentAiRequestId = call.subAgentAiRequestId;
if (!subAgentAiRequestId) continue;
if (aiRequests[subAgentAiRequestId]) continue;
if (attemptedFetchRef.current.has(subAgentAiRequestId)) continue;
attemptedFetchRef.current.add(subAgentAiRequestId);
refreshAiRequest(subAgentAiRequestId);
}
},
[selectedAiRequest, aiRequests, refreshAiRequest]
);
};
export const useAiRequestState = ({
project,
fileMetadata,
storageProviderName,
onSave,
onSaveProjectAsWithStorageProvider,
}: {|
project: ?gdProject,
fileMetadata?: ?FileMetadata,
storageProviderName?: ?string,
onSave?: (options?: {|
skipNewVersionWarning: boolean,
|}) => Promise<?FileMetadata>,
onSaveProjectAsWithStorageProvider?: (
options: ?{|
requestedStorageProvider?: StorageProvider,
forcedSavedAsLocation?: SaveAsLocation,
createdProject?: gdProject,
|}
) => Promise<?FileMetadata>,
|}): {
isFetchingSuggestions: boolean,
savingProjectForMessageId: ?string,
} => {
const authenticatedUser = React.useContext(AuthenticatedUserContext);
const { profile, getAuthorizationHeader } = authenticatedUser;
const {
aiRequestStorage,
editorFunctionCallResultsStorage,
isFetchingSuggestions,
setIsFetchingSuggestions,
selectedAiRequestId,
setSelectedAiRequestId,
selectedAiRequest,
} = React.useContext(AiRequestContext);
const { updateAiRequest, isSendingAiRequest } = aiRequestStorage;
const { getEditorFunctionCallResults } = editorFunctionCallResultsStorage;
const [
savingProjectForMessageId,
setSavingProjectForMessageId,
] = React.useState<?string>(null);
// Best-effort suggestions are attempted at most once per message; this tracks
// which messages were already attempted (key: aiRequestId + last message id),
// so that a transient failure cannot loop now that the input stays enabled.
const attemptedSuggestionMessageIdsRef = React.useRef<Set<string>>(new Set());
const prevProjectRef = React.useRef(project);
React.useEffect(
() => {
if (prevProjectRef.current !== project) {
const hadPreviousProject = prevProjectRef.current !== null;
prevProjectRef.current = project;
// Only clear the selected request when switching away from an existing
// project (closing or switching projects). Do NOT clear when a project
// is first opened from scratch (null → project), e.g. when the AI
// creates a new project — we want to keep the in-progress request.
if (hadPreviousProject) {
setSelectedAiRequestId(null);
}
}
},
[project, setSelectedAiRequestId]
);
const { hasUnsavedChanges } = React.useContext(UnsavedChangesContext);
const isCloudProjectsMaximumReached = checkIfHasTooManyCloudProjects(
authenticatedUser
);
const isSavingRef = React.useRef<boolean>(false);
const currentlyOpenedCloudProjectVersionId =
fileMetadata && storageProviderName === CloudStorageProvider.internalName
? fileMetadata.version
: null;
React.useEffect(
() => {
async function fetchSuggestionsIfNeeded() {
// If the request :
// - is an agent request,
// - is not sending a new message right now,
// - went from "working" to "ready",
// - has a few messages already (not an empty request),
// - does not have any tools waiting to run,
// - and does not have any suggestions yet,
// Then ask for some.
if (
!selectedAiRequest ||
(selectedAiRequest.mode !== 'agent' &&
selectedAiRequest.mode !== 'orchestrator') ||
isSendingAiRequest(selectedAiRequest.id) ||
!selectedAiRequest.output ||
selectedAiRequest.output.length === 0 ||
selectedAiRequest.status !== 'ready' ||
!profile ||
isFetchingSuggestions
)
return;
// No suggestions until there is an actual project: before that, the AI
// is still discussing the game idea or making a plan with the user.
if (!project) return;
// Check if there are tools being run. If so, no suggestions at this time.
const hasFunctionsCallsToProcess =
getFunctionCallsToProcess({
aiRequest: selectedAiRequest,
editorFunctionCallResults: getEditorFunctionCallResults(
selectedAiRequest.id
),
}).length > 0;
if (hasFunctionsCallsToProcess) return;
// If there are sub-agents running, it means the request is still running,
// so no suggestions at this time.
const hasPendingSubAgentCalls =
getPendingSubAgentFunctionCalls({
aiRequest: selectedAiRequest,
}).length > 0;
if (hasPendingSubAgentCalls) return;
const {
hasUnfinishedResult,
} = getFunctionCallOutputsFromEditorFunctionCallResults(
getEditorFunctionCallResults(selectedAiRequest.id)
);
if (hasUnfinishedResult) return;
const outputForSuggestions = selectedAiRequest.output || [];
const lastMessage =
outputForSuggestions.length > 0
? outputForSuggestions[outputForSuggestions.length - 1]
: null;
if (
!lastMessage ||
(!(
lastMessage.type === 'message' && lastMessage.role === 'assistant'
) &&
lastMessage.type !== 'function_call_output') ||
lastMessage.suggestions
) {
return;
}
const lastMessageKey = lastMessage.messageId
? lastMessage.messageId
: `index-${outputForSuggestions.length}`;
const suggestionAttemptKey = `${
selectedAiRequest.id
}:${lastMessageKey}`;
if (
attemptedSuggestionMessageIdsRef.current.has(suggestionAttemptKey)
) {
return;
}
const isLastMessageFunctionCallOutputProjectInitialization =
lastMessage.type === 'function_call_output' &&
getFunctionCallNameByCallId({
aiRequest: selectedAiRequest,
callId: lastMessage.call_id,
}) === 'initialize_project';
if (selectedAiRequest.mode === 'orchestrator') {
if (isLastMessageFunctionCallOutputProjectInitialization) {
// Don't fetch suggestions right after project initialization, as a plan
// will be generated in the next messages and we want to display it instead.
return;
}
if (getLatestActivePlan(selectedAiRequest)) {
// For orchestrator mode, don't fetch suggestions if there is an active plan
// being displayed.
return;
}
}
const simplifiedProjectBuilder = makeSimplifiedProjectBuilder(gd);
const simplifiedProjectJson = project
? JSON.stringify(
simplifiedProjectBuilder.getSimplifiedProject(project, {})
)
: null;
const projectSpecificExtensionsSummaryJson = project
? JSON.stringify(
simplifiedProjectBuilder.getProjectSpecificExtensionsSummary(
project
)
)
: null;
const preparedAiUserContent = await prepareAiUserContent({
getAuthorizationHeader,
userId: profile.id,
simplifiedProjectJson,
projectSpecificExtensionsSummaryJson,
eventsJson: null,
});
try {
// The request will switch from "ready" to "working" while suggestions are generated.
// It will be watched and eventually return to "ready" with suggestions.
setIsFetchingSuggestions(true);
attemptedSuggestionMessageIdsRef.current.add(suggestionAttemptKey);
const aiRequestWorkingForSuggestions = await getAiRequestSuggestions(
getAuthorizationHeader,
{
userId: profile.id,
aiRequestId: selectedAiRequest.id,
suggestionsType: isLastMessageFunctionCallOutputProjectInitialization
? 'list-with-explanations'
: 'simple-list',
gameProjectJsonUserRelativeKey:
preparedAiUserContent.gameProjectJsonUserRelativeKey,
gameProjectJson: preparedAiUserContent.gameProjectJson,
projectSpecificExtensionsSummaryJsonUserRelativeKey:
preparedAiUserContent.projectSpecificExtensionsSummaryJsonUserRelativeKey,
projectSpecificExtensionsSummaryJson:
preparedAiUserContent.projectSpecificExtensionsSummaryJson,
}
);
// While we were fetching, the user may have sent a new message. If the
// conversation advanced, drop the stale snapshot: the newer message wins.
const snapshotOutput = aiRequestWorkingForSuggestions.output || [];
updateAiRequest(selectedAiRequest.id, prevRequest => {
if (!prevRequest) return aiRequestWorkingForSuggestions;
if (isSendingAiRequest(selectedAiRequest.id)) return prevRequest;
const prevOutput = prevRequest.output || [];
if (prevOutput.length !== snapshotOutput.length) return prevRequest;
return {
...prevRequest,
...aiRequestWorkingForSuggestions,
};
});
// If the request is already ready with suggestions, clear the flag immediately
// Otherwise, it will be watched and cleared when it becomes ready
if (aiRequestWorkingForSuggestions.status === 'ready') {
setIsFetchingSuggestions(false);
}
} catch (error) {
const extractedStatusAndCode = extractGDevelopApiErrorStatusAndCode(
error
);
if (
extractedStatusAndCode &&
extractedStatusAndCode.status === 400 &&
extractedStatusAndCode.code === 'ai-request/request-still-working'
) {
// Don't log anything.
return;
}
setIsFetchingSuggestions(false);
console.error('Error getting AI request suggestions:', error);
// Do not block updating the request if suggestions fetching fails.
}
}
// Debounce the call to avoid too many requests in a short period
const timeoutId = setTimeout(() => {
fetchSuggestionsIfNeeded();
}, 300);
return () => clearTimeout(timeoutId);
},
[