Skip to content

Commit 879bf3c

Browse files
committed
Refactor session validation to use overloaded get_session! in AiAssistant context
1 parent 9d44090 commit 879bf3c

File tree

2 files changed

+19
-10
lines changed

2 files changed

+19
-10
lines changed

lib/lightning/ai_assistant/ai_assistant.ex

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,24 @@ defmodule Lightning.AiAssistant do
274274
end
275275
end
276276

277+
@doc """
278+
Gets a session scoped to a specific job.
279+
280+
Returns the session only if it belongs to the given job.
281+
Raises `Ecto.NoResultsError` if the session doesn't exist or doesn't belong to the job.
282+
283+
## Examples
284+
285+
iex> get_session!(session_id, job)
286+
%ChatSession{}
287+
"""
288+
def get_session!(session_id, %Job{id: job_id}) do
289+
ChatSession
290+
|> where([s], s.id == ^session_id and s.job_id == ^job_id)
291+
|> Repo.one!()
292+
|> Repo.preload([:user, messages: {session_messages_query(), :user}])
293+
end
294+
277295
def get_session(id) do
278296
case Repo.get(ChatSession, id) do
279297
nil ->

lib/lightning_web/live/ai_assistant/modes/job_code.ex

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -100,16 +100,7 @@ defmodule LightningWeb.Live.AiAssistant.Modes.JobCode do
100100
@impl true
101101
@spec get_session!(assigns()) :: session()
102102
def get_session!(%{chat_session_id: session_id, selected_job: job} = assigns) do
103-
session = AiAssistant.get_session!(session_id)
104-
105-
# Validate that the session belongs to the selected job
106-
if session.job_id != job.id do
107-
raise Ecto.NoResultsError,
108-
queryable: Lightning.AiAssistant.ChatSession,
109-
message: "Chat session #{session_id} does not belong to job #{job.id}"
110-
end
111-
112-
session
103+
AiAssistant.get_session!(session_id, job)
113104
|> AiAssistant.put_expression_and_adaptor(job.body, job.adaptor)
114105
|> maybe_add_run_logs(job, assigns[:follow_run])
115106
end

0 commit comments

Comments
 (0)