-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathChatBasedContentEditorController.php
More file actions
871 lines (742 loc) · 36.2 KB
/
ChatBasedContentEditorController.php
File metadata and controls
871 lines (742 loc) · 36.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
<?php
declare(strict_types=1);
namespace App\ChatBasedContentEditor\Presentation\Controller;
use App\Account\Facade\AccountFacadeInterface;
use App\Account\Facade\Dto\AccountInfoDto;
use App\ChatBasedContentEditor\Domain\Entity\Conversation;
use App\ChatBasedContentEditor\Domain\Entity\EditSession;
use App\ChatBasedContentEditor\Domain\Entity\EditSessionChunk;
use App\ChatBasedContentEditor\Domain\Enum\ConversationStatus;
use App\ChatBasedContentEditor\Domain\Enum\EditSessionStatus;
use App\ChatBasedContentEditor\Domain\Service\ConversationService;
use App\ChatBasedContentEditor\Infrastructure\Adapter\DistFileScannerInterface;
use App\ChatBasedContentEditor\Infrastructure\Message\RunEditSessionMessage;
use App\ChatBasedContentEditor\Presentation\Service\ConversationContextUsageService;
use App\ChatBasedContentEditor\Presentation\Service\PromptSuggestionsService;
use App\LlmContentEditor\Facade\Dto\AgentConfigDto;
use App\LlmContentEditor\Facade\Dto\ConversationMessageDto;
use App\LlmContentEditor\Facade\LlmContentEditorFacadeInterface;
use App\ProjectMgmt\Facade\ProjectMgmtFacadeInterface;
use App\RemoteContentAssets\Facade\RemoteContentAssetsFacadeInterface;
use App\WorkspaceMgmt\Facade\Enum\WorkspaceStatus;
use App\WorkspaceMgmt\Facade\WorkspaceMgmtFacadeInterface;
use App\WorkspaceTooling\Facade\WorkspaceToolingServiceInterface;
use Doctrine\ORM\EntityManagerInterface;
use RuntimeException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Contracts\Translation\TranslatorInterface;
use Throwable;
use function array_key_exists;
use function is_array;
use function is_string;
use function json_decode;
/**
* Controller for chat-based content editing.
* Uses internal ConversationService and cross-vertical facades.
*/
#[IsGranted('ROLE_USER')]
final class ChatBasedContentEditorController extends AbstractController
{
public function __construct(
private readonly ConversationService $conversationService,
private readonly WorkspaceMgmtFacadeInterface $workspaceMgmtFacade,
private readonly ProjectMgmtFacadeInterface $projectMgmtFacade,
private readonly AccountFacadeInterface $accountFacade,
private readonly EntityManagerInterface $entityManager,
private readonly MessageBusInterface $messageBus,
private readonly DistFileScannerInterface $distFileScanner,
private readonly ConversationContextUsageService $contextUsageService,
private readonly TranslatorInterface $translator,
private readonly PromptSuggestionsService $promptSuggestionsService,
private readonly LlmContentEditorFacadeInterface $llmContentEditorFacade,
private readonly WorkspaceToolingServiceInterface $workspaceToolingFacade,
) {
}
/**
* Resolve security user to domain AccountInfoDto via facade.
* Uses getUserIdentifier() which returns the email for our AccountCore entity.
*/
private function getAccountInfo(UserInterface $user): AccountInfoDto
{
$accountInfo = $this->accountFacade->getAccountInfoByEmail($user->getUserIdentifier());
if ($accountInfo === null) {
throw new RuntimeException('Account not found for authenticated user');
}
return $accountInfo;
}
#[Route(
path: '/projects/{projectId}/conversation',
name: 'chat_based_content_editor.presentation.start',
methods: [Request::METHOD_GET],
requirements: ['projectId' => '[a-f0-9-]{36}']
)]
public function startConversation(
string $projectId,
#[CurrentUser] UserInterface $user
): Response {
$accountInfo = $this->getAccountInfo($user);
$project = $this->projectMgmtFacade->getProjectInfo($projectId);
// Check workspace status before starting
$workspace = $this->workspaceMgmtFacade->getWorkspaceForProject($projectId);
if ($workspace !== null) {
// Handle special statuses
if ($workspace->status === WorkspaceStatus::IN_REVIEW) {
$this->addFlash('warning', $this->translator->trans('flash.error.workspace_in_review'));
return $this->redirectToRoute('project_mgmt.presentation.list');
}
if ($workspace->status === WorkspaceStatus::PROBLEM) {
return $this->render('@chat_based_content_editor.presentation/workspace_problem.twig', [
'workspace' => $workspace,
'project' => $project,
]);
}
// If workspace is setting up, show the setup waiting page
if ($workspace->status === WorkspaceStatus::IN_SETUP) {
return $this->render('@chat_based_content_editor.presentation/workspace_setup.twig', [
'workspace' => $workspace,
'project' => $project,
'pollUrl' => $this->generateUrl('chat_based_content_editor.presentation.poll_workspace_status', ['workspaceId' => $workspace->id]),
'redirectUrl' => $this->generateUrl('chat_based_content_editor.presentation.start', ['projectId' => $projectId]),
]);
}
if ($workspace->status === WorkspaceStatus::IN_CONVERSATION) {
// Check if there's an ongoing conversation for another user
$existingConversation = $this->conversationService->findOngoingConversation(
$workspace->id,
$accountInfo->id
);
if ($existingConversation === null) {
// Find who is working on it
$otherConversation = $this->conversationService->findAnyOngoingConversationForWorkspace($workspace->id);
$otherUserEmail = 'another user';
if ($otherConversation !== null) {
$otherAccount = $this->accountFacade->getAccountInfoById($otherConversation->getUserId());
if ($otherAccount !== null) {
$otherUserEmail = $otherAccount->email;
}
}
$this->addFlash('warning', $this->translator->trans('flash.error.workspace_busy', ['%email%' => $otherUserEmail]));
return $this->redirectToRoute('project_mgmt.presentation.list');
}
}
}
try {
// Dispatch async setup if needed - this will start setup in background
$workspace = $this->workspaceMgmtFacade->dispatchSetupIfNeeded($projectId, $accountInfo->email);
// If setup was dispatched (workspace is now IN_SETUP), show waiting page
if ($workspace->status === WorkspaceStatus::IN_SETUP) {
return $this->render('@chat_based_content_editor.presentation/workspace_setup.twig', [
'workspace' => $workspace,
'project' => $project,
'pollUrl' => $this->generateUrl('chat_based_content_editor.presentation.poll_workspace_status', ['workspaceId' => $workspace->id]),
'redirectUrl' => $this->generateUrl('chat_based_content_editor.presentation.start', ['projectId' => $projectId]),
]);
}
// Workspace is ready - start or resume conversation
$conversationInfo = $this->conversationService->startOrResumeConversation($projectId, $accountInfo->id);
return $this->redirectToRoute('chat_based_content_editor.presentation.show', [
'conversationId' => $conversationInfo->id,
]);
} catch (Throwable $e) {
$this->addFlash('error', $this->translator->trans('flash.error.start_conversation_failed', ['%error%' => $e->getMessage()]));
return $this->redirectToRoute('project_mgmt.presentation.list');
}
}
#[Route(
path: '/workspace/{workspaceId}/status',
name: 'chat_based_content_editor.presentation.poll_workspace_status',
methods: [Request::METHOD_GET],
requirements: ['workspaceId' => '[a-f0-9-]{36}']
)]
public function pollWorkspaceStatus(string $workspaceId): Response
{
$workspace = $this->workspaceMgmtFacade->getWorkspaceById($workspaceId);
if ($workspace === null) {
return $this->json(['error' => 'Workspace not found.'], Response::HTTP_NOT_FOUND);
}
return $this->json([
'status' => $workspace->status->name,
'ready' => $workspace->status === WorkspaceStatus::AVAILABLE_FOR_CONVERSATION,
'error' => $workspace->status === WorkspaceStatus::PROBLEM,
]);
}
/**
* Heartbeat endpoint to track user presence in a conversation.
* Called periodically by the frontend to indicate the user is still active.
*/
#[Route(
path: '/conversation/{conversationId}/heartbeat',
name: 'chat_based_content_editor.presentation.heartbeat',
methods: [Request::METHOD_POST],
requirements: ['conversationId' => '[a-f0-9-]{36}']
)]
public function heartbeat(
string $conversationId,
#[CurrentUser] UserInterface $user
): Response {
$conversation = $this->entityManager->find(Conversation::class, $conversationId);
if ($conversation === null) {
return $this->json(['error' => 'Conversation not found.'], Response::HTTP_NOT_FOUND);
}
$accountInfo = $this->getAccountInfo($user);
// Only the conversation owner can send heartbeats
if ($conversation->getUserId() !== $accountInfo->id) {
return $this->json(['error' => 'Not authorized.'], Response::HTTP_FORBIDDEN);
}
// Only update heartbeat for ongoing conversations
if ($conversation->getStatus() !== ConversationStatus::ONGOING) {
return $this->json(['error' => 'Conversation is not ongoing.'], Response::HTTP_BAD_REQUEST);
}
$conversation->updateLastActivity();
$this->entityManager->flush();
return $this->json(['success' => true]);
}
#[Route(
path: '/conversation/{conversationId}',
name: 'chat_based_content_editor.presentation.show',
methods: [Request::METHOD_GET],
requirements: ['conversationId' => '[a-f0-9-]{36}']
)]
public function show(
string $conversationId,
Request $request,
#[CurrentUser] UserInterface $user,
): Response {
$conversation = $this->entityManager->find(Conversation::class, $conversationId);
if ($conversation === null) {
throw $this->createNotFoundException('Conversation not found.');
}
$accountInfo = $this->getAccountInfo($user);
// Authorization: Owner can access any conversation; anyone can access finished (read-only) conversations
$isOwner = $conversation->getUserId() === $accountInfo->id;
$isFinished = $conversation->getStatus() !== ConversationStatus::ONGOING;
// Determine if this is a read-only view (finished conversation)
$readOnly = $conversation->getStatus() !== ConversationStatus::ONGOING;
$canEdit = !$readOnly;
if (!$isOwner && !$isFinished) {
$readOnly = true;
$canEdit = false;
}
// Get workspace info for status display
$workspace = $this->workspaceMgmtFacade->getWorkspaceById($conversation->getWorkspaceId());
$projectInfo = null;
if ($workspace !== null) {
$projectInfo = $this->projectMgmtFacade->getProjectInfo($workspace->projectId);
}
// Build turns from edit sessions and detect active session
$turns = [];
$activeSession = null;
$activeSessionChunks = [];
foreach ($conversation->getEditSessions() as $session) {
$sessionStatus = $session->getStatus();
// Check if this is an active (Pending, Running, or Cancelling) session
if (
$sessionStatus === EditSessionStatus::Pending
|| $sessionStatus === EditSessionStatus::Running
|| $sessionStatus === EditSessionStatus::Cancelling
) {
$activeSession = $session;
// Collect existing chunks for this active session
foreach ($session->getChunks() as $chunk) {
$activeSessionChunks[] = [
'id' => $chunk->getId(),
'chunkType' => $chunk->getChunkType()->value,
'payload' => $chunk->getPayloadJson(),
];
}
}
$assistantResponse = '';
$eventChunks = [];
foreach ($session->getChunks() as $chunk) {
$chunkType = $chunk->getChunkType()->value;
if ($chunkType === 'text') {
$payload = json_decode($chunk->getPayloadJson(), true);
if (is_array($payload) && array_key_exists('content', $payload) && is_string($payload['content'])) {
$assistantResponse .= $payload['content'];
}
} elseif ($chunkType === 'event') {
$eventChunks[] = [
'id' => $chunk->getId(),
'chunkType' => $chunkType,
'payload' => $chunk->getPayloadJson(),
];
}
}
$turns[] = [
'instruction' => $session->getInstruction(),
'response' => $assistantResponse,
'status' => $sessionStatus->value,
'events' => $eventChunks,
];
}
$activeSessionIdForContext = $activeSession !== null ? $activeSession->getId() : null;
$contextUsage = $this->contextUsageService->getContextUsage($conversation, $activeSessionIdForContext);
// Load prompt suggestions only for editable sessions
$promptSuggestions = [];
if ($canEdit && $workspace !== null) {
$promptSuggestions = $this->promptSuggestionsService->getSuggestions($workspace->workspacePath);
}
return $this->render('@chat_based_content_editor.presentation/chat_based_content_editor.twig', [
'conversation' => $conversation,
'workspace' => $workspace,
'project' => $projectInfo,
'turns' => $turns,
'readOnly' => $readOnly,
'canEdit' => $canEdit,
'runUrl' => $readOnly ? '' : $this->generateUrl('chat_based_content_editor.presentation.run'),
'pollUrlTemplate' => $readOnly ? '' : $this->generateUrl('chat_based_content_editor.presentation.poll', ['sessionId' => '__SESSION_ID__']),
'cancelUrlTemplate' => $readOnly ? '' : $this->generateUrl('chat_based_content_editor.presentation.cancel', ['sessionId' => '__SESSION_ID__']),
'contextUsage' => [
'usedTokens' => $contextUsage->usedTokens,
'maxTokens' => $contextUsage->maxTokens,
'modelName' => $contextUsage->modelName,
'inputTokens' => $contextUsage->inputTokens,
'outputTokens' => $contextUsage->outputTokens,
'inputCost' => $contextUsage->inputCost,
'outputCost' => $contextUsage->outputCost,
'totalCost' => $contextUsage->totalCost,
],
'contextUsageUrl' => $readOnly ? '' : $this->generateUrl('chat_based_content_editor.presentation.context_usage', ['conversationId' => $conversation->getId()]),
'activeSession' => $activeSession !== null ? [
'id' => $activeSession->getId(),
'status' => $activeSession->getStatus()->value,
'instruction' => $activeSession->getInstruction(),
'chunks' => $activeSessionChunks,
'lastChunkId' => count($activeSessionChunks) > 0 ? $activeSessionChunks[count($activeSessionChunks) - 1]['id'] : 0,
] : null,
'remoteAssetBrowserWindowSize' => RemoteContentAssetsFacadeInterface::BROWSER_WINDOW_SIZE,
'promptSuggestions' => $promptSuggestions,
'prefillMessage' => $request->query->getString('prefill'),
]);
}
#[Route(
path: '/chat-based-content-editor/{conversationId}/context-usage',
name: 'chat_based_content_editor.presentation.context_usage',
methods: [Request::METHOD_GET],
requirements: ['conversationId' => '[a-f0-9-]{36}']
)]
public function contextUsage(string $conversationId, Request $request): Response
{
$conversation = $this->entityManager->find(Conversation::class, $conversationId);
if ($conversation === null) {
return $this->json(['error' => 'Conversation not found.'], Response::HTTP_NOT_FOUND);
}
$sessionId = $request->query->get('sessionId');
$activeSessionId = null;
if ($sessionId !== null && $sessionId !== '') {
$session = $this->entityManager->find(EditSession::class, $sessionId);
if ($session instanceof EditSession && $session->getConversation()->getId() === $conversation->getId()) {
$activeSessionId = $sessionId;
}
}
$dto = $this->contextUsageService->getContextUsage($conversation, $activeSessionId);
return $this->json([
'usedTokens' => $dto->usedTokens,
'maxTokens' => $dto->maxTokens,
'modelName' => $dto->modelName,
'inputTokens' => $dto->inputTokens,
'outputTokens' => $dto->outputTokens,
'inputCost' => $dto->inputCost,
'outputCost' => $dto->outputCost,
'totalCost' => $dto->totalCost,
]);
}
/**
* Dump the full agent context (system prompt + conversation history + last instruction)
* as it would be sent to the LLM API. Returns plain text for troubleshooting.
*/
#[Route(
path: '/conversation/{conversationId}/dump-agent-context',
name: 'chat_based_content_editor.presentation.dump_agent_context',
methods: [Request::METHOD_GET],
requirements: ['conversationId' => '[a-f0-9-]{36}']
)]
public function dumpAgentContext(
string $conversationId,
#[CurrentUser] UserInterface $user
): Response {
$conversation = $this->entityManager->find(Conversation::class, $conversationId);
if ($conversation === null) {
throw $this->createNotFoundException('Conversation not found.');
}
$accountInfo = $this->getAccountInfo($user);
// Only the conversation owner can dump context
if ($conversation->getUserId() !== $accountInfo->id) {
throw $this->createAccessDeniedException('Only the conversation owner can view the agent context.');
}
// Load project info for agent config
$workspace = $this->workspaceMgmtFacade->getWorkspaceById($conversation->getWorkspaceId());
$projectInfo = $workspace !== null ? $this->projectMgmtFacade->getProjectInfo($workspace->projectId) : null;
if ($projectInfo === null) {
return new Response('Project not found — cannot reconstruct agent context.', Response::HTTP_OK, [
'Content-Type' => 'text/plain; charset=UTF-8',
]);
}
// Build agent config from project settings (same as RunEditSessionHandler)
$agentConfig = new AgentConfigDto(
$projectInfo->agentBackgroundInstructions,
$projectInfo->agentStepInstructions,
$projectInfo->agentOutputInstructions,
'/workspace',
);
// Collect conversation messages as DTOs
/** @var list<ConversationMessageDto> $previousMessages */
$previousMessages = [];
foreach ($conversation->getMessages() as $message) {
$previousMessages[] = new ConversationMessageDto(
$message->getRole()->value,
$message->getContentJson()
);
}
// Find the last instruction from the most recent edit session
$lastInstruction = '(no instruction yet)';
$editSessions = $conversation->getEditSessions();
$lastSession = $editSessions->last();
if ($lastSession !== false) {
$lastInstruction = $lastSession->getInstruction();
}
$dump = $this->llmContentEditorFacade->buildAgentContextDump(
$lastInstruction,
$previousMessages,
$agentConfig
);
return new Response($dump, Response::HTTP_OK, [
'Content-Type' => 'text/plain; charset=UTF-8',
]);
}
#[Route(
path: '/conversation/{conversationId}/finish',
name: 'chat_based_content_editor.presentation.finish',
methods: [Request::METHOD_POST],
requirements: ['conversationId' => '[a-f0-9-]{36}']
)]
public function finish(
string $conversationId,
Request $request,
#[CurrentUser] UserInterface $user
): Response {
if (!$this->isCsrfTokenValid('conversation_finish', $request->request->getString('_csrf_token'))) {
$this->addFlash('error', $this->translator->trans('flash.error.invalid_csrf'));
return $this->redirectToRoute('chat_based_content_editor.presentation.show', [
'conversationId' => $conversationId,
]);
}
$accountInfo = $this->getAccountInfo($user);
try {
$this->conversationService->finishConversation($conversationId, $accountInfo->id);
$this->addFlash('success', $this->translator->trans('flash.success.conversation_finished'));
} catch (Throwable $e) {
$this->addFlash('error', $this->translator->trans('flash.error.finish_conversation_failed', ['%error%' => $e->getMessage()]));
}
return $this->redirectToRoute('project_mgmt.presentation.list');
}
#[Route(
path: '/conversation/{conversationId}/send-to-review',
name: 'chat_based_content_editor.presentation.send_to_review',
methods: [Request::METHOD_POST],
requirements: ['conversationId' => '[a-f0-9-]{36}']
)]
public function sendToReview(
string $conversationId,
Request $request,
#[CurrentUser] UserInterface $user
): Response {
if (!$this->isCsrfTokenValid('conversation_review', $request->request->getString('_csrf_token'))) {
$this->addFlash('error', $this->translator->trans('flash.error.invalid_csrf'));
return $this->redirectToRoute('chat_based_content_editor.presentation.show', [
'conversationId' => $conversationId,
]);
}
$accountInfo = $this->getAccountInfo($user);
try {
$prUrl = $this->conversationService->sendToReview($conversationId, $accountInfo->id);
if ($prUrl === '') {
$this->addFlash('success', $this->translator->trans('flash.success.conversation_finished_no_changes'));
} else {
$this->addFlash('success', $this->translator->trans('flash.success.conversation_sent_to_review', ['%url%' => $prUrl]));
}
} catch (Throwable $e) {
$this->addFlash('error', $this->translator->trans('flash.error.send_to_review_failed', ['%error%' => $e->getMessage()]));
}
return $this->redirectToRoute('project_mgmt.presentation.list');
}
#[Route(
path: '/workspace/{workspaceId}/reset',
name: 'chat_based_content_editor.presentation.reset_workspace',
methods: [Request::METHOD_POST],
requirements: ['workspaceId' => '[a-f0-9-]{36}']
)]
public function resetWorkspace(string $workspaceId, Request $request): Response
{
if (!$this->isCsrfTokenValid('workspace_reset', $request->request->getString('_csrf_token'))) {
$this->addFlash('error', $this->translator->trans('flash.error.invalid_csrf'));
return $this->redirectToRoute('project_mgmt.presentation.list');
}
try {
$this->workspaceMgmtFacade->resetProblemWorkspace($workspaceId);
$this->addFlash('success', $this->translator->trans('flash.success.workspace_reset_conversation_ready'));
} catch (Throwable $e) {
$this->addFlash('error', $this->translator->trans('flash.error.workspace_reset_failed', ['%error%' => $e->getMessage()]));
}
return $this->redirectToRoute('project_mgmt.presentation.list');
}
#[Route(
path: '/chat-based-content-editor/run',
name: 'chat_based_content_editor.presentation.run',
methods: [Request::METHOD_POST]
)]
public function run(
Request $request,
#[CurrentUser] UserInterface $user
): Response {
$instruction = $request->request->getString('instruction');
$conversationId = $request->request->getString('conversation_id');
if ($instruction === '') {
return $this->json(['error' => 'Instruction is required.'], Response::HTTP_BAD_REQUEST);
}
if (!$this->isCsrfTokenValid('chat_based_content_editor_run', $request->request->getString('_csrf_token'))) {
return $this->json(['error' => 'Invalid CSRF token.'], Response::HTTP_FORBIDDEN);
}
$conversation = $this->entityManager->find(Conversation::class, $conversationId);
if ($conversation === null) {
return $this->json(['error' => 'Conversation not found.'], Response::HTTP_NOT_FOUND);
}
// Verify user owns this conversation
$accountInfo = $this->getAccountInfo($user);
if ($conversation->getUserId() !== $accountInfo->id) {
return $this->json(['error' => 'Not authorized to run edits in this conversation.'], Response::HTTP_FORBIDDEN);
}
// Verify conversation is still ongoing
if ($conversation->getStatus() !== ConversationStatus::ONGOING) {
return $this->json(['error' => 'Conversation is no longer active.'], Response::HTTP_BAD_REQUEST);
}
$session = new EditSession($conversation, $instruction);
$this->entityManager->persist($session);
$this->entityManager->flush();
$sessionId = $session->getId();
if ($sessionId === null) {
return $this->json(['error' => 'Failed to create session.'], Response::HTTP_INTERNAL_SERVER_ERROR);
}
$this->messageBus->dispatch(new RunEditSessionMessage($sessionId, $request->getLocale()));
return $this->json([
'sessionId' => $sessionId,
]);
}
#[Route(
path: '/chat-based-content-editor/cancel/{sessionId}',
name: 'chat_based_content_editor.presentation.cancel',
methods: [Request::METHOD_POST]
)]
public function cancel(
string $sessionId,
Request $request,
#[CurrentUser] UserInterface $user
): Response {
if (!$this->isCsrfTokenValid('chat_based_content_editor_run', $request->request->getString('_csrf_token'))) {
return $this->json(['error' => $this->translator->trans('api.error.invalid_csrf')], Response::HTTP_FORBIDDEN);
}
$session = $this->entityManager->find(EditSession::class, $sessionId);
if ($session === null) {
return $this->json(['error' => $this->translator->trans('api.error.session_not_found')], Response::HTTP_NOT_FOUND);
}
// Verify user owns this conversation
$accountInfo = $this->getAccountInfo($user);
$conversation = $session->getConversation();
if ($conversation->getUserId() !== $accountInfo->id) {
return $this->json(['error' => $this->translator->trans('api.error.not_authorized')], Response::HTTP_FORBIDDEN);
}
$status = $session->getStatus();
// If already in a terminal state, nothing to cancel
if (
$status === EditSessionStatus::Completed
|| $status === EditSessionStatus::Failed
|| $status === EditSessionStatus::Cancelled
) {
return $this->json(['success' => true, 'alreadyFinished' => true]);
}
// Set to Cancelling so the handler can detect it cooperatively
$session->setStatus(EditSessionStatus::Cancelling);
$this->entityManager->flush();
$conversationId = $conversation->getId();
if ($conversationId !== null) {
try {
// Best-effort hard stop for long-running tool/runtime containers.
$this->workspaceToolingFacade->stopAgentContainersForConversation(
$conversation->getWorkspaceId(),
$conversationId
);
} catch (Throwable) {
// If runtime interruption fails, cooperative cancellation still applies.
}
}
return $this->json(['success' => true]);
}
#[Route(
path: '/chat-based-content-editor/poll/{sessionId}',
name: 'chat_based_content_editor.presentation.poll',
methods: [Request::METHOD_GET]
)]
public function poll(string $sessionId, Request $request): Response
{
$session = $this->entityManager->find(EditSession::class, $sessionId);
if ($session === null) {
return $this->json(['error' => 'Session not found.'], Response::HTTP_NOT_FOUND);
}
$after = $request->query->getInt('after', 0);
$limit = 100;
/** @var list<EditSessionChunk> $chunks */
$chunks = $this->entityManager->createQueryBuilder()
->select('c')
->from(EditSessionChunk::class, 'c')
->where('c.session = :session')
->andWhere('c.id > :after')
->setParameter('session', $session)
->setParameter('after', $after)
->orderBy('c.id', 'ASC')
->setMaxResults($limit)
->getQuery()
->getResult();
$lastId = $after;
$chunkData = [];
foreach ($chunks as $chunk) {
$chunkId = $chunk->getId();
if ($chunkId !== null && $chunkId > $lastId) {
$lastId = $chunkId;
}
$chunkData[] = [
'id' => $chunkId,
'chunkType' => $chunk->getChunkType()->value,
'payload' => $chunk->getPayloadJson(),
];
}
$conversation = $session->getConversation();
$contextUsage = $this->contextUsageService->getContextUsage($conversation, $session->getId());
return $this->json([
'chunks' => $chunkData,
'lastId' => $lastId,
'status' => $session->getStatus()->value,
'contextUsage' => [
'usedTokens' => $contextUsage->usedTokens,
'maxTokens' => $contextUsage->maxTokens,
'modelName' => $contextUsage->modelName,
'inputTokens' => $contextUsage->inputTokens,
'outputTokens' => $contextUsage->outputTokens,
'inputCost' => $contextUsage->inputCost,
'outputCost' => $contextUsage->outputCost,
'totalCost' => $contextUsage->totalCost,
],
]);
}
#[Route(
path: '/workspace/{workspaceId}/dist-files',
name: 'chat_based_content_editor.presentation.dist_files',
methods: [Request::METHOD_GET],
requirements: ['workspaceId' => '[a-f0-9-]{36}']
)]
public function distFiles(string $workspaceId): Response
{
$workspace = $this->workspaceMgmtFacade->getWorkspaceById($workspaceId);
if ($workspace === null) {
return $this->json(['error' => 'Workspace not found.'], Response::HTTP_NOT_FOUND);
}
$distFiles = $this->distFileScanner->scanDistHtmlFiles($workspace->id, $workspace->workspacePath);
$files = [];
foreach ($distFiles as $distFile) {
$files[] = [
'path' => $distFile->path,
'url' => $distFile->url,
];
}
return $this->json(['files' => $files]);
}
#[Route(
path: '/workspace/{workspaceId}/page-content',
name: 'chat_based_content_editor.presentation.page_content',
methods: [Request::METHOD_GET],
requirements: ['workspaceId' => '[a-f0-9-]{36}']
)]
public function getPageContent(string $workspaceId, Request $request): Response
{
$workspace = $this->workspaceMgmtFacade->getWorkspaceById($workspaceId);
if ($workspace === null) {
return $this->json(['error' => 'Workspace not found.'], Response::HTTP_NOT_FOUND);
}
$path = $request->query->getString('path');
if ($path === '') {
return $this->json(['error' => 'Path parameter is required.'], Response::HTTP_BAD_REQUEST);
}
// Map dist/ path to src/ for reading source files
$sourcePath = $this->mapDistPathToSrc($path);
try {
$content = $this->workspaceMgmtFacade->readWorkspaceFile($workspaceId, $sourcePath);
return $this->json(['content' => $content]);
} catch (Throwable $e) {
return $this->json(['error' => 'Failed to read file: ' . $e->getMessage()], Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
#[Route(
path: '/workspace/{workspaceId}/save-page',
name: 'chat_based_content_editor.presentation.save_page',
methods: [Request::METHOD_POST],
requirements: ['workspaceId' => '[a-f0-9-]{36}']
)]
public function savePage(
string $workspaceId,
Request $request,
#[CurrentUser] UserInterface $user
): Response {
if (!$this->isCsrfTokenValid('html_editor_save', $request->request->getString('_csrf_token'))) {
return $this->json(['error' => 'Invalid CSRF token.'], Response::HTTP_FORBIDDEN);
}
$workspace = $this->workspaceMgmtFacade->getWorkspaceById($workspaceId);
if ($workspace === null) {
return $this->json(['error' => 'Workspace not found.'], Response::HTTP_NOT_FOUND);
}
$path = $request->request->getString('path');
$content = $request->request->getString('content');
if ($path === '') {
return $this->json(['error' => 'Path parameter is required.'], Response::HTTP_BAD_REQUEST);
}
// Map dist/ path to src/ for writing source files
$sourcePath = $this->mapDistPathToSrc($path);
try {
// Write the file to src/
$this->workspaceMgmtFacade->writeWorkspaceFile($workspaceId, $sourcePath, $content);
// Run build to update dist/ from src/
$this->workspaceMgmtFacade->runBuild($workspaceId);
// Get user email for commit author
$accountInfo = $this->getAccountInfo($user);
// Commit and push the changes (now includes both src/ and rebuilt dist/)
$this->workspaceMgmtFacade->commitAndPush(
$workspaceId,
'Manual HTML edit: ' . $sourcePath,
$accountInfo->email
);
return $this->json(['success' => true]);
} catch (Throwable $e) {
return $this->json(['error' => 'Failed to save file: ' . $e->getMessage()], Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
/**
* Map a dist/ path to the corresponding src/ path.
*
* The HTML editor displays files from /dist but edits should be made to /src.
* After saving to /src, a build is run to update /dist.
*
* Example: dist/index.html -> src/index.html
*/
private function mapDistPathToSrc(string $path): string
{
if (str_starts_with($path, 'dist/')) {
return 'src/' . substr($path, 5); // 'dist/' = 5 characters
}
return $path;
}
}