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.

fix(tasks): bootstrap desktop cloud task dependencies (#81760)

Alessandro Pogliaghif13ec1585508
diff --git a/products/desktop/AGENTS.md b/products/desktop/AGENTS.md
index ac357c1c8544..9e27437fd057 100644
--- a/products/desktop/AGENTS.md
+++ b/products/desktop/AGENTS.md
@@ -209,6 +209,7 @@ await boot(container);
## Commands
- `pnpm install`: install dependencies.
+- `pnpm bootstrap:cloud-task`: link dependencies from the prebaked pnpm store without running unrelated app install hooks, then build the packages required before scoped typechecks in cloud tasks.
- `pnpm dev`: run agent watch and desktop app.
- `pnpm build`: build all packages.
- `pnpm typecheck`: typecheck all packages.
diff --git a/products/desktop/package.json b/products/desktop/package.json
index df267aaf6080..6f15b9499898 100644
--- a/products/desktop/package.json
+++ b/products/desktop/package.json
@@ -11,6 +11,7 @@
"preinstall": "node scripts/enforce-pnpm.mjs",
"postinstall": "bash scripts/ensure-phrocs.sh --update",
"setup": "bash apps/code/bin/setup",
+ "bootstrap:cloud-task": "pnpm install --frozen-lockfile --prefer-offline --ignore-scripts && pnpm build:deps",
"prepare": "husky",
"dev": "pnpm build:deps && bash scripts/ensure-phrocs.sh && bin/phrocs --config mprocs.yaml",
"dev:mprocs": "pnpm build:deps && mprocs",
diff --git a/products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh b/products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh
index fabd4d3b0288..b6047390df19 100644
--- a/products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh
+++ b/products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh
@@ -185,6 +185,12 @@ pnpm fetch --frozen-lockfile
# which runs scripts as usual. node_modules itself is discarded with the checkout.
pnpm install --prefer-offline --frozen-lockfile --ignore-scripts
+log "smoke-testing Desktop cloud-task bootstrap"
+# Exercise the same branch-correct preparation that task provisioning runs after
+# checkout. This keeps the nightly publish from succeeding when a fresh dev-stack
+# task cannot resolve the built workspace exports needed by @posthog/ui.
+(cd products/desktop && pnpm bootstrap:cloud-task && pnpm --filter @posthog/ui --filter code typecheck)
+
log "installing playwright chromium (+ system deps)"
# Storybook builds and screenshot runs drive Playwright's Chromium. Browsers land in
# ~/.cache/ms-playwright, outside the checkout; --with-deps apt-installs the shared
diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.py
index 50b145b1f44a..eae0c481e9af 100644
--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py
+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py
@@ -23,6 +23,7 @@ from temporalio.common import RetryPolicy
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.oauth import PosthogMcpScopes
+from products.tasks.backend.constants import DEV_STACK_IMAGE_NAME
from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.logic.services.sandbox import is_public_sandbox_repo
from products.tasks.backend.temporal.constants import (
@@ -141,6 +142,8 @@ SHUTDOWN_REJECTION_DETAIL = "child_shutting_down"
FOLLOWUP_SOURCE_USER = "user"
FOLLOWUP_SOURCE_CI = "ci"
+_DESKTOP_BOOTSTRAP_ACTIVITY_TIMEOUT = timedelta(minutes=20)
+
@dataclass
class ExecuteSandboxInput:
@@ -1101,6 +1104,9 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
checkout_repository = self.context.repositories[0] if len(self.context.repositories) == 1 else None
will_checkout = bool(checkout_repository and prepared.branch and has_clone_credentials)
+ def prepares_desktop(repository: str) -> bool:
+ return self.context.custom_image_name == DEV_STACK_IMAGE_NAME and repository.casefold() == "posthog/posthog"
+
if will_clone:
await self._emit_progress("clone", "in_progress", "Cloning repository", "setup")
await asyncio.gather(
@@ -1114,7 +1120,11 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
github_token=prepared.github_token,
shallow_clone=prepared.shallow_clone,
),
- start_to_close_timeout=timedelta(minutes=5),
+ start_to_close_timeout=(
+ _DESKTOP_BOOTSTRAP_ACTIVITY_TIMEOUT
+ if prepares_desktop(repository)
+ else timedelta(minutes=5)
+ ),
retry_policy=RetryPolicy(maximum_attempts=3),
)
for repository in repositories_to_clone
@@ -1128,6 +1138,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
if will_checkout and not is_resume:
assert checkout_repository is not None
assert prepared.branch is not None
+ prepares_repository_desktop = prepares_desktop(checkout_repository)
branch_label_active = f"Checking out branch {prepared.branch}"
branch_label_done = f"Checked out branch {prepared.branch}"
await self._emit_progress("checkout", "in_progress", branch_label_active, "setup")
@@ -1142,7 +1153,9 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
shallow_clone=prepared.shallow_clone,
used_snapshot=used_snapshot,
),
- start_to_close_timeout=timedelta(minutes=5),
+ start_to_close_timeout=(
+ _DESKTOP_BOOTSTRAP_ACTIVITY_TIMEOUT if prepares_repository_desktop else timedelta(minutes=5)
+ ),
retry_policy=RetryPolicy(maximum_attempts=3),
)
await self._emit_progress("checkout", "completed", branch_label_done, "setup")
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
index a063edaca334..cd0abd3d5a58 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -9,6 +9,7 @@ from django.conf import settings
from django.utils import timezone
from temporalio import activity
+from temporalio.exceptions import ApplicationError
from posthog.models.user_integration import ReauthorizationRequired
from posthog.temporal.common.utils import asyncify
@@ -35,9 +36,11 @@ from products.tasks.backend.logic.services.connection_token import (
from products.tasks.backend.logic.services.sandbox import (
ExecutionResult,
Sandbox,
+ SandboxBase,
SandboxConfig,
SandboxTemplate,
get_sandbox_class,
+ sandbox_repo_path,
)
from products.tasks.backend.logic.services.sandbox_usage import measure_sandbox_cpu_usage, open_sandbox_session
from products.tasks.backend.models import SandboxSnapshot, Task, TaskRun
@@ -151,6 +154,35 @@ class CheckoutBranchInSandboxInput:
used_snapshot: bool
+def _prepare_posthog_desktop_cloud_task(ctx: TaskProcessingContext, sandbox: SandboxBase, repository: str) -> None:
+ """Build Desktop workspace exports from the task's checked-out source.
+
+ The dev-stack image warms pnpm's content-addressed store but deliberately does
+ not retain checkout-specific node_modules or dist directories. Prepare only the
+ internal PostHog checkout that uses that image, after its final branch is in place.
+ """
+ if (
+ ctx.custom_image_name != DEV_STACK_IMAGE_NAME
+ or repository.casefold() != "posthog/posthog"
+ or sandbox.config.image_fallback
+ ):
+ return
+
+ repo_path = f"{sandbox_repo_path(repository)}/products/desktop"
+ emit_agent_log(ctx.run_id, "debug", "Preparing Desktop workspace dependencies")
+ result = sandbox.execute(
+ f"cd {shlex.quote(repo_path)} && pnpm bootstrap:cloud-task",
+ timeout_seconds=10 * 60,
+ )
+ if result.exit_code != 0:
+ output = (result.stderr or result.stdout)[-2_000:]
+ raise ApplicationError(
+ f"Failed to prepare Desktop workspace: {output}",
+ type="DesktopCloudTaskBootstrapError",
+ non_retryable=True,
+ )
+
+
@dataclass
class InjectFreshTokensOnResumeInput:
context: TaskProcessingContext
@@ -823,6 +855,13 @@ def clone_repository_in_sandbox(input: CloneRepositoryInSandboxInput) -> CloneRe
if clone_result.exit_code != 0:
raise RuntimeError(f"Failed to clone repository {input.repository}: {clone_result.stderr}")
+ # A fresh single-repository run checks its requested branch out in the next
+ # activity. Resumes clone that branch directly, and multi-repo runs do not run
+ # the checkout activity, so prepare them here once their final source exists.
+ will_checkout_later = len(ctx.repositories) == 1 and bool(ctx.branch) and not is_resume
+ if not will_checkout_later:
+ _prepare_posthog_desktop_cloud_task(ctx, sandbox, input.repository)
+
return CloneRepositoryInSandboxOutput(clone_ms=clone_timer.elapsed_ms)
@@ -908,6 +947,8 @@ def checkout_branch_in_sandbox(input: CheckoutBranchInSandboxInput) -> CheckoutB
logger.warning("Branch checkout failed", extra={"branch": input.branch, "stderr": result.stderr})
raise RuntimeError(f"Failed to checkout branch {input.branch}")
+ _prepare_posthog_desktop_cloud_task(ctx, sandbox, input.repository)
+
return CheckoutBranchInSandboxOutput(checkout_ms=checkout_timer.elapsed_ms)
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
index c5153d9aa5c8..b6abdcf16ccd 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
@@ -18,12 +18,87 @@ from products.tasks.backend.temporal.process_task.activities.provision_sandbox i
CreateSandboxForRepositoryInput,
CreateSandboxForRepositoryOutput,
PrepareSandboxForRepositoryOutput,
+ _prepare_posthog_desktop_cloud_task,
_sandbox_image_kind,
clone_repository_in_sandbox,
create_sandbox_for_repository,
)
+def _context_for_desktop_bootstrap(*, image_name: str | None = "posthog-dev-stack") -> TaskProcessingContext:
+ return TaskProcessingContext(
+ task_id="task-id",
+ run_id="run-id",
+ team_id=1,
+ team_uuid="team-uuid",
+ organization_id="organization-id",
+ github_integration_id=123,
+ repository="posthog/posthog",
+ distinct_id="distinct-id",
+ state={},
+ custom_image_name=image_name,
+ )
+
+
+def test_prepares_desktop_workspace_for_posthog_dev_stack_task(mocker):
+ sandbox = mocker.Mock()
+ sandbox.config.image_fallback = None
+ sandbox.execute.return_value = ExecutionResult(stdout="", stderr="", exit_code=0)
+
+ _prepare_posthog_desktop_cloud_task(
+ _context_for_desktop_bootstrap(),
+ sandbox,
+ "PostHog/posthog",
+ )
+
+ sandbox.execute.assert_called_once_with(
+ "cd /tmp/workspace/repos/posthog/posthog/products/desktop && pnpm bootstrap:cloud-task",
+ timeout_seconds=10 * 60,
+ )
+
+
+ "image_name, repository, image_fallback",
+ [
+ (None, "posthog/posthog", None),
+ ("team-image", "posthog/posthog", None),
+ ("posthog-dev-stack", "posthog/posthog-js", None),
+ ("posthog-dev-stack", "posthog/posthog", "custom image -> base image"),
+ ],
+)
+def test_skips_desktop_workspace_preparation_for_other_images_repositories_and_fallbacks(
+ mocker, image_name, repository, image_fallback
+):
+ sandbox = mocker.Mock()
+ sandbox.config.image_fallback = image_fallback
+
+ _prepare_posthog_desktop_cloud_task(
+ _context_for_desktop_bootstrap(image_name=image_name),
+ sandbox,
+ repository,
+ )
+
+ sandbox.execute.assert_not_called()
+
+
+def test_desktop_workspace_preparation_failure_is_non_retryable(mocker):
+ from temporalio.exceptions import ApplicationError
+
+ sandbox = mocker.Mock()
+ sandbox.config.image_fallback = None
+ sandbox.execute.return_value = ExecutionResult(stdout="", stderr="build failed", exit_code=1)
+
+ with pytest.raises(ApplicationError) as error:
+ _prepare_posthog_desktop_cloud_task(
+ _context_for_desktop_bootstrap(),
+ sandbox,
+ "posthog/posthog",
+ )
+
+ assert error.value.non_retryable is True
+ assert "build failed" in str(error.value)
+
+
@pytest.mark.parametrize(
"image_source, custom_image_name, expected",
[
diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
index f2817dca76b7..68bea2710fc6 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -1697,6 +1697,7 @@ class TestProcessTaskWorkflowUnit:
workflow._context = _build_context(
github_integration_id=123,
state={"repositories": ["posthog/posthog", "posthog/code"]},
+ custom_image_name="posthog-dev-stack",
)
prepared = PrepareSandboxForRepositoryOutput(
sandbox_name="sandbox-name",
@@ -1718,6 +1719,7 @@ class TestProcessTaskWorkflowUnit:
connect_token="connect-token",
)
cloned: list[str] = []
+ clone_options: dict[str, dict[str, Any]] = {}
async def fake_execute_activity(activity_fn: Any, *args: Any, **kwargs: Any) -> Any:
if activity_fn is prepare_sandbox_for_repository:
@@ -1726,6 +1728,7 @@ class TestProcessTaskWorkflowUnit:
return created
if activity_fn is clone_repository_in_sandbox:
cloned.append(args[0].repository)
+ clone_options[args[0].repository] = kwargs
return None
if activity_fn is emit_progress_activity:
return None
@@ -1737,8 +1740,59 @@ class TestProcessTaskWorkflowUnit:
result = await workflow._get_sandbox_for_repository()
assert cloned == ["posthog/posthog", "posthog/code"]
+ assert clone_options["posthog/posthog"]["start_to_close_timeout"] == timedelta(minutes=20)
+ assert clone_options["posthog/posthog"]["retry_policy"].maximum_attempts == 3
+ assert clone_options["posthog/code"]["start_to_close_timeout"] == timedelta(minutes=5)
+ assert clone_options["posthog/code"]["retry_policy"].maximum_attempts == 3
assert result.clone_ms is None
+ async def test_get_sandbox_for_repository_uses_desktop_budget_for_snapshot_checkout(self, monkeypatch):
+ workflow = ProcessTaskWorkflow()
+ workflow._context = _build_context(
+ github_integration_id=123,
+ repository="posthog/posthog",
+ custom_image_name="posthog-dev-stack",
+ )
+ prepared = PrepareSandboxForRepositoryOutput(
+ sandbox_name="sandbox-name",
+ repository="posthog/posthog",
+ github_token="ghs_token",
+ branch="feature-branch",
+ environment_variables={},
+ snapshot_id="repo-snapshot-id",
+ snapshot_external_id=None,
+ used_snapshot=True,
+ should_create_snapshot=False,
+ shallow_clone=True,
+ image_source="repository_snapshot",
+ image_source_label="repository snapshot x",
+ )
+ created = CreateSandboxForRepositoryOutput(
+ sandbox_id="sandbox-123",
+ sandbox_url="https://sandbox.example",
+ connect_token="connect-token",
+ )
+ checkout_options: dict[str, Any] = {}
+
+ async def fake_execute_activity(activity_fn: Any, *args: Any, **kwargs: Any) -> Any:
+ if activity_fn is prepare_sandbox_for_repository:
+ return prepared
+ if activity_fn is create_sandbox_for_repository:
+ return created
+ if activity_fn is checkout_branch_in_sandbox:
+ checkout_options.update(kwargs)
+ return None
+ if activity_fn is emit_progress_activity:
+ return None
+ raise AssertionError(f"Unexpected activity call: {activity_fn}")
+
+ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)
+
+ await workflow._get_sandbox_for_repository()
+
+ assert checkout_options["start_to_close_timeout"] == timedelta(minutes=20)
+ assert checkout_options["retry_policy"].maximum_attempts == 3
+
async def test_overlap_releases_agent_after_primary_clone_and_materializes_failed_secondary(self, monkeypatch):
workflow = ProcessTaskWorkflow()
workflow._context = _build_context(
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index ca47ad145985..204934b8a0af 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -16,7 +16,7 @@ from temporalio.workflow import ParentClosePolicy
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.oauth import PosthogMcpScopes
-from products.tasks.backend.constants import SNAPSHOT_KIND_FILESYSTEM
+from products.tasks.backend.constants import DEV_STACK_IMAGE_NAME, SNAPSHOT_KIND_FILESYSTEM
from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.logic.services.sandbox import is_public_sandbox_repo
from products.tasks.backend.temporal.create_snapshot.workflow import CreateSnapshotForRepositoryInput
@@ -270,6 +270,10 @@ _PATCH_ID_EXCLUDE_WIZARD_FROM_BOOT_TOTAL = "tasks-exclude-wizard-from-boot-total
# Preserve that command order on replay while new runs can release it after the primary clone.
_PATCH_ID_AGENT_READY_AFTER_PRIMARY_CLONE = "tasks-agent-ready-after-primary-clone"
+# Desktop preparation links a large workspace and writes compiled package outputs. Give
+# that non-idempotent work one attempt with a budget larger than its inner 10-minute cap.
+_DESKTOP_BOOTSTRAP_ACTIVITY_TIMEOUT = timedelta(minutes=20)
+
# #60923 dropped the redundant slack post that ran immediately after sandbox
# provisioning — between `_get_sandbox_for_repository` and the agent-start
# progress emit. Pre-rollout histories scheduled a `post_slack_update` activity
@@ -1461,6 +1465,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):
checkout_repository = self.context.repositories[0] if len(self.context.repositories) == 1 else None
will_checkout = bool(checkout_repository and prepared.branch and has_clone_credentials)
+ def prepares_desktop(repository: str) -> bool:
+ return self.context.custom_image_name == DEV_STACK_IMAGE_NAME and repository.casefold() == "posthog/posthog"
+
overlap = bool(self.context.overlap_clone_boot_enabled and will_clone)
boot_path = "overlap" if overlap else "classic"
launch_ms: int | None = None
@@ -1483,6 +1490,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
async def clone_repository(
repository: str,
) -> tuple[CloneRepositoryInSandboxOutput | None, bool, bool]:
+ prepares_repository_desktop = prepares_desktop(repository)
try:
clone_output = await workflow.execute_activity(
clone_repository_in_sandbox,
@@ -1493,7 +1501,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):
github_token=prepared.github_token,
shallow_clone=prepared.shallow_clone,
),
- start_to_close_timeout=timedelta(minutes=5),
+ start_to_close_timeout=(
+ _DESKTOP_BOOTSTRAP_ACTIVITY_TIMEOUT if prepares_repository_desktop else timedelta(minutes=5)
+ ),
retry_policy=RetryPolicy(maximum_attempts=3),
)
except Exception as error:
@@ -1567,6 +1577,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
if will_checkout and checkout_repository not in failed_repositories and not is_resume:
assert checkout_repository is not None
assert prepared.branch is not None
+ prepares_repository_desktop = prepares_desktop(checkout_repository)
branch_label_active = f"Checking out branch {prepared.branch}"
branch_label_done = f"Checked out branch {prepared.branch}"
await self._emit_progress("checkout", "in_progress", branch_label_active, "setup")
@@ -1581,7 +1592,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):
shallow_clone=prepared.shallow_clone,
used_snapshot=used_snapshot,
),
- start_to_close_timeout=timedelta(minutes=5),
+ start_to_close_timeout=(
+ _DESKTOP_BOOTSTRAP_ACTIVITY_TIMEOUT if prepares_repository_desktop else timedelta(minutes=5)
+ ),
retry_policy=RetryPolicy(maximum_attempts=3),
)
# Pre-rollout histories (and mocked tests) recorded a null result here.