Coverage for app / router / app / conversations / router.py: 97%

68 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1from uuid import UUID 

2from typing import Any 

3 

4from fastapi import APIRouter, Depends, HTTPException, Path, Query, status 

5from fastapi.responses import Response 

6from sqlalchemy.orm import Session 

7 

8from app.dependency.base import get_db 

9from app.dependency.user.context import get_current_user 

10from app.db.postgres.enums import MessageEnum 

11from app.db.postgres.models import ChatMessage, User 

12from app.services import documents as documents_service 

13from app.services import usage as usage_service 

14from app.util import document_images 

15import app.router.app.conversations.transformers as conversations_transformers 

16from app.router.app.conversations.models import ( 

17 ConversationMessageRead, 

18 ConversationRead, 

19) 

20from app.services.decisions import outcomes 

21 

22import logging 

23 

24logger = logging.getLogger(__name__) 

25 

26conversation_router = APIRouter( 

27 prefix="/conversations", 

28 tags=["App - Conversations"], 

29) 

30 

31 

32@conversation_router.get( 

33 "", 

34 response_model=list[ConversationRead], 

35) 

36def list_conversations( 

37 agent_id: UUID | None = Query(None), 

38 ai_model_id: UUID | None = Query(None), 

39 workspace: str | None = Query(None), 

40 db: Session = Depends(get_db), 

41 current_user: User = Depends(get_current_user), 

42): 

43 """List conversations owned by the current user, optionally filtered by 

44 agent or model — and by ``workspace``, the one they were had in. A 

45 conversation stays its person's wherever it was had.""" 

46 ws = None 

47 if workspace: 

48 from app.services import workspace as workspace_service 

49 

50 ws = workspace_service.resolve(db, workspace, current_user) 

51 return _with_verdicts( 

52 db, 

53 conversations_transformers.list_conversations( 

54 db=db, 

55 owner_user_id=current_user.id, 

56 agent_id=agent_id, 

57 ai_model_id=ai_model_id, 

58 workspace=ws, 

59 ), 

60 ) 

61 

62 

63@conversation_router.get( 

64 "/{conversation_id}", 

65 response_model=ConversationRead, 

66) 

67def get_conversation( 

68 conversation_id: UUID, 

69 db: Session = Depends(get_db), 

70 current_user: User = Depends(get_current_user), 

71): 

72 """Get a single conversation by ID, scoped to the current user.""" 

73 conversation = conversations_transformers.get_conversation( 

74 db=db, 

75 conversation_id=conversation_id, 

76 owner_user_id=current_user.id, 

77 ) 

78 return _with_verdicts(db, [conversation])[0] 

79 

80 

81def _with_verdicts(db: Session, conversations: list) -> list[ConversationRead]: 

82 """Each conversation as served, every answer with its turn's verdict and 

83 what it cost — validated from the rows (every declared field), then given 

84 verdicts and costs read in one query each.""" 

85 served = [ConversationRead.model_validate(c) for c in conversations] 

86 turns = [ 

87 m.invocation_id for c in served for m in c.messages if m.role == "assistant" 

88 ] 

89 verdicts = outcomes.latest(db, turns) 

90 costs = usage_service.turn_costs(db, turns) 

91 

92 def _answer(m: ConversationMessageRead) -> ConversationMessageRead: 

93 if m.role != "assistant": 

94 return m 

95 update: dict = {} 

96 if m.invocation_id in verdicts: 

97 update["verdict"] = verdicts[m.invocation_id].verdict 

98 cost = costs.get(m.invocation_id) 

99 if cost is not None: 

100 update["cost_usd"] = ( 

101 float(cost.cost_usd) if cost.cost_usd is not None else None 

102 ) 

103 update["unpriced_calls"] = cost.unpriced_calls 

104 return m.model_copy(update=update) if update else m 

105 

106 out: list[ConversationRead] = [] 

107 for c in served: 

108 messages = [_answer(m) for m in c.messages] 

109 priced = [m.cost_usd for m in messages if m.cost_usd is not None] 

110 out.append( 

111 c.model_copy( 

112 update={ 

113 "messages": messages, 

114 "cost_usd": sum(priced) if priced else None, 

115 "unpriced_calls": sum(m.unpriced_calls for m in messages), 

116 } 

117 ) 

118 ) 

119 return out 

120 

121 

122def _assistant_message( 

123 conversation_id: UUID, message_id: UUID, db: Session, current_user: User 

124) -> tuple[Any, ChatMessage]: 

125 """The caller's conversation and one of its answers, else 404. 

126 

127 Only an answer's documents went through svc-ai's artifact guard, which 

128 keeps a document exactly what ``render_document`` made; a document a 

129 person typed into their own message is text, never a document to render. 

130 """ 

131 conversation = conversations_transformers.get_conversation( 

132 db=db, conversation_id=conversation_id, owner_user_id=current_user.id 

133 ) 

134 message = db.get(ChatMessage, message_id) 

135 if ( 

136 message is None 

137 or message.conversation_id != conversation.id 

138 or message.role != MessageEnum.Role.ASSISTANT 

139 ): 

140 raise HTTPException( 

141 status_code=status.HTTP_404_NOT_FOUND, detail="Message not found." 

142 ) 

143 return conversation, message 

144 

145 

146@conversation_router.get( 

147 "/{conversation_id}/messages/{message_id}/documents/{index}.pdf", 

148 response_class=Response, 

149 responses={200: {"content": {"application/pdf": {}}}}, 

150) 

151def download_message_document( 

152 conversation_id: UUID, 

153 message_id: UUID, 

154 index: int, 

155 db: Session = Depends(get_db), 

156 current_user: User = Depends(get_current_user), 

157): 

158 """The ``index``-th document in an answer, as a PDF. 

159 

160 Rendered from the stored message — the ```document fence svc-ai's 

161 ``render_document`` tool put there — never from anything sent with the 

162 request. Only the conversation's owner can download it. 

163 """ 

164 conversation, message = _assistant_message( 

165 conversation_id, message_id, db, current_user 

166 ) 

167 fences = documents_service.document_fences(message.content) 

168 if not 0 <= index < len(fences): 

169 raise HTTPException( 

170 status_code=status.HTTP_404_NOT_FOUND, 

171 detail="This message has no such document.", 

172 ) 

173 return documents_service.pdf_response( 

174 fences[index], 

175 footer=documents_service.message_footer(conversation, message), 

176 when=message.sent_at, 

177 ) 

178 

179 

180@conversation_router.get( 

181 "/{conversation_id}/messages/{message_id}/images/{asset}", 

182 response_class=Response, 

183 responses={200: {"content": {"image/png": {}, "image/jpeg": {}}}}, 

184) 

185def message_document_image( 

186 conversation_id: UUID, 

187 message_id: UUID, 

188 asset: str = Path(pattern=document_images.ASSET_ID.pattern), 

189 db: Session = Depends(get_db), 

190 current_user: User = Depends(get_current_user), 

191): 

192 """An image a document in an answer shows: the copy svc-ai stored when it 

193 made the document, so the image's own site never sees who is reading. 

194 Only an image a document in that answer names, for the conversation's 

195 owner. The URL names the bytes (their hash), so it never changes.""" 

196 _, message = _assistant_message(conversation_id, message_id, db, current_user) 

197 return documents_service.image_response( 

198 documents_service.document_fences(message.content), asset 

199 )