Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

5.8 KB
Raw Blame
from __future__ import annotations

from collections.abc import Iterable
from typing import Any
from uuid import UUID

from django.db import transaction

from posthog.models.team.team import Team
from posthog.models.user import User

from products.tasks.backend.facade.contracts import CreatedTaskDTO, TaskRunDTO

from .constants import MAX_OPEN_RUNS_PER_OWNER
from .models import PlaygroundChat, PlaygroundTurn
from .sandbox import (
    SandboxPollStatus,
    SandboxRunInProgress,
    SandboxRunLimitReached,
    _title_for,
    load_sandbox_run,
    lock_owner_admission,
    open_sandbox_task_ids,
    resume_sandbox_run,
    start_sandbox_run,
)


def create_playground_chat(*, team: Team, user: User) -> PlaygroundChat:
    return PlaygroundChat.objects.create(team=team, created_by=user, title="")


def serialize_playground_chat_list_item(chat: PlaygroundChat, *, has_open_turn: bool) -> dict[str, Any]:
    return {
        "id": chat.id,
        "title": chat.title,
        "created_at": chat.created_at,
        "updated_at": chat.updated_at,
        "has_open_turn": has_open_turn,
    }


def serialize_playground_chat_list(chats: Iterable[PlaygroundChat], *, team_id: int, user_id: int) -> list[dict]:
    chats = list(chats)
    open_task_ids = open_sandbox_task_ids(team_id=team_id, user_id=user_id)
    open_chat_ids = (
        set(
            PlaygroundTurn.objects.for_team(team_id)
            .filter(chat_id__in=[chat.id for chat in chats], task_id__in=open_task_ids)
            .values_list("chat_id", flat=True)
        )
        if open_task_ids and chats
        else set()
    )
    return [serialize_playground_chat_list_item(chat, has_open_turn=chat.id in open_chat_ids) for chat in chats]


def serialize_playground_chat(*, chat: PlaygroundChat, user_id: int) -> dict[str, Any]:
    turns = PlaygroundTurn.objects.filter(chat=chat).order_by("position")
    serialized_turns = [serialize_playground_turn(turn, user_id=user_id) for turn in turns]
    has_open_turn = any(
        turn["run"] is not None and turn["run"]["status"] == SandboxPollStatus.RUNNING for turn in serialized_turns
    )
    return {
        **serialize_playground_chat_list_item(chat, has_open_turn=has_open_turn),
        "turns": serialized_turns,
    }


def serialize_playground_turn(turn: PlaygroundTurn, *, user_id: int) -> dict[str, Any]:
    run = load_sandbox_run(
        task_id=str(turn.task_id),
        team_id=turn.team_id,
        user_id=user_id,
        run_id=None if turn.run_id is None else str(turn.run_id),
    )
    return {
        "id": turn.id,
        "question": turn.question,
        "task_id": turn.task_id,
        "position": turn.position,
        "run": run,
        "error": None if run is not None else "Couldn't load this answer. Try again.",
    }


def ask_playground_chat(*, chat: PlaygroundChat, team: Team, user_id: int, question: str) -> dict[str, Any]:
    def admit_one_run_per_chat() -> None:
        # The owner lock serializes this person's asks, so the chat check and the owner cap see every open run.
        lock_owner_admission(chat.team_id, user_id)
        open_task_ids = open_sandbox_task_ids(team_id=chat.team_id, user_id=user_id)
        if (
            open_task_ids
            and PlaygroundTurn.objects.for_team(chat.team_id).filter(chat=chat, task_id__in=open_task_ids).exists()
        ):
            raise SandboxRunInProgress()
        if len(open_task_ids) >= MAX_OPEN_RUNS_PER_OWNER:
            raise SandboxRunLimitReached()

    def record_turn(created: CreatedTaskDTO) -> None:
        run = created.latest_run
        if run is None:
            raise RuntimeError("Sandbox task was created without a run")
        last = PlaygroundTurn.objects.filter(chat=chat).order_by("-position").values_list("position", flat=True).first()
        PlaygroundTurn.objects.create(
            team_id=chat.team_id,
            chat=chat,
            question=question,
            task_id=created.task_id,
            run_id=run.id,
            position=0 if last is None else last + 1,
        )
        update_fields = ["updated_at"]
        if chat.task_id != created.task_id:
            chat.task_id = created.task_id
            update_fields.append("task_id")
        if not chat.title:
            chat.title = _title_for(question)
            update_fields.append("title")
        chat.save(update_fields=update_fields)

    def remember_current_run(previous: TaskRunDTO) -> None:
        PlaygroundTurn.objects.filter(chat=chat, task_id=previous.task_id, run_id__isnull=True).update(
            run_id=previous.id
        )

    def task_for_next_run() -> UUID | None:
        chat.refresh_from_db(fields=["task_id", "title"])
        latest_task_id = (
            PlaygroundTurn.objects.filter(chat=chat).order_by("-position").values_list("task_id", flat=True).first()
        )
        # An older process can append a turn on a new task and leave chat.task_id behind.
        if latest_task_id is not None and latest_task_id != chat.task_id:
            chat.task_id = latest_task_id
            chat.save(update_fields=["task_id", "updated_at"])
        return chat.task_id

    def already_admitted() -> None:
        return

    with transaction.atomic():
        admit_one_run_per_chat()
        task_id = task_for_next_run()
        if task_id is None:
            start_sandbox_run(
                team=team,
                user_id=user_id,
                question=question,
                admit=already_admitted,
                on_admitted=record_turn,
            )
        else:
            resume_sandbox_run(
                team=team,
                user_id=user_id,
                task_id=task_id,
                question=question,
                admit=already_admitted,
                on_admitted=record_turn,
                before_create=remember_current_run,
            )
    return serialize_playground_chat(chat=chat, user_id=user_id)