-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1340 lines (1181 loc) · 47.4 KB
/
main.py
File metadata and controls
1340 lines (1181 loc) · 47.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import html
from contextlib import asynccontextmanager
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from textwrap import dedent
from typing import cast
from uuid import uuid4
from fastapi import FastAPI, Form, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from agents.base_agent import (
ChatHarness,
)
from agents.harness_registry import (
HarnessRegistry,
HarnessResolutionError,
build_chat_harness_registry,
)
from persistence import (
ChatMessage,
ChatRepository,
ChatSession,
ChatSessionRun,
ChatTurnRequestState,
StorageInitializationError,
bootstrap_database,
)
from services import ChatTurnObservability, ChatTurnService, failure_presentation
from utils.diagnostics import (
DiagnosticCheck,
StartupDiagnosticsError,
build_readiness_payload,
collect_startup_checks,
raise_for_failed_startup_checks,
)
from utils.client_identity import resolve_client_id, set_client_id_cookie
from utils.html_formatter import format_response_as_html
from utils.logging_config import get_logger, init_logging
from utils.settings import RuntimeSettings, get_settings, load_project_env
APP_ROOT = Path(__file__).resolve().parent
TEMPLATES_DIR = APP_ROOT / "templates"
STATIC_DIR = APP_ROOT / "static"
logger = get_logger("api")
templates = Jinja2Templates(directory=str(TEMPLATES_DIR))
def _static_asset_version() -> str:
asset_paths = [
STATIC_DIR / "css" / "chat.css",
STATIC_DIR / "js" / "chat.js",
]
latest_mtime = max(int(path.stat().st_mtime) for path in asset_paths if path.exists())
return str(latest_mtime)
@dataclass(frozen=True)
class ChatPageState:
visible_chats: list[ChatSession]
selected_chat: ChatSession | None
transcript_messages: list[ChatMessage]
view_state: str
@property
def active_chat_session_id(self) -> int | None:
if self.selected_chat is None:
return None
return self.selected_chat.id
@dataclass(frozen=True)
class ChatSessionInspectabilityView:
session_id: int
created_at: str
updated_at: str
harness_key: str
harness_version: str | None
runtime_display_name: str
runtime_model_display_name: str
runtime_provider_name: str | None
latest_run_id: int | None
latest_run_kind: str | None
latest_run_status: str | None
latest_run_updated_at: str | None
def _get_chat_harness(request: Request) -> ChatHarness:
"""Resolve the default request-scoped harness initialized at startup."""
try:
registry = request.app.state.chat_harness_registry
except AttributeError as exc:
logger.error("Chat harness is not initialized")
raise HTTPException(status_code=503, detail="Chat harness unavailable") from exc
try:
return registry.default()
except HarnessResolutionError as exc:
logger.error("Default chat harness could not be resolved detail=%s", str(exc))
raise HTTPException(status_code=503, detail="Chat harness unavailable") from exc
def _get_chat_harness_registry(request: Request) -> HarnessRegistry:
try:
return request.app.state.chat_harness_registry
except AttributeError as exc:
logger.error("Chat harness registry is not initialized")
raise HTTPException(status_code=503, detail="Chat harness unavailable") from exc
def _get_chat_turn_service(request: Request) -> ChatTurnService:
try:
return request.app.state.chat_turn_service
except AttributeError as exc:
logger.error("Chat turn service is not initialized")
raise HTTPException(status_code=503, detail="Chat turn service unavailable") from exc
def _chat_harness_display_name(chat_harness: ChatHarness) -> str:
return chat_harness.identity.display_name
def _chat_harness_model_display_name(chat_harness: ChatHarness) -> str:
return chat_harness.identity.model_display_name
def _render_bot_message(
body_html: str, timestamp: str, title: str | None = None, *, is_error: bool = False
) -> str:
message_classes = "message bot-message fade-in"
if is_error:
message_classes += " error-message"
title_html = f'<div class="message-title">{html.escape(title)}</div>' if title else ""
return dedent(
f"""
<div class="{message_classes}">
<div class="message-content">
{title_html}
<div class="message-body">{body_html}</div>
<div class="message-timestamp">{timestamp}</div>
</div>
</div>
"""
).strip()
def _render_error_message(title: str, body: str, timestamp: str, status_code: int) -> HTMLResponse:
return _render_error_response(title, body, timestamp, status_code)
def _render_chat_session_id_input(chat_session_id: int) -> str:
return (
f'<input type="hidden" id="chat-session-id" name="chat_session_id" '
f'value="{chat_session_id}" hx-swap-oob="true">'
)
def _render_chat_session_id_input_value(chat_session_id: int | None) -> str:
value = "" if chat_session_id is None else str(chat_session_id)
return (
'<input type="hidden" id="chat-session-id" name="chat_session_id" '
f'value="{value}" hx-swap-oob="true">'
)
def _render_htmx_response(
content: str, status_code: int = 200, *, chat_session_id: int | None = None
) -> HTMLResponse:
response_content = content
if chat_session_id is not None:
response_content = f"{response_content}\n{_render_chat_session_id_input(chat_session_id)}"
return HTMLResponse(
content=response_content,
status_code=status_code,
)
def _render_error_response(
title: str,
body: str,
timestamp: str,
status_code: int,
*,
chat_session_id: int | None = None,
) -> HTMLResponse:
return _render_htmx_response(
_render_bot_message(html.escape(body), timestamp, title, is_error=True),
status_code=status_code,
chat_session_id=chat_session_id,
)
def _render_chat_not_found_message(timestamp: str) -> HTMLResponse:
return _render_error_response(
"Chat Not Found",
"The requested chat could not be found.",
timestamp,
404,
)
def _chat_url_path(chat_session_id: int) -> str:
return f"/chats/{chat_session_id}"
def _chat_start_url_path() -> str:
return "/chat-start"
def _new_request_id() -> str:
return str(uuid4())
def _validate_message_input(message: str | None) -> str:
if message is None or not message.strip():
raise ValueError("Message cannot be empty")
return message
def _validate_chat_session_input(chat_session_id: str | None) -> int | None:
if chat_session_id is None or not chat_session_id.strip():
return None
try:
parsed_chat_session_id = int(chat_session_id)
except ValueError as exc:
raise ValueError("Chat session ID is invalid") from exc
if parsed_chat_session_id <= 0:
raise ValueError("Chat session ID is invalid")
return parsed_chat_session_id
def _validate_request_id_input(request_id: str | None) -> str:
if request_id is None or not request_id.strip():
raise ValueError("Request ID is required")
return request_id.strip()
def _set_startup_state(app: FastAPI, *, startup_complete: bool) -> None:
app.state.startup_complete = startup_complete
def _is_chat_service_available(app: FastAPI) -> bool:
return (
bool(getattr(app.state, "startup_complete", False))
and hasattr(app.state, "chat_harness_registry")
and hasattr(app.state, "chat_repository")
and hasattr(app.state, "chat_turn_service")
)
def _chat_service_unavailable_detail(app: FastAPI) -> str:
if not bool(getattr(app.state, "startup_complete", False)):
return "The chat service is still starting up. Please try again shortly."
return "The chat service is temporarily unavailable. Please try again shortly."
def _readiness_status(app: FastAPI) -> tuple[int, dict[str, object]]:
harness_observability: ChatTurnObservability | None = None
if hasattr(app.state, "chat_harness"):
harness_observability = ChatTurnObservability.from_harness(
app.state.chat_harness,
model=app.state.chat_harness.model if hasattr(app.state.chat_harness, "model") else None,
)
return build_readiness_payload(
startup_complete=bool(getattr(app.state, "startup_complete", False)),
harness_initialized=hasattr(app.state, "chat_harness_registry"),
storage_initialized=hasattr(app.state, "chat_repository"),
harness_metadata=(
None if harness_observability is None else harness_observability.identity_metadata()
),
)
def _log_known_chat_error(event: str, exc: Exception) -> None:
logger.warning("%s detail=%s", event, str(exc))
def _finalize_response_with_client_cookie(
response: Response, *, client_id: str, should_set_cookie: bool
) -> Response:
if should_set_cookie:
set_client_id_cookie(response, client_id)
return response
def _format_text_as_html(text: str) -> str:
return html.escape(text).replace("\n", "<br>")
def _format_chat_timestamp(timestamp: str) -> str:
try:
parsed_timestamp = datetime.fromisoformat(timestamp)
except ValueError:
return timestamp
if parsed_timestamp.tzinfo is not None:
parsed_timestamp = parsed_timestamp.astimezone()
return parsed_timestamp.strftime("%b %d, %I:%M %p")
def _format_chat_list_timestamp(timestamp: str) -> str:
try:
parsed_timestamp = datetime.fromisoformat(timestamp)
except ValueError:
return timestamp
if parsed_timestamp.tzinfo is not None:
parsed_timestamp = parsed_timestamp.astimezone()
now = datetime.now(parsed_timestamp.tzinfo)
if parsed_timestamp.date() == now.date():
return parsed_timestamp.strftime("%I:%M %p")
return parsed_timestamp.strftime("%b %d")
def _is_chat_session_active(chat_session: ChatSession | None) -> bool:
return chat_session is not None and chat_session.archived_at is None and chat_session.deleted_at is None
def _first_visible_chat_session_id(repository: ChatRepository, *, client_id: str) -> int | None:
visible_chats = repository.list_visible_chats(client_id=client_id)
if not visible_chats:
return None
return visible_chats[0].id
def _load_chat_page_state(
repository: ChatRepository,
*,
client_id: str,
chat_session_id: int | None,
) -> ChatPageState:
visible_chats = repository.list_visible_chats(client_id=client_id)
if chat_session_id is None:
return ChatPageState(
visible_chats=visible_chats,
selected_chat=None,
transcript_messages=[],
view_state="start",
)
selected_chat = repository.get_chat(chat_session_id=chat_session_id, client_id=client_id)
if selected_chat is None:
return ChatPageState(
visible_chats=visible_chats,
selected_chat=None,
transcript_messages=[],
view_state="not_found",
)
return ChatPageState(
visible_chats=visible_chats,
selected_chat=selected_chat,
transcript_messages=repository.list_messages_for_chat(
chat_session_id=selected_chat.id,
client_id=client_id,
),
view_state="active",
)
def _resolve_runtime_identity_for_chat_session(
request: Request,
*,
chat_session: ChatSession,
) -> tuple[str, str, str | None]:
try:
registry = _get_chat_harness_registry(request)
bound_harness = registry.resolve_binding(
chat_session.harness_key,
version=chat_session.harness_version,
)
return (
bound_harness.identity.display_name,
bound_harness.identity.model_display_name,
bound_harness.identity.provider_name,
)
except (HTTPException, HarnessResolutionError):
return (
chat_session.harness_key,
"Unavailable",
None,
)
def _latest_run_view_fields(run: ChatSessionRun | None) -> tuple[int | None, str | None, str | None, str | None]:
if run is None:
return (None, None, None, None)
return (
run.id,
run.run_kind,
run.status,
run.updated_at,
)
def _build_session_inspectability_view(
request: Request,
*,
repository: ChatRepository | None,
page_state: ChatPageState,
) -> ChatSessionInspectabilityView | None:
if repository is None or page_state.view_state != "active" or page_state.selected_chat is None:
return None
inspectability = repository.get_chat_session_inspectability(
chat_session_id=page_state.selected_chat.id,
client_id=page_state.selected_chat.client_id,
)
if inspectability is None:
return None
runtime_display_name, runtime_model_display_name, runtime_provider_name = (
_resolve_runtime_identity_for_chat_session(
request,
chat_session=inspectability.chat_session,
)
)
latest_run_id, latest_run_kind, latest_run_status, latest_run_updated_at = _latest_run_view_fields(
inspectability.latest_run
)
return ChatSessionInspectabilityView(
session_id=inspectability.chat_session.id,
created_at=inspectability.chat_session.created_at,
updated_at=inspectability.chat_session.updated_at,
harness_key=inspectability.chat_session.harness_key,
harness_version=inspectability.chat_session.harness_version,
runtime_display_name=runtime_display_name,
runtime_model_display_name=runtime_model_display_name,
runtime_provider_name=runtime_provider_name,
latest_run_id=latest_run_id,
latest_run_kind=latest_run_kind,
latest_run_status=latest_run_status,
latest_run_updated_at=latest_run_updated_at,
)
def _base_template_context(
request: Request,
*,
display_name: str,
model_display_name: str,
chat_available: bool,
service_status_message: str,
) -> dict[str, object]:
return {
"request": request,
"model_display_name": model_display_name,
"display_name": display_name,
"chat_available": chat_available,
"service_status_title": "Chat unavailable",
"service_status_message": service_status_message,
"format_chat_timestamp": _format_chat_timestamp,
"format_chat_list_timestamp": _format_chat_list_timestamp,
"format_text_as_html": _format_text_as_html,
"format_response_as_html": format_response_as_html,
"asset_version": _static_asset_version(),
"chat_request_id": _new_request_id(),
}
def _chat_page_context(
request: Request,
*,
display_name: str,
model_display_name: str,
chat_available: bool,
service_status_message: str,
page_state: ChatPageState,
repository: ChatRepository | None,
) -> dict[str, object]:
context = _base_template_context(
request,
display_name=display_name,
model_display_name=model_display_name,
chat_available=chat_available,
service_status_message=service_status_message,
)
context.update(
{
"visible_chats": page_state.visible_chats,
"selected_chat": page_state.selected_chat,
"selected_chat_id": page_state.active_chat_session_id,
"chat_messages": page_state.transcript_messages,
"view_state": page_state.view_state,
"active_chat_session_id": page_state.active_chat_session_id,
"active_chat_url": (
_chat_url_path(page_state.active_chat_session_id)
if page_state.active_chat_session_id is not None
else "/"
),
"oob_swap": False,
"session_inspectability": _build_session_inspectability_view(
request,
repository=repository,
page_state=page_state,
),
}
)
return context
def _render_template_fragment(template_name: str, context: dict[str, object]) -> str:
return templates.get_template(template_name).render(context)
def _render_oob_fragment(template_name: str, context: dict[str, object]) -> str:
oob_context = dict(context)
oob_context["oob_swap"] = True
return _render_template_fragment(template_name, oob_context)
def _render_transcript_partial(context: dict[str, object]) -> str:
return _render_template_fragment("components/chat_box_content.html", context)
def _render_chat_view_updates(
context: dict[str, object],
*,
chat_session_id: int | None,
) -> str:
return "\n".join(
[
_render_oob_fragment("components/chat_view_header.html", context),
_render_oob_fragment("components/chat_list.html", context),
_render_chat_session_id_input_value(chat_session_id),
]
)
def _response_with_optional_push_url(
response: HTMLResponse,
*,
chat_session_id: int | None,
) -> HTMLResponse:
response.headers["HX-Push-Url"] = (
_chat_url_path(chat_session_id) if chat_session_id is not None else _chat_start_url_path()
)
return response
def _render_chat_page_partial_response(
context: dict[str, object],
*,
status_code: int = 200,
push_url: bool = False,
chat_session_id: int | None = None,
) -> HTMLResponse:
response = HTMLResponse(
content="\n".join(
[
_render_transcript_partial(context),
_render_chat_view_updates(
context,
chat_session_id=chat_session_id,
),
]
),
status_code=status_code,
)
if push_url:
response = _response_with_optional_push_url(response, chat_session_id=chat_session_id)
return response
def _render_chat_error_htmx_response(
request: Request,
*,
chat_harness: ChatHarness,
repository: ChatRepository,
client_id: str,
active_chat_session_id: int | None,
title: str,
body: str,
timestamp: str,
status_code: int,
) -> HTMLResponse:
if active_chat_session_id is None:
return _render_error_response(
title,
body,
timestamp,
status_code,
)
page_context = _chat_page_context(
request,
display_name=_chat_harness_display_name(chat_harness),
model_display_name=_chat_harness_model_display_name(chat_harness),
chat_available=True,
service_status_message=_chat_service_unavailable_detail(request.app),
page_state=_load_chat_page_state(
repository,
client_id=client_id,
chat_session_id=active_chat_session_id,
),
repository=repository,
)
return _response_with_optional_push_url(
_render_htmx_response(
"\n".join(
[
_render_bot_message(html.escape(body), timestamp, title, is_error=True),
_render_chat_view_updates(
page_context,
chat_session_id=active_chat_session_id,
),
]
),
status_code=status_code,
),
chat_session_id=active_chat_session_id,
)
def _render_turn_request_state_response(
request: Request,
*,
chat_harness: ChatHarness,
repository: ChatRepository,
client_id: str,
turn_request_state: ChatTurnRequestState,
timestamp: str,
) -> HTMLResponse:
active_chat_session_id = turn_request_state.turn_request.chat_session_id
if turn_request_state.turn_request.status == "completed" and _is_chat_session_active(
turn_request_state.chat_session
):
assistant_message = turn_request_state.assistant_message
if assistant_message is None: # pragma: no cover - defensive against required persistence
raise RuntimeError("Completed turn request is missing its assistant message.")
page_context = _chat_page_context(
request,
display_name=_chat_harness_display_name(chat_harness),
model_display_name=_chat_harness_model_display_name(chat_harness),
chat_available=True,
service_status_message=_chat_service_unavailable_detail(request.app),
page_state=_load_chat_page_state(
repository,
client_id=client_id,
chat_session_id=active_chat_session_id,
),
repository=repository,
)
return _response_with_optional_push_url(
_render_htmx_response(
"\n".join(
[
_render_bot_message(
format_response_as_html(assistant_message.content),
timestamp,
),
_render_chat_view_updates(
page_context,
chat_session_id=active_chat_session_id,
),
]
),
),
chat_session_id=active_chat_session_id,
)
failure_code = turn_request_state.turn_request.failure_code or "unexpected_error"
presentation = failure_presentation(failure_code)
response_chat_session_id: int | None = active_chat_session_id
if turn_request_state.turn_request.status == "conflicted" or not _is_chat_session_active(
turn_request_state.chat_session
):
response_chat_session_id = _first_visible_chat_session_id(repository, client_id=client_id)
if response_chat_session_id is None:
return _response_with_optional_push_url(
_render_error_response(
presentation.title,
presentation.body,
timestamp,
presentation.status_code,
),
chat_session_id=None,
)
return _render_chat_error_htmx_response(
request,
chat_harness=chat_harness,
repository=repository,
client_id=client_id,
active_chat_session_id=response_chat_session_id,
title=presentation.title,
body=presentation.body,
timestamp=timestamp,
status_code=presentation.status_code,
)
async def _await_turn_request_resolution(
chat_turn_service: ChatTurnService,
*,
client_id: str,
request_id: str,
timeout_seconds: float = 5.0,
) -> ChatTurnRequestState | None:
deadline = asyncio.get_running_loop().time() + timeout_seconds
state = await asyncio.to_thread(
chat_turn_service.get_turn_state,
client_id=client_id,
request_id=request_id,
)
while state is not None and state.turn_request.status == "processing":
if asyncio.get_running_loop().time() >= deadline:
return state
await asyncio.sleep(0.05)
state = await asyncio.to_thread(
chat_turn_service.get_turn_state,
client_id=client_id,
request_id=request_id,
)
return state
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Initialize dependencies at startup instead of import time."""
init_logging()
_set_startup_state(app, startup_complete=False)
logger.info("startup.begin")
settings: RuntimeSettings = app.state.settings
startup_checks = collect_startup_checks(settings)
try:
raise_for_failed_startup_checks(startup_checks)
bootstrap_database(settings.chat_database_path)
app.state.chat_repository = ChatRepository(settings.chat_database_path)
app.state.chat_harness_registry = build_chat_harness_registry(settings)
app.state.chat_harness = app.state.chat_harness_registry.default()
app.state.chat_turn_service = ChatTurnService(
app.state.chat_repository,
app.state.chat_harness_registry,
)
except StartupDiagnosticsError as exc:
for failure in exc.failures:
logger.critical("startup.failed check=%s detail=%s", failure.name, failure.detail)
raise
except StorageInitializationError as exc:
logger.critical(
"startup.failed check=storage_initialization detail=%s", str(exc), exc_info=True
)
raise StartupDiagnosticsError(
[
DiagnosticCheck(
name="storage_initialization",
ok=False,
detail=(
f"Failed to initialize chat storage at {settings.chat_database_path}. {str(exc)}"
),
)
]
) from exc
except Exception as exc:
logger.critical(
"startup.failed check=harness_initialization detail=%s", str(exc), exc_info=True
)
raise StartupDiagnosticsError(
[
DiagnosticCheck(
name="harness_initialization",
ok=False,
detail=f"Failed to initialize the chat harness. {str(exc)}",
)
]
) from exc
_set_startup_state(app, startup_complete=True)
startup_observability = ChatTurnObservability.from_harness(
app.state.chat_harness,
model=app.state.chat_harness.model if hasattr(app.state.chat_harness, "model") else None,
)
logger.info(
"startup.ready harness_key=%s harness_version=%s provider=%s model=%s harness=%s",
startup_observability.harness_key,
startup_observability.harness_version,
startup_observability.provider_name,
startup_observability.model or _chat_harness_model_display_name(app.state.chat_harness),
_chat_harness_display_name(app.state.chat_harness),
)
try:
yield
finally:
_set_startup_state(app, startup_complete=False)
if hasattr(app.state, "chat_harness_registry"):
del app.state.chat_harness_registry
if hasattr(app.state, "chat_harness"):
del app.state.chat_harness
if hasattr(app.state, "chat_turn_service"):
del app.state.chat_turn_service
if hasattr(app.state, "chat_repository"):
del app.state.chat_repository
logger.info("startup.shutdown")
def create_app(settings: RuntimeSettings | None = None) -> FastAPI:
load_project_env()
settings = settings or get_settings()
app = FastAPI(lifespan=lifespan)
app.state.settings = settings
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_allowed_origins,
allow_credentials=settings.cors_allow_credentials,
allow_methods=settings.cors_allowed_methods,
allow_headers=settings.cors_allowed_headers,
)
app.mount("/static", StaticFiles(directory=str(STATIC_DIR), check_dir=False), name="static")
def _chat_shell_context(
request: Request,
*,
client_id: str,
chat_session_id: int | None,
) -> tuple[dict[str, object], int]:
chat_available = _is_chat_service_available(request.app)
service_status_message = _chat_service_unavailable_detail(request.app)
display_name = "AI Chat"
model_display_name = "Unavailable"
page_state = ChatPageState(
visible_chats=[],
selected_chat=None,
transcript_messages=[],
view_state="start",
)
repository: ChatRepository | None = None
status_code = 200
if chat_available:
chat_harness = _get_chat_harness(request)
display_name = _chat_harness_display_name(chat_harness)
model_display_name = _chat_harness_model_display_name(chat_harness)
repository = request.app.state.chat_repository
page_state = _load_chat_page_state(
repository,
client_id=client_id,
chat_session_id=chat_session_id,
)
if page_state.view_state == "not_found":
status_code = 404
else:
logger.warning("chat.shell_unavailable detail=%s", service_status_message)
status_code = 503
return (
_chat_page_context(
request,
display_name=display_name,
model_display_name=model_display_name,
chat_available=chat_available,
service_status_message=service_status_message,
page_state=page_state,
repository=repository,
),
status_code,
)
@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
"""Render the Phase 2 start screen or redirect to the latest visible chat."""
logger.debug("home.render")
client_id, should_set_client_cookie = resolve_client_id(request)
if _is_chat_service_available(request.app):
repository = request.app.state.chat_repository
visible_chats = repository.list_visible_chats(client_id=client_id)
if visible_chats:
redirect_response = RedirectResponse(
url=request.url_for("chat_page", chat_id=visible_chats[0].id),
status_code=307,
)
return _finalize_response_with_client_cookie(
redirect_response,
client_id=client_id,
should_set_cookie=should_set_client_cookie,
)
context, status_code = _chat_shell_context(
request,
client_id=client_id,
chat_session_id=None,
)
response = templates.TemplateResponse(
request,
"index.html",
context,
status_code=status_code,
)
return _finalize_response_with_client_cookie(
response,
client_id=client_id,
should_set_cookie=should_set_client_cookie,
)
@app.get("/chats/{chat_id}", response_class=HTMLResponse)
async def chat_page(request: Request, chat_id: int):
client_id, should_set_client_cookie = resolve_client_id(request)
context, status_code = _chat_shell_context(
request,
client_id=client_id,
chat_session_id=chat_id,
)
response = templates.TemplateResponse(
request,
"index.html",
context,
status_code=status_code,
)
return _finalize_response_with_client_cookie(
response,
client_id=client_id,
should_set_cookie=should_set_client_cookie,
)
@app.get("/chat-start", response_class=HTMLResponse)
async def chat_start_page(request: Request):
client_id, should_set_client_cookie = resolve_client_id(request)
context, status_code = _chat_shell_context(
request,
client_id=client_id,
chat_session_id=None,
)
response = templates.TemplateResponse(
request,
"index.html",
context,
status_code=status_code,
)
return _finalize_response_with_client_cookie(
response,
client_id=client_id,
should_set_cookie=should_set_client_cookie,
)
@app.get("/chat-list", response_class=HTMLResponse)
async def chat_list_partial(request: Request):
client_id, should_set_client_cookie = resolve_client_id(request)
context, status_code = _chat_shell_context(
request,
client_id=client_id,
chat_session_id=None,
)
response = HTMLResponse(
content=_render_template_fragment("components/chat_list.html", context),
status_code=status_code,
)
return _finalize_response_with_client_cookie(
response,
client_id=client_id,
should_set_cookie=should_set_client_cookie,
)
@app.get("/chat-start/transcript", response_class=HTMLResponse)
async def chat_start_transcript_partial(request: Request):
client_id, should_set_client_cookie = resolve_client_id(request)
context, status_code = _chat_shell_context(
request,
client_id=client_id,
chat_session_id=None,
)
response = _render_chat_page_partial_response(
context,
status_code=status_code,
push_url=True,
chat_session_id=None,
)
return _finalize_response_with_client_cookie(
response,
client_id=client_id,
should_set_cookie=should_set_client_cookie,
)
@app.get("/chats/{chat_id}/transcript", response_class=HTMLResponse)
async def chat_transcript_partial(request: Request, chat_id: int):
client_id, should_set_client_cookie = resolve_client_id(request)
context, status_code = _chat_shell_context(
request,
client_id=client_id,
chat_session_id=chat_id,
)
response = _render_chat_page_partial_response(
context,