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.

feat(context-layer): add a Dreams tab to the context page (#90370)

Peter Kirkhamda93d8bbd71e
diff --git a/products/context_layer/README.md b/products/context_layer/README.md
index edac3d014cfc..9af16cc31a65 100644
--- a/products/context_layer/README.md
+++ b/products/context_layer/README.md
@@ -45,3 +45,5 @@ During enablement, malformed wiki-link brackets in legacy Space context are enco
## Dreaming
A nightly Temporal coordinator (`context-layer-dream-coordinator`, 03:00 UTC) dispatches one cloud task per enabled organization using GPT-5.6 Sol with high reasoning. Each tick dispatches up to 1,000 due organizations, least-recently-dreamt first. Before dispatch, deterministic reconciliation creates a project-scoped page for every public Space and regenerates the project and Space indexes. The run works unlocked on its own clone all night, on a dated `dream/<YYYY-MM-DD>` branch, and lands it through the commits endpoint as one two-parent merge commit (`dream: <date>`): `git log --merges` lists the dreams, and `git revert -m 1` undoes a whole night. The skills live in `products/context_layer/skills/` and source context from completed tasks and loops, merged PRs, and instrumented events. Activity pagination follows cursors until the window or budget is exhausted: up to 100 newest items total per Space across channel-scoped sources, and 100 per organization-wide source. Each run also rechecks completed tasks from the previous seven days so work that finishes after an earlier review is not lost behind the incremental cursor. A first dream includes empty public Space pages in its scan and fills them only when their channels have qualifying activity in the seed window. Dream branches may change sourced content pages only; the server rejects changes to repository instructions, generated indexes, scripts, or Space paths. A per-org failure streak pauses a lane after repeated dispatch failures (`ContextLayerConfig.dreaming_paused`).
+
+The Desktop context page reads the same history back: `GET context_layer/dreams/` returns the active dreaming task and lists the landed runs (subject, summary, page-change counts), while `GET context_layer/dreams/<sha>/` returns one run's per-file unified patches. Landed runs are derived from merge commits at request time and cached per head sha; active task state stays live.
diff --git a/products/context_layer/backend/dreams.py b/products/context_layer/backend/dreams.py
new file mode 100644
index 000000000000..51157803f6ed
--- /dev/null
+++ b/products/context_layer/backend/dreams.py
@@ -0,0 +1,278 @@
+"""Read dream runs out of the wiki's git history.
+
+A dreaming run lands as one two-parent merge commit whose subject is
+`dream: <YYYY-MM-DD>` and whose body is the run summary, so the history itself
+is the record: `git log --merges` lists the runs and `git diff <merge>^1
+<merge>` shows what the night changed. Lists are cached per head sha (a new
+dream moves the head), and one run's diff is immutable within that history, so
+its cache entry is keyed by both the head and merge shas.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+
+from posthog.dataclasses import frozen
+from posthog.utils import get_safe_cache, safe_cache_set
+
+from products.context_layer.backend import store
+from products.tasks.backend.facade import api as tasks_facade
+
+CACHE_TTL_SECONDS = 24 * 60 * 60
+DREAM_SUBJECT_PREFIX = "dream: "
+DREAM_AI_STAGE = "context-layer-dream"
+# A dream touches content pages only; these caps keep one oversized night from
+# ballooning the API response. Files past the cap are still listed, with their
+# patch replaced by a truncation note.
+DREAM_MAX_FILES = 500
+DREAM_MAX_PATCH_BYTES_PER_FILE = 100_000
+
+# git log record and field separators.
+_CHANGE_SEPARATOR = "\x1d"
+_RECORD_SEPARATOR = "\x1e"
+_FIELD_SEPARATOR = "\x1f"
+
+
+class DreamNotFoundError(store.ContextLayerStoreError):
+ pass
+
+
+@frozen
+class DreamRun:
+ sha: str
+ date: str
+ committed_at: datetime
+ summary: str
+ pages_added: int
+ pages_modified: int
+ pages_deleted: int
+
+
+@frozen
+class ActiveDreamRun:
+ run_status: str
+ started_at: datetime
+
+
+@frozen
+class DreamFileDiff:
+ path: str
+ status: str # added | modified | deleted
+ patch: str
+ truncated: bool
+
+
+@frozen
+class DreamRunDetail:
+ run: DreamRun
+ files: list[DreamFileDiff]
+
+
+@frozen
+class DreamRunList:
+ head_sha: str
+ dreams: list[DreamRun]
+ active_run: ActiveDreamRun | None
+
+
+_STATUS_MAP = {"A": "added", "M": "modified", "D": "deleted"}
+
+
+def _list_cache_key(organization_id: uuid.UUID | str, head_sha: str) -> str:
+ return f"context_layer:dreams:{organization_id}:{head_sha}"
+
+
+def _detail_cache_key(organization_id: uuid.UUID | str, head_sha: str, sha: str) -> str:
+ return f"context_layer:dream:{organization_id}:{head_sha}:{sha}"
+
+
+def list_dream_runs(organization_id: uuid.UUID | str) -> DreamRunList:
+ """Every dream run on the wiki's main branch, newest first."""
+ head_sha = store.get_config(organization_id).head_sha
+ active_run = _get_active_dream_run(organization_id)
+ cached = get_safe_cache(_list_cache_key(organization_id, head_sha))
+ if cached is not None:
+ return DreamRunList(
+ head_sha=head_sha,
+ dreams=[_dream_run_from_dict(entry) for entry in cached if isinstance(entry, dict)],
+ active_run=active_run,
+ )
+ with store.checkout_repo(organization_id) as checkout:
+ dreams = _read_dream_runs(checkout)
+ safe_cache_set(
+ _list_cache_key(organization_id, head_sha),
+ [_dream_run_to_dict(dream) for dream in dreams],
+ CACHE_TTL_SECONDS,
+ )
+ return DreamRunList(head_sha=head_sha, dreams=dreams, active_run=active_run)
+
+
+def _get_active_dream_run(organization_id: uuid.UUID | str) -> ActiveDreamRun | None:
+ run = tasks_facade.get_latest_active_internal_task_run_for_organization(organization_id, ai_stage=DREAM_AI_STAGE)
+ if run is None or run.created_at is None:
+ return None
+ return ActiveDreamRun(run_status=run.status, started_at=run.created_at)
+
+
+def get_dream_run(organization_id: uuid.UUID | str, sha: str) -> DreamRunDetail:
+ """One dream run with the per-file patches it landed.
+
+ The sha must name a dream merge on main, so a caller cannot diff arbitrary
+ commits through this endpoint."""
+ head_sha = store.get_config(organization_id).head_sha
+ cached = get_safe_cache(_detail_cache_key(organization_id, head_sha, sha))
+ if isinstance(cached, dict):
+ try:
+ return _dream_detail_from_dict(cached)
+ except ValueError:
+ pass
+ with store.checkout_repo(organization_id) as checkout:
+ dreams = {dream.sha: dream for dream in _read_dream_runs(checkout)}
+ run = dreams.get(sha)
+ if run is None:
+ raise DreamNotFoundError(f"no dream run at {sha}")
+ files = _read_dream_files(checkout, sha)
+ detail = DreamRunDetail(run=run, files=files)
+ safe_cache_set(
+ _detail_cache_key(organization_id, checkout.head_sha, sha),
+ _dream_detail_to_dict(detail),
+ CACHE_TTL_SECONDS,
+ )
+ return detail
+
+
+def _read_dream_runs(checkout: store.RepoCheckout) -> list[DreamRun]:
+ log = store._run_git(
+ [
+ "log",
+ "--merges",
+ "--diff-merges=first-parent",
+ "--name-status",
+ "--no-renames",
+ f"--format={_RECORD_SEPARATOR}%H{_FIELD_SEPARATOR}%cI{_FIELD_SEPARATOR}%s{_FIELD_SEPARATOR}%b{_CHANGE_SEPARATOR}.",
+ "main",
+ ],
+ checkout.path,
+ )
+ dreams: list[DreamRun] = []
+ for record in log.split(_RECORD_SEPARATOR):
+ record = record.strip("\n")
+ if not record:
+ continue
+ metadata, separator, changes = record.partition(_CHANGE_SEPARATOR)
+ if not separator:
+ continue
+ changes = changes.removeprefix(".")
+ sha, _, rest = metadata.partition(_FIELD_SEPARATOR)
+ committed_at, _, rest = rest.partition(_FIELD_SEPARATOR)
+ subject, _, body = rest.partition(_FIELD_SEPARATOR)
+ if not subject.startswith(DREAM_SUBJECT_PREFIX):
+ continue
+ counts = {"A": 0, "M": 0, "D": 0}
+ for line in changes.splitlines():
+ status, _, path = line.partition("\t")
+ status = status[:1]
+ if path.endswith(".md") and status in counts:
+ counts[status] += 1
+ dreams.append(
+ DreamRun(
+ sha=sha,
+ date=subject.removeprefix(DREAM_SUBJECT_PREFIX).strip(),
+ committed_at=datetime.fromisoformat(committed_at),
+ summary=body.strip(),
+ pages_added=counts["A"],
+ pages_modified=counts["M"],
+ pages_deleted=counts["D"],
+ )
+ )
+ return dreams
+
+
+def _read_dream_files(checkout: store.RepoCheckout, sha: str) -> list[DreamFileDiff]:
+ name_status = store._run_git(
+ ["diff", "--name-status", "--no-renames", f"{sha}^1", sha, "--", "*.md"], checkout.path
+ )
+ combined_patch = store._run_git(["diff", "--no-renames", f"{sha}^1", sha, "--", "*.md"], checkout.path)
+ patches = _split_file_patches(combined_patch)
+ changed_files = name_status.splitlines()
+ if len(patches) != len(changed_files):
+ raise store.ContextLayerStoreError("could not match dream patches to changed files")
+ files: list[DreamFileDiff] = []
+ for index, (line, patch) in enumerate(zip(changed_files, patches, strict=True)):
+ status_code, _, path = line.partition("\t")
+ status = _STATUS_MAP.get(status_code[:1], "modified")
+ truncated = False
+ if index >= DREAM_MAX_FILES:
+ patch = ""
+ truncated = True
+ elif len(patch.encode("utf-8")) > DREAM_MAX_PATCH_BYTES_PER_FILE:
+ patch = patch.encode("utf-8")[:DREAM_MAX_PATCH_BYTES_PER_FILE].decode("utf-8", errors="ignore")
+ truncated = True
+ files.append(DreamFileDiff(path=path, status=status, patch=patch, truncated=truncated))
+ return files
+
+
+def _split_file_patches(combined_patch: str) -> list[str]:
+ if not combined_patch:
+ return []
+ first, *rest = combined_patch.split("\ndiff --git ")
+ return [first, *(f"diff --git {patch}" for patch in rest)]
+
+
+def _dream_run_to_dict(dream: DreamRun) -> dict[str, object]:
+ return {
+ "sha": dream.sha,
+ "date": dream.date,
+ "committed_at": dream.committed_at.astimezone(UTC).isoformat(),
+ "summary": dream.summary,
+ "pages_added": dream.pages_added,
+ "pages_modified": dream.pages_modified,
+ "pages_deleted": dream.pages_deleted,
+ }
+
+
+def _dream_run_from_dict(data: dict[str, object]) -> DreamRun:
+ return DreamRun(
+ sha=str(data["sha"]),
+ date=str(data["date"]),
+ committed_at=datetime.fromisoformat(str(data["committed_at"])),
+ summary=str(data["summary"]),
+ pages_added=int(str(data["pages_added"])),
+ pages_modified=int(str(data["pages_modified"])),
+ pages_deleted=int(str(data["pages_deleted"])),
+ )
+
+
+def _dream_detail_to_dict(detail: DreamRunDetail) -> dict[str, object]:
+ return {
+ "run": _dream_run_to_dict(detail.run),
+ "files": [
+ {"path": file.path, "status": file.status, "patch": file.patch, "truncated": file.truncated}
+ for file in detail.files
+ ],
+ }
+
+
+def _dream_detail_from_dict(data: dict[str, object]) -> DreamRunDetail:
+ run_data = data.get("run")
+ files_data = data.get("files")
+ if not isinstance(run_data, dict) or not isinstance(files_data, list):
+ raise ValueError("malformed cached dream detail")
+ try:
+ run = _dream_run_from_dict(run_data)
+ files: list[DreamFileDiff] = []
+ for file in files_data:
+ if not isinstance(file, dict):
+ raise ValueError("malformed cached dream detail")
+ files.append(
+ DreamFileDiff(
+ path=str(file["path"]),
+ status=str(file["status"]),
+ patch=str(file["patch"]),
+ truncated=bool(file["truncated"]),
+ )
+ )
+ except (KeyError, TypeError, ValueError) as err:
+ raise ValueError("malformed cached dream detail") from err
+ return DreamRunDetail(run=run, files=files)
diff --git a/products/context_layer/backend/facade/api.py b/products/context_layer/backend/facade/api.py
index 6a188ca0ba84..175dab550f27 100644
--- a/products/context_layer/backend/facade/api.py
+++ b/products/context_layer/backend/facade/api.py
@@ -16,6 +16,16 @@ from posthog.dataclasses import frozen
from posthog.permissions import posthog_feature_flag_enabled
from products.context_layer.backend import store
+from products.context_layer.backend.dreams import (
+ ActiveDreamRun,
+ DreamFileDiff,
+ DreamNotFoundError,
+ DreamRun,
+ DreamRunDetail,
+ DreamRunList,
+ get_dream_run,
+ list_dream_runs,
+)
from products.context_layer.backend.enablement import enable_context_layer
from products.context_layer.backend.models import ContextLayerConfig
from products.context_layer.backend.pages import (
@@ -73,6 +83,12 @@ __all__ = [
"ContextLayerMount",
"ContextLayerStoreError",
"DependencyUnavailableError",
+ "ActiveDreamRun",
+ "DreamFileDiff",
+ "DreamNotFoundError",
+ "DreamRun",
+ "DreamRunDetail",
+ "DreamRunList",
"HeadConflictError",
"InvalidPagePathError",
"LintFailedError",
@@ -86,6 +102,7 @@ __all__ = [
"enable_context_layer",
"get_bundle_export",
"get_config",
+ "get_dream_run",
"get_page",
"get_health_report",
"get_sandbox_mount",
@@ -93,6 +110,7 @@ __all__ = [
"is_context_layer_enabled",
"land_commit_bundle",
"land_dream_branch",
+ "list_dream_runs",
"page_frontmatter_channel_id",
"proposed_channel_page_path",
"resolve_channel_page",
diff --git a/products/context_layer/backend/presentation/serializers.py b/products/context_layer/backend/presentation/serializers.py
index 14039ba34c59..21c738335798 100644
--- a/products/context_layer/backend/presentation/serializers.py
+++ b/products/context_layer/backend/presentation/serializers.py
@@ -33,6 +33,62 @@ class WikiPageSerializer(serializers.Serializer):
updated_at = serializers.DateTimeField(help_text="When this page was last changed in the wiki history.")
+class DreamRunSerializer(serializers.Serializer):
+ """One dreaming run: the merge commit it landed as, plus what it changed."""
+
+ sha = serializers.CharField(help_text="Merge commit sha the run landed as; pass back as `sha` on the detail read.")
+ date = serializers.CharField(help_text="The run's date, `YYYY-MM-DD`.")
+ committed_at = serializers.DateTimeField(help_text="When the run landed.")
+ summary = serializers.CharField(allow_blank=True, help_text="The run summary the dreaming agent wrote.")
+ pages_added = serializers.IntegerField(help_text="Pages the run created.")
+ pages_modified = serializers.IntegerField(help_text="Pages the run edited.")
+ pages_deleted = serializers.IntegerField(help_text="Pages the run removed.")
+
+
+class ActiveDreamRunSerializer(serializers.Serializer):
+ """A dreaming task that has not reached a terminal state yet."""
+
+ run_status = serializers.ChoiceField(
+ choices=[
+ ("not_started", "not_started"),
+ ("queued", "queued"),
+ ("in_progress", "in_progress"),
+ ],
+ help_text="The current task-run state for the active dream.",
+ )
+ started_at = serializers.DateTimeField(help_text="When the active dream task was created.")
+
+
+class DreamRunListSerializer(serializers.Serializer):
+ """Response shape for the wiki's dream run listing."""
+
+ head_sha = serializers.CharField(help_text="Commit sha of the wiki's current head.")
+ active_run = ActiveDreamRunSerializer(
+ allow_null=True,
+ help_text="The organization's active dreaming task, or null when no dream is running.",
+ )
+ dreams = DreamRunSerializer(many=True, help_text="Every landed dream run, newest first.")
+
+
+class DreamFileDiffSerializer(serializers.Serializer):
+ """One file a dream run changed, with its unified patch."""
+
+ path = serializers.CharField(help_text="Repo-relative path of the changed page.")
+ status = serializers.ChoiceField(
+ choices=[("added", "added"), ("modified", "modified"), ("deleted", "deleted")],
+ help_text="How the run changed the page.",
+ )
+ patch = serializers.CharField(allow_blank=True, help_text="Unified git patch for this file.")
+ truncated = serializers.BooleanField(help_text="Whether the patch was cut off for size.")
+
+
+class DreamRunDetailSerializer(serializers.Serializer):
+ """Response shape for one dream run: the run plus the diff it landed."""
+
+ run = DreamRunSerializer()
+ files = DreamFileDiffSerializer(many=True, help_text="Per-file patches, in diff order.")
+
+
class WikiHealthFindingSerializer(serializers.Serializer):
category = serializers.CharField(help_text="Stable category used to group this finding.")
path = serializers.CharField(help_text="Wiki page path associated with this finding.")
diff --git a/products/context_layer/backend/presentation/views.py b/products/context_layer/backend/presentation/views.py
index 8a2c038c638c..72bced5d4c55 100644
--- a/products/context_layer/backend/presentation/views.py
+++ b/products/context_layer/backend/presentation/views.py
@@ -18,6 +18,8 @@ from products.context_layer.backend.presentation.serializers import (
ChannelWikiPageSerializer,
CommitBundleSerializer,
ContextLayerStatusSerializer,
+ DreamRunDetailSerializer,
+ DreamRunListSerializer,
HeadConflictSerializer,
LintErrorSerializer,
WikiExportSerializer,
@@ -44,6 +46,8 @@ def _store_error_response(error: facade.ContextLayerStoreError) -> Response:
raise Throttled(detail=str(error))
if isinstance(error, facade.PageNotFoundError):
raise NotFound(str(error)) from error
+ if isinstance(error, facade.DreamNotFoundError):
+ raise NotFound(str(error)) from error
if isinstance(error, facade.HeadConflictError):
return Response(
{
@@ -244,7 +248,7 @@ class ContextLayerViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
posthog_feature_flag = "context-layer"
permission_classes = [IsAuthenticated, APIScopePermission, PostHogFeatureFlagPermission]
scope_object = "organization"
- scope_object_read_actions = ["status", "tree", "page", "report", "channel_page", "export"]
+ scope_object_read_actions = ["status", "tree", "page", "report", "channel_page", "export", "dreams", "dream"]
scope_object_write_actions = ["enable", "update_page", "commits"]
# No sandbox-token override here: a run token carries `scoped_teams`, which
@@ -365,6 +369,40 @@ class ContextLayerViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
def commits(self, request: Request, **kwargs) -> Response:
return _land_commits(self.organization.id, request)
+ @extend_schema(
+ operation_id="context_layer_dreams_list",
+ responses={200: DreamRunListSerializer, 404: OpenApiResponse(description="The context layer is not enabled.")},
+ summary="List dream runs",
+ description=(
+ "The active dreaming task, when present, plus every landed run newest first. A landed run is one "
+ "merge commit `dream: <date>` whose body is the summary; its changes are on the detail read."
+ ),
+ )
+ @action(methods=["GET"], detail=False)
+ def dreams(self, request: Request, **kwargs) -> Response:
+ try:
+ dream_list = facade.list_dream_runs(self.organization.id)
+ except facade.ContextLayerStoreError as error:
+ return _store_error_response(error)
+ return Response(DreamRunListSerializer(dream_list).data)
+
+ @extend_schema(
+ operation_id="context_layer_dreams_retrieve",
+ responses={
+ 200: DreamRunDetailSerializer,
+ 404: OpenApiResponse(description="No dream run at this sha, or the context layer is not enabled."),
+ },
+ summary="Read one dream run",
+ description="One dreaming run with the per-file unified patches it landed.",
+ )
+ @action(methods=["GET"], detail=False, url_path=r"dreams/(?P<sha>[0-9a-f]{40})")
+ def dream(self, request: Request, sha: str, **kwargs) -> Response:
+ try:
+ detail = facade.get_dream_run(self.organization.id, sha)
+ except facade.ContextLayerStoreError as error:
+ return _store_error_response(error)
+ return Response(DreamRunDetailSerializer(detail).data)
+
@extend_schema(
responses={200: WikiExportSerializer},
summary="Export the wiki",
diff --git a/products/context_layer/backend/temporal/dreaming.py b/products/context_layer/backend/temporal/dreaming.py
index 663922c682b9..2dfb1adb5c5f 100644
--- a/products/context_layer/backend/temporal/dreaming.py
+++ b/products/context_layer/backend/temporal/dreaming.py
@@ -33,6 +33,7 @@ from posthog.ph_client import ph_scoped_capture
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.client import sync_connect
+from products.context_layer.backend.dreams import DREAM_AI_STAGE
from products.context_layer.backend.facade import api as context_layer_facade
from products.context_layer.backend.models import ContextLayerConfig
@@ -206,6 +207,7 @@ async def dispatch_dream_run(input: DispatchDreamRunInput) -> DispatchDreamRunOu
initial_permission_mode="bypassPermissions",
),
step_name="context-layer-dream",
+ ai_stage=DREAM_AI_STAGE,
internal=True,
workflow_id_prefix="context-layer-dream",
)
diff --git a/products/context_layer/backend/test/test_api.py b/products/context_layer/backend/test/test_api.py
index f2ec5a805ed0..3f161cca68e2 100644
--- a/products/context_layer/backend/test/test_api.py
+++ b/products/context_layer/backend/test/test_api.py
@@ -5,7 +5,7 @@ from pathlib import Path
from uuid import uuid4
from posthog.test.base import APIBaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.apps import apps
from django.core.files.uploadedfile import SimpleUploadedFile
@@ -19,9 +19,10 @@ from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.scoping import team_scope
from posthog.models.team.team import Team
from posthog.storage.object_storage import UnavailableStorage
+from posthog.utils import safe_cache_set
from products.access_control.backend.models.access_control import AccessControl
-from products.context_layer.backend import enablement, store
+from products.context_layer.backend import dreams, enablement, store
from products.context_layer.backend.presentation import views
from products.tasks.backend.facade import api as tasks_facade
@@ -715,17 +716,150 @@ class TestContextLayerAPI(APIBaseTest):
assert body["head_sha"] == head
assert body["url"].startswith("http")
+ def _land_dream(self, path: str, content: str, branch: str) -> None:
+ bundle_bytes = self._bundle_with_edit(path, content, branch=branch)
+ response = self.client.post(
+ f"{self.base_url}/commits/",
+ {
+ "bundle": SimpleUploadedFile("out.bundle", bundle_bytes),
+ "branch": branch,
+ "summary": f"# Context dream — {branch.removeprefix('dream/')}\n\nDid things.",
+ },
+ format="multipart",
+ )
+ assert response.status_code == 200, response.content
+
+ def test_dreams_lists_landed_dream_runs_newest_first(self, _flag) -> None:
+ self._enable()
+ # An ordinary (linear) landing between two dreams must not appear: only
+ # `dream: <date>` merge commits are runs.
+ response = self.client.put(
+ f"{self.base_url}/pages/",
+ {"path": "areas/interactive.md", "content": _page("Interactive")},
+ format="json",
+ )
+ assert response.status_code == 200, response.content
+ self._land_dream("areas/dreamt-one.md", _page("Dreamt one"), "dream/2026-08-17")
+ self._land_dream("areas/dreamt-two.md", _page("Dreamt two"), "dream/2026-08-18")
+
+ started_at = timezone.now()
+ with patch.object(
+ dreams.tasks_facade,
+ "get_latest_active_internal_task_run_for_organization",
+ return_value=MagicMock(status="in_progress", created_at=started_at),
+ ):
+ response = self.client.get(f"{self.base_url}/dreams/")
+ assert response.status_code == 200, response.content
+ body = response.json()
+ assert body["active_run"] == {
+ "run_status": "in_progress",
+ "started_at": started_at.isoformat().replace("+00:00", "Z"),
+ }
+ dream_runs = body["dreams"]
+ assert [dream["date"] for dream in dream_runs] == ["2026-08-18", "2026-08-17"]
+ assert dream_runs[0]["pages_added"] == 1
+ assert dream_runs[0]["pages_modified"] == 0
+ assert dream_runs[0]["pages_deleted"] == 0
+ assert "Did things." in dream_runs[0]["summary"]
+ assert dream_runs[0]["sha"]
+
+ def test_dreams_404_before_enablement(self, _flag) -> None:
+ assert self.client.get(f"{self.base_url}/dreams/").status_code == 404
+
+ def test_dream_returns_the_runs_per_file_patches(self, _flag) -> None:
+ self._enable()
+ self._land_dream("areas/dreamt.md", _page("Dreamt"), "dream/2026-08-18")
+ dreams = self.client.get(f"{self.base_url}/dreams/").json()["dreams"]
+
+ response = self.client.get(f"{self.base_url}/dreams/{dreams[0]['sha']}/")
+ assert response.status_code == 200, response.content
+ body = response.json()
+ assert body["run"]["sha"] == dreams[0]["sha"]
+ assert body["run"]["date"] == "2026-08-18"
+ files = {file["path"]: file for file in body["files"]}
+ assert files["areas/dreamt.md"]["status"] == "added"
+ assert "+# Dreamt" in files["areas/dreamt.md"]["patch"]
+ assert files["areas/dreamt.md"]["truncated"] is False
+
+ def test_dream_lists_files_past_the_patch_cap(self, _flag) -> None:
+ self._enable()
+ bundle_bytes = self._bundle_with_edits(
+ {
+ "areas/first.md": _page("First"),
+ "areas/second.md": _page("Second"),
+ },
+ branch="dream/2026-08-18",
+ )
+ response = self.client.post(
+ f"{self.base_url}/commits/",
+ {
+ "bundle": SimpleUploadedFile("out.bundle", bundle_bytes),
+ "branch": "dream/2026-08-18",
+ "summary": "Dream summary",
+ },
+ format="multipart",
+ )
+ assert response.status_code == 200, response.content
+ dream = self.client.get(f"{self.base_url}/dreams/").json()["dreams"][0]
+
+ with patch.object(dreams, "DREAM_MAX_FILES", 1):
+ response = self.client.get(f"{self.base_url}/dreams/{dream['sha']}/")
+
+ assert response.status_code == 200, response.content
+ files = response.json()["files"]
+ assert [file["path"] for file in files] == ["areas/first.md", "areas/second.md"]
+ assert files[0]["patch"]
+ assert files[0]["truncated"] is False
+ assert files[1]["patch"] == ""
+ assert files[1]["truncated"] is True
+
+ def test_dream_rejects_a_sha_that_is_not_a_dream_merge(self, _flag) -> None:
+ # The detail read diffs the sha it is given, so it must refuse arbitrary
+ # commits rather than leak history that is not a dream run.
+ head = self._enable()
+ assert self.client.get(f"{self.base_url}/dreams/{head}/").status_code == 404
+ assert self.client.get(f"{self.base_url}/dreams/{'0' * 40}/").status_code == 404
+
+ def test_cached_dream_is_rejected_after_history_purge(self, _flag) -> None:
+ self._enable()
+ self._land_dream("areas/dreamt.md", _page("Dreamt"), "dream/2026-08-18")
+ dream = self.client.get(f"{self.base_url}/dreams/").json()["dreams"][0]
+ assert self.client.get(f"{self.base_url}/dreams/{dream['sha']}/").status_code == 200
+
+ store.purge_repo_history(self.organization.id)
+
+ assert self.client.get(f"{self.base_url}/dreams/{dream['sha']}/").status_code == 404
+
+ def test_malformed_dream_cache_is_rebuilt(self, _flag) -> None:
+ self._enable()
+ self._land_dream("areas/dreamt.md", _page("Dreamt"), "dream/2026-08-18")
+ dream = self.client.get(f"{self.base_url}/dreams/").json()["dreams"][0]
+ head_sha = self.client.get(f"{self.base_url}/status/").json()["head_sha"]
+ safe_cache_set(
+ dreams._detail_cache_key(self.organization.id, head_sha, dream["sha"]),
+ {"run": {}, "files": []},
+ )
+
+ response = self.client.get(f"{self.base_url}/dreams/{dream['sha']}/")
+
+ assert response.status_code == 200
+ assert response.json()["run"]["sha"] == dream["sha"]
+
def _bundle_with_edit(self, path: str, content: str, branch: str = "main") -> bytes:
"""Clone the wiki the way a sandbox does, commit one edit, pack it as a thin bundle."""
+ return self._bundle_with_edits({path: content}, branch=branch)
+
+ def _bundle_with_edits(self, edits: dict[str, str], branch: str = "main") -> bytes:
with store.checkout_repo(self.organization.id) as checkout:
env_git = ["git", "-c", "user.name=agent", "-c", "[email protected]"]
if branch != "main":
subprocess.run([*env_git, "checkout", "--quiet", "-b", branch], cwd=checkout.path, check=True)
- target = checkout.path / path
- target.parent.mkdir(parents=True, exist_ok=True)
- target.write_text(content)
+ for path, content in edits.items():
+ target = checkout.path / path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content)
subprocess.run([*env_git, "add", "--all"], cwd=checkout.path, check=True)
- subprocess.run([*env_git, "commit", "--quiet", "-m", f"Edit {path}"], cwd=checkout.path, check=True)
+ subprocess.run([*env_git, "commit", "--quiet", "-m", "Edit context"], cwd=checkout.path, check=True)
with tempfile.NamedTemporaryFile(suffix=".bundle") as bundle_file:
subprocess.run(
[*env_git, "bundle", "create", bundle_file.name, f"origin/main..{branch}"],
diff --git a/products/context_layer/backend/test/test_dreaming.py b/products/context_layer/backend/test/test_dreaming.py
index 8fd36f3f23ba..4b58c261a2c7 100644
--- a/products/context_layer/backend/test/test_dreaming.py
+++ b/products/context_layer/backend/test/test_dreaming.py
@@ -169,6 +169,7 @@ class TestDreamingLane(BaseTest):
assert context.model == "gpt-5.6-sol"
assert context.reasoning_effort == "high"
assert context.initial_permission_mode == "bypassPermissions"
+ assert trigger_mock.call_args.kwargs["ai_stage"] == dreaming.DREAM_AI_STAGE
prompt = trigger_mock.call_args.args[0]
assert prompt.startswith(
"This is the first dream: review the last 7 days of organizational activity. Treat this as a seed run:"
diff --git a/products/context_layer/frontend/generated/api.schemas.ts b/products/context_layer/frontend/generated/api.schemas.ts
index 20067aae9121..43789ef77c69 100644
--- a/products/context_layer/frontend/generated/api.schemas.ts
+++ b/products/context_layer/frontend/generated/api.schemas.ts
@@ -54,6 +54,106 @@ export interface LintErrorApi {
errors: string[]
}
+/**
+ * * `not_started` - not_started
+ * * `queued` - queued
+ * * `in_progress` - in_progress
+ */
+export type ActiveDreamRunRunStatusEnumApi =
+ (typeof ActiveDreamRunRunStatusEnumApi)[keyof typeof ActiveDreamRunRunStatusEnumApi]
+
+export const ActiveDreamRunRunStatusEnumApi = {
+ NotStarted: 'not_started',
+ Queued: 'queued',
+ InProgress: 'in_progress',
+} as const
+
+/**
+ * A dreaming task that has not reached a terminal state yet.
+ */
+export interface ActiveDreamRunApi {
+ /** The current task-run state for the active dream.
+ *
+ * * `not_started` - not_started
+ * * `queued` - queued
+ * * `in_progress` - in_progress */
+ run_status: ActiveDreamRunRunStatusEnumApi
+ /** When the active dream task was created. */
+ started_at: string
+}
+
+/**
+ * One dreaming run: the merge commit it landed as, plus what it changed.
+ */
+export interface DreamRunApi {
+ /** Merge commit sha the run landed as; pass back as `sha` on the detail read. */
+ sha: string
+ /** The run's date, `YYYY-MM-DD`. */
+ date: string
+ /** When the run landed. */
+ committed_at: string
+ /** The run summary the dreaming agent wrote. */
+ summary: string
+ /** Pages the run created. */
+ pages_added: number
+ /** Pages the run edited. */
+ pages_modified: number
+ /** Pages the run removed. */
+ pages_deleted: number
+}
+
+/**
+ * Response shape for the wiki's dream run listing.
+ */
+export interface DreamRunListApi {
+ /** Commit sha of the wiki's current head. */
+ head_sha: string
+ /** The organization's active dreaming task, or null when no dream is running. */
+ active_run: ActiveDreamRunApi | null
+ /** Every landed dream run, newest first. */
+ dreams: DreamRunApi[]
+}
+
+/**
+ * * `added` - added
+ * * `modified` - modified
+ * * `deleted` - deleted
+ */
+export type DreamFileDiffStatusEnumApi = (typeof DreamFileDiffStatusEnumApi)[keyof typeof DreamFileDiffStatusEnumApi]
+
+export const DreamFileDiffStatusEnumApi = {
+ Added: 'added',
+ Modified: 'modified',
+ Deleted: 'deleted',
+} as const
+
+/**
+ * One file a dream run changed, with its unified patch.
+ */
+export interface DreamFileDiffApi {
+ /** Repo-relative path of the changed page. */
+ path: string
+ /** How the run changed the page.
+ *
+ * * `added` - added
+ * * `modified` - modified
+ * * `deleted` - deleted */
+ status: DreamFileDiffStatusEnumApi
+ /** Unified git patch for this file. */
+ patch: string
+ /** Whether the patch was cut off for size. */
+ truncated: boolean
+}
+
+/**
+ * Response shape for one dream run: the run plus the diff it landed.
+ */
+export interface DreamRunDetailApi {
+ run: DreamRunApi
+ /** Per-file patches, in diff order. */
+ files: DreamFileDiffApi[]
+}
+
/**
* Response shape for a wiki bundle export.
*/
diff --git a/products/context_layer/frontend/generated/api.ts b/products/context_layer/frontend/generated/api.ts
index 5a3c1f9c768e..16089818f770 100644
--- a/products/context_layer/frontend/generated/api.ts
+++ b/products/context_layer/frontend/generated/api.ts
@@ -14,6 +14,8 @@ import type {
ContextLayerAgentPagesRetrieveParams,
ContextLayerPagesRetrieveParams,
ContextLayerStatusApi,
+ DreamRunDetailApi,
+ DreamRunListApi,
WikiExportApi,
WikiHealthReportApi,
WikiPageApi,
@@ -69,6 +71,43 @@ export const contextLayerCommitsCreate = async (
})
}
+export const getContextLayerDreamsListUrl = (organizationId: string) => {
+ return `/api/organizations/${organizationId}/context_layer/dreams/`
+}
+
+/**
+ * The active dreaming task, when present, plus every landed run newest first. A landed run is one merge commit `dream: <date>` whose body is the summary; its changes are on the detail read.
+ * @summary List dream runs
+ */
+export const contextLayerDreamsList = async (
+ organizationId: string,
+ options?: RequestInit
+): Promise<DreamRunListApi> => {
+ return apiMutator<DreamRunListApi>(getContextLayerDreamsListUrl(organizationId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getContextLayerDreamsRetrieveUrl = (organizationId: string, sha: string) => {
+ return `/api/organizations/${organizationId}/context_layer/dreams/${sha}/`
+}
+
+/**
+ * One dreaming run with the per-file unified patches it landed.
+ * @summary Read one dream run
+ */
+export const contextLayerDreamsRetrieve = async (
+ organizationId: string,
+ sha: string,
+ options?: RequestInit
+): Promise<DreamRunDetailApi> => {
+ return apiMutator<DreamRunDetailApi>(getContextLayerDreamsRetrieveUrl(organizationId, sha), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getContextLayerEnableCreateUrl = (organizationId: string) => {
return `/api/organizations/${organizationId}/context_layer/enable/`
}
diff --git a/products/context_layer/mcp/tools.yaml b/products/context_layer/mcp/tools.yaml
index 070128f39767..1d65e58c5ebe 100644
--- a/products/context_layer/mcp/tools.yaml
+++ b/products/context_layer/mcp/tools.yaml
@@ -15,6 +15,12 @@ tools:
context-layer-commits-create:
operation: context_layer_commits_create
enabled: false
+ context-layer-dreams-list:
+ operation: context_layer_dreams_list
+ enabled: false
+ context-layer-dreams-retrieve:
+ operation: context_layer_dreams_retrieve
+ enabled: false
context-layer-enable-create:
operation: context_layer_enable_create
enabled: false
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index c0ca1ff751ea..e190914f81c6 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -762,6 +762,39 @@ export interface ChannelContextWikiPage {
path: string;
}
+export interface ContextWikiDreamRun {
+ sha: string;
+ date: string;
+ committed_at: string;
+ summary: string;
+ pages_added: number;
+ pages_modified: number;
+ pages_deleted: number;
+}
+
+export interface ContextWikiActiveDreamRun {
+ run_status: "not_started" | "queued" | "in_progress";
+ started_at: string;
+}
+
+export interface ContextWikiDreamList {
+ head_sha: string;
+ active_run: ContextWikiActiveDreamRun | null;
+ dreams: ContextWikiDreamRun[];
+}
+
+export interface ContextWikiDreamFile {
+ path: string;
+ status: "added" | "modified" | "deleted";
+ patch: string;
+ truncated: boolean;
+}
+
+export interface ContextWikiDreamDetail {
+ run: ContextWikiDreamRun;
+ files: ContextWikiDreamFile[];
+}
+
// Thrown when PUT /context_layer/pages/ rejects a write because the caller's
// `base_head` is older than the wiki's current head. `currentHead` is the head
// to re-read against before retrying.
@@ -3181,6 +3214,20 @@ export class PostHogAPIClient {
);
}
+ async getContextWikiDreams(): Promise<ContextWikiDreamList | null> {
+ return this.getContextWikiResource<ContextWikiDreamList>(
+ `/api/organizations/@current/context_layer/dreams/`,
+ );
+ }
+
+ async getContextWikiDream(
+ sha: string,
+ ): Promise<ContextWikiDreamDetail | null> {
+ return this.getContextWikiResource<ContextWikiDreamDetail>(
+ `/api/organizations/@current/context_layer/dreams/${encodeURIComponent(sha)}/`,
+ );
+ }
+
/**
* Full-content page write guarded by `baseHead` optimistic concurrency.
* The server holds a per-org writer lock shared with agent commit landings;
diff --git a/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiDreamsPane.test.tsx b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiDreamsPane.test.tsx
new file mode 100644
index 000000000000..13e530f2d720
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiDreamsPane.test.tsx
@@ -0,0 +1,141 @@
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { ContextWikiDreamsPane } from "./ContextWikiDreamsPane";
+import { firstSummaryLine } from "./contextWikiDreams";
+
+const hoisted = vi.hoisted(() => ({
+ dreams: [
+ {
+ sha: "b".repeat(40),
+ date: "2026-08-18",
+ committed_at: "2026-08-18T03:00:00Z",
+ summary:
+ "# Context dream — 2026-08-18\n\nSecond night summary.\n\n![internal service](http://127.0.0.1/action)",
+ pages_added: 1,
+ pages_modified: 0,
+ pages_deleted: 0,
+ },
+ {
+ sha: "a".repeat(40),
+ date: "2026-08-17",
+ committed_at: "2026-08-17T03:00:00Z",
+ summary: "# Context dream — 2026-08-17\n\nFirst night summary.",
+ pages_added: 0,
+ pages_modified: 2,
+ pages_deleted: 0,
+ },
+ ],
+ detail: {
+ run: null as null | object,
+ files: [
+ {
+ path: "areas/dreamt.md",
+ status: "added",
+ patch:
+ "diff --git a/areas/dreamt.md b/areas/dreamt.md\nnew file mode 100644\nindex 0000000..1111111\n--- /dev/null\n+++ b/areas/dreamt.md\n@@ -0,0 +1 @@\n+# Dreamt\n",
+ truncated: false,
+ },
+ {
+ path: "areas/omitted.md",
+ status: "modified",
+ patch: "",
+ truncated: true,
+ },
+ ],
+ },
+ activeRun: {
+ run_status: "in_progress" as const,
+ started_at: "2026-08-18T04:00:00Z",
+ },
+ refetch: vi.fn(),
+}));
+
+vi.mock("../hooks/useContextWiki", () => ({
+ useContextWikiDreams: () => ({
+ data: {
+ head_sha: "head-1",
+ dreams: hoisted.dreams,
+ active_run: hoisted.activeRun,
+ },
+ isLoading: false,
+ error: null,
+ refetch: hoisted.refetch,
+ }),
+ useContextWikiDream: (sha: string) => ({
+ data: {
+ run: hoisted.dreams.find((dream) => dream.sha === sha) ?? null,
+ files: hoisted.detail.files,
+ },
+ isLoading: false,
+ error: null,
+ refetch: hoisted.refetch,
+ }),
+}));
+
+// The diff viewer needs browser APIs jsdom does not have; the pane only needs
+// the patch-to-metadata conversion, which is the part worth keeping real.
+vi.mock("@pierre/diffs/react", () => ({
+ FileDiff: () => <div data-testid="file-diff" />,
+}));
+
+vi.mock("../../../shell/themeStore", () => ({
+ useThemeStore: (selector: (s: { isDarkMode: boolean }) => unknown) =>
+ selector({ isDarkMode: false }),
+}));
+
+describe("ContextWikiDreamsPane", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("shows the newest run's summary and per-file changes, and switches runs", async () => {
+ const user = userEvent.setup();
+ render(<ContextWikiDreamsPane />);
+
+ expect(screen.getByText("Dreaming now")).toBeInTheDocument();
+
+ // Newest first, and the newest is selected without a click.
+ expect(screen.getAllByText("Second night summary.")).toHaveLength(2);
+ expect(
+ screen.getByText("Remote image blocked: internal service"),
+ ).toBeInTheDocument();
+ expect(document.querySelector("img")).toBeNull();
+ expect(screen.getByText("areas/dreamt.md")).toBeInTheDocument();
+ expect(screen.getByTestId("file-diff")).toBeInTheDocument();
+ expect(screen.getByText("areas/omitted.md")).toBeInTheDocument();
+ expect(
+ screen.getByText("This patch was too large to show in full."),
+ ).toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: /2026-08-17/ }));
+
+ // The detail pane follows the selection; the list keeps both previews.
+ expect(screen.getByText("Dream run: 2026-08-17")).toBeInTheDocument();
+ expect(screen.queryByText("Dream run: 2026-08-18")).toBeNull();
+ });
+
+ it("shows an active first dream before any history has landed", () => {
+ const landedDreams = hoisted.dreams.splice(0);
+ try {
+ render(<ContextWikiDreamsPane />);
+ expect(screen.getByText("Dreaming now")).toBeInTheDocument();
+ expect(screen.getByText("Dream in progress")).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ "This run will appear in the history after it lands its changes.",
+ ),
+ ).toBeInTheDocument();
+ } finally {
+ hoisted.dreams.push(...landedDreams);
+ }
+ });
+
+ it.each([
+ ["# Heading\n\nFirst prose line.\n\nSecond.", "First prose line."],
+ ["# Only heading", ""],
+ ["No heading at all.", "No heading at all."],
+ ])("firstSummaryLine(%j) -> %j", (summary, expected) => {
+ expect(firstSummaryLine(summary)).toBe(expected);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiDreamsPane.tsx b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiDreamsPane.tsx
new file mode 100644
index 000000000000..6bce20dcee80
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiDreamsPane.tsx
@@ -0,0 +1,340 @@
+import { MoonIcon, WarningCircleIcon } from "@phosphor-icons/react";
+import { processFile } from "@pierre/diffs";
+import { FileDiff } from "@pierre/diffs/react";
+import type {
+ ContextWikiActiveDreamRun,
+ ContextWikiDreamFile,
+ ContextWikiDreamRun,
+} from "@posthog/api-client/posthog-client";
+import {
+ Badge,
+ Button,
+ cn,
+ Empty,
+ EmptyContent,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+ Spinner,
+ Text,
+} from "@posthog/quill";
+import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";
+import { DIFFS_HIGHLIGHTER_OPTIONS } from "@posthog/ui/features/sessions/diffHighlighterOptions";
+import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";
+import { useMemo, useState } from "react";
+import type { Components } from "react-markdown";
+import { useThemeStore } from "../../../shell/themeStore";
+import {
+ useContextWikiDream,
+ useContextWikiDreams,
+} from "../hooks/useContextWiki";
+import { firstSummaryLine } from "./contextWikiDreams";
+
+const dreamMarkdownComponents: Partial<Components> = {
+ img: ({ alt }) => (
+ <span className="text-[13px] text-gray-10">
+ Remote image blocked{alt ? `: ${alt}` : ""}
+ </span>
+ ),
+};
+
+/**
+ * The dreaming history: every nightly synthesis run the wiki landed, newest
+ * first. Selecting a run shows the summary the agent wrote and the diff it
+ * landed, read from the wiki's git history.
+ */
+export function ContextWikiDreamsPane() {
+ const { data, isLoading, error, refetch } = useContextWikiDreams();
+ const [selectedSha, setSelectedSha] = useState<string | null>(null);
+
+ const dreams = useMemo(() => data?.dreams ?? [], [data]);
+ const activeRun = data?.active_run ?? null;
+ const effectiveSha =
+ selectedSha && dreams.some((dream) => dream.sha === selectedSha)
+ ? selectedSha
+ : (dreams[0]?.sha ?? null);
+ const selectedRun = dreams.find((dream) => dream.sha === effectiveSha);
+
+ if (isLoading) {
+ return (
+ <div className="flex h-full items-center justify-center">
+ <Spinner className="size-5" />
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <Empty>
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <WarningCircleIcon size={28} />
+ </EmptyMedia>
+ <EmptyTitle>Couldn't load the dream runs</EmptyTitle>
+ <EmptyDescription>{error.message}</EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <Button variant="outline" size="default" onClick={() => refetch()}>
+ Try again
+ </Button>
+ </EmptyContent>
+ </Empty>
+ );
+ }
+
+ if (!selectedRun && !activeRun) {
+ return (
+ <Empty>
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <MoonIcon size={28} />
+ </EmptyMedia>
+ <EmptyTitle>No dream runs yet</EmptyTitle>
+ <EmptyDescription>
+ Every night a dreaming agent reads recent activity and lands what it
+ learned into the wiki. Its runs will show up here.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ );
+ }
+
+ return (
+ <div className="flex h-full min-h-0">
+ <div className="flex w-72 shrink-0 flex-col overflow-y-auto border-(--gray-5) border-r">
+ {activeRun ? <ActiveDreamListItem run={activeRun} /> : null}
+ {dreams.map((dream) => (
+ <DreamListItem
+ key={dream.sha}
+ dream={dream}
+ selected={dream.sha === effectiveSha}
+ onSelect={() => setSelectedSha(dream.sha)}
+ />
+ ))}
+ </div>
+ <div className="flex min-w-0 flex-1 flex-col overflow-hidden">
+ {selectedRun ? (
+ <DreamDetail key={selectedRun.sha} run={selectedRun} />
+ ) : (
+ <Empty>
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <MoonIcon size={28} />
+ </EmptyMedia>
+ <EmptyTitle>Dream in progress</EmptyTitle>
+ <EmptyDescription>
+ This run will appear in the history after it lands its changes.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ )}
+ </div>
+ </div>
+ );
+}
+
+const ACTIVE_DREAM_LABELS: Record<
+ ContextWikiActiveDreamRun["run_status"],
+ string
+> = {
+ not_started: "Preparing dream",
+ queued: "Dream queued",
+ in_progress: "Dreaming now",
+};
+
+function ActiveDreamListItem({ run }: { run: ContextWikiActiveDreamRun }) {
+ return (
+ <div className="flex flex-col gap-1 border-(--gray-5) border-b bg-(--gray-2) px-4 py-3">
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-2">
+ <Spinner className="size-3.5" />
+ <Text size="sm" weight="medium">
+ {ACTIVE_DREAM_LABELS[run.run_status]}
+ </Text>
+ </div>
+ <RelativeTimestamp timestamp={run.started_at} />
+ </div>
+ <Text size="xs" variant="muted">
+ Reading recent activity and updating the wiki.
+ </Text>
+ </div>
+ );
+}
+
+function DreamListItem({
+ dream,
+ selected,
+ onSelect,
+}: {
+ dream: ContextWikiDreamRun;
+ selected: boolean;
+ onSelect: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onSelect}
+ className={cn(
+ "flex flex-col gap-1 border-(--gray-5) border-b px-4 py-3 text-left hover:bg-(--gray-2)",
+ selected && "bg-(--gray-2)",
+ )}
+ >
+ <div className="flex items-center justify-between gap-2">
+ <Text size="sm" weight="medium">
+ {dream.date}
+ </Text>
+ <RelativeTimestamp timestamp={dream.committed_at} />
+ </div>
+ <div className="flex items-center gap-2">
+ <DreamStats dream={dream} />
+ </div>
+ {dream.summary ? (
+ <Text size="xs" variant="muted" className="line-clamp-2">
+ {firstSummaryLine(dream.summary)}
+ </Text>
+ ) : null}
+ </button>
+ );
+}
+
+function DreamStats({ dream }: { dream: ContextWikiDreamRun }) {
+ const parts: {
+ label: string;
+ variant: "success" | "info" | "destructive";
+ }[] = [];
+ if (dream.pages_added > 0) {
+ parts.push({ label: `+${dream.pages_added}`, variant: "success" });
+ }
+ if (dream.pages_modified > 0) {
+ parts.push({ label: `~${dream.pages_modified}`, variant: "info" });
+ }
+ if (dream.pages_deleted > 0) {
+ parts.push({ label: `−${dream.pages_deleted}`, variant: "destructive" });
+ }
+ if (parts.length === 0) {
+ return (
+ <Text size="xs" variant="muted">
+ No page changes
+ </Text>
+ );
+ }
+ return (
+ <div className="flex items-center gap-1">
+ {parts.map((part) => (
+ <Badge key={part.label} variant={part.variant}>
+ {part.label}
+ </Badge>
+ ))}
+ </div>
+ );
+}
+
+function DreamDetail({ run }: { run: ContextWikiDreamRun }) {
+ const {
+ data: detail,
+ isLoading,
+ error,
+ refetch,
+ } = useContextWikiDream(run.sha);
+
+ return (
+ <div className="flex h-full min-h-0 flex-col overflow-y-auto">
+ <div className="flex flex-col gap-1 border-(--gray-5) border-b px-4 py-3">
+ <div className="flex items-center justify-between gap-3">
+ <Text size="base" weight="semibold">
+ Dream run: {run.date}
+ </Text>
+ <RelativeTimestamp timestamp={run.committed_at} />
+ </div>
+ <code className="truncate text-[11px] text-gray-10">{run.sha}</code>
+ </div>
+ {run.summary ? (
+ <div className="border-(--gray-5) border-b p-4 text-[13px]">
+ <MarkdownRenderer
+ content={run.summary}
+ componentsOverride={dreamMarkdownComponents}
+ />
+ </div>
+ ) : null}
+ <div className="flex flex-col gap-3 p-4">
+ {isLoading ? (
+ <div className="flex items-center justify-center py-8">
+ <Spinner className="size-5" />
+ </div>
+ ) : error ? (
+ <div className="flex flex-col items-center gap-2 py-8 text-[13px] text-gray-10">
+ <span>Couldn't load this run's changes: {error.message}</span>
+ <Button variant="outline" size="sm" onClick={() => refetch()}>
+ Try again
+ </Button>
+ </div>
+ ) : detail && detail.files.length > 0 ? (
+ detail.files.map((file) => (
+ <DreamFileDiffView key={file.path} file={file} />
+ ))
+ ) : (
+ <Text size="sm" variant="muted">
+ This run landed without changing any pages.
+ </Text>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function DreamFileDiffView({ file }: { file: ContextWikiDreamFile }) {
+ const isDarkMode = useThemeStore((s) => s.isDarkMode);
+ const fileDiff = useMemo(() => {
+ if (!file.patch) return undefined;
+ try {
+ return processFile(file.patch, { isGitDiff: true });
+ } catch {
+ return undefined;
+ }
+ }, [file.patch]);
+ const options = useMemo(
+ () => ({
+ ...DIFFS_HIGHLIGHTER_OPTIONS,
+ diffStyle: "unified" as const,
+ overflow: "wrap" as const,
+ themeType: (isDarkMode ? "dark" : "light") as "dark" | "light",
+ }),
+ [isDarkMode],
+ );
+
+ return (
+ <div className="overflow-hidden rounded-(--radius-2) border border-(--gray-5)">
+ <div className="flex items-center justify-between gap-2 border-(--gray-5) border-b bg-(--gray-2) px-3 py-1.5">
+ <code className="truncate text-[12px]">{file.path}</code>
+ <Badge
+ variant={
+ file.status === "added"
+ ? "success"
+ : file.status === "deleted"
+ ? "destructive"
+ : "info"
+ }
+ >
+ {file.status}
+ </Badge>
+ </div>
+ {fileDiff ? (
+ <>
+ <FileDiff fileDiff={fileDiff} options={options} />
+ {file.truncated ? (
+ <div className="border-(--gray-5) border-t bg-(--gray-2) px-3 py-1.5 text-(--gray-10) text-[12px]">
+ This patch was too large to show in full.
+ </div>
+ ) : null}
+ </>
+ ) : (
+ <div className="bg-(--gray-2) px-3 py-2 text-(--gray-10) text-[12px]">
+ {file.truncated
+ ? "This patch was too large to show in full."
+ : "No diff available for this file."}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiView.tsx b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiView.tsx
index db87aafeecb3..e83efeddd1aa 100644
--- a/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiView.tsx
+++ b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiView.tsx
@@ -9,6 +9,10 @@ import {
EmptyMedia,
EmptyTitle,
Spinner,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
} from "@posthog/quill";
import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";
import { FileExplorer } from "@posthog/ui/primitives/FileExplorer";
@@ -25,6 +29,7 @@ import {
useEnableContextWiki,
} from "../hooks/useContextWiki";
import { buildWikiTree } from "../wikiTree";
+import { ContextWikiDreamsPane } from "./ContextWikiDreamsPane";
import { ContextWikiPagePane, type WikiDraft } from "./ContextWikiPagePane";
/**
@@ -58,6 +63,26 @@ export function ContextWikiView({ initialPath }: { initialPath?: string }) {
);
}
+// Page-level sections: the wiki explorer itself, and the dreaming history.
+function ContextWikiTabs({ explorer }: { explorer: React.ReactNode }) {
+ return (
+ <Tabs defaultValue="pages" className="flex h-full min-h-0 flex-col">
+ <div className="shrink-0 border-(--gray-5) border-b px-4">
+ <TabsList variant="line">
+ <TabsTrigger value="pages">Pages</TabsTrigger>
+ <TabsTrigger value="dreams">Dreams</TabsTrigger>
+ </TabsList>
+ </div>
+ <TabsContent value="pages" className="min-h-0 flex-1">
+ {explorer}
+ </TabsContent>
+ <TabsContent value="dreams" className="min-h-0 flex-1">
+ <ContextWikiDreamsPane />
+ </TabsContent>
+ </Tabs>
+ );
+}
+
// The state-dependent body under the constant page header: loading, the two
// distinct empty states (403 dark vs 404 never enabled), errors, or the
// explorer.
@@ -179,28 +204,32 @@ function ContextWikiBody({ initialPath }: { initialPath?: string }) {
}
return (
- <FileExplorer
- tree={wikiRoot}
- selectedPath={effectivePath}
- onSelectPath={setSelectedPath}
- emptyMessage="The wiki has no pages yet."
- storageKey="context-wiki-explorer"
- >
- {effectivePath ? (
- // Keyed by path so view state never leaks across pages; the draft is
- // held above this so the remount does not take it with it.
- <ContextWikiPagePane
- key={effectivePath}
- path={effectivePath}
- draft={drafts[effectivePath]}
- onDraftChange={setDraft}
- onDraftDiscard={discardDraft}
- />
- ) : (
- <div className="flex flex-1 items-center justify-center text-[13px] text-gray-10">
- The wiki has no pages yet.
- </div>
- )}
- </FileExplorer>
+ <ContextWikiTabs
+ explorer={
+ <FileExplorer
+ tree={wikiRoot}
+ selectedPath={effectivePath}
+ onSelectPath={setSelectedPath}
+ emptyMessage="The wiki has no pages yet."
+ storageKey="context-wiki-explorer"
+ >
+ {effectivePath ? (
+ // Keyed by path so view state never leaks across pages; the draft is
+ // held above this so the remount does not take it with it.
+ <ContextWikiPagePane
+ key={effectivePath}
+ path={effectivePath}
+ draft={drafts[effectivePath]}
+ onDraftChange={setDraft}
+ onDraftDiscard={discardDraft}
+ />
+ ) : (
+ <div className="flex flex-1 items-center justify-center text-[13px] text-gray-10">
+ The wiki has no pages yet.
+ </div>
+ )}
+ </FileExplorer>
+ }
+ />
);
}
diff --git a/products/desktop/packages/ui/src/features/context-wiki/components/contextWikiDreams.ts b/products/desktop/packages/ui/src/features/context-wiki/components/contextWikiDreams.ts
new file mode 100644
index 000000000000..9cc5cc68c2f3
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/context-wiki/components/contextWikiDreams.ts
@@ -0,0 +1,8 @@
+export function firstSummaryLine(summary: string): string {
+ for (const line of summary.split("\n")) {
+ const trimmed = line.trim();
+ if (!trimmed || trimmed.startsWith("#")) continue;
+ return trimmed;
+ }
+ return "";
+}
diff --git a/products/desktop/packages/ui/src/features/context-wiki/hooks/useContextWiki.ts b/products/desktop/packages/ui/src/features/context-wiki/hooks/useContextWiki.ts
index a6599f1774f7..9ebd1dbc8231 100644
--- a/products/desktop/packages/ui/src/features/context-wiki/hooks/useContextWiki.ts
+++ b/products/desktop/packages/ui/src/features/context-wiki/hooks/useContextWiki.ts
@@ -1,6 +1,8 @@
import { requestErrorStatus } from "@posthog/api-client/fetcher";
import {
type ChannelContextWikiPage,
+ type ContextWikiDreamDetail,
+ type ContextWikiDreamList,
type ContextWikiHealthReport,
type ContextWikiPage,
type ContextWikiTree,
@@ -14,6 +16,9 @@ export const CONTEXT_WIKI_TREE_KEY = ["context-wiki", "tree"] as const;
export const CONTEXT_WIKI_PAGE_KEY = (path: string) =>
["context-wiki", "page", path] as const;
export const CONTEXT_WIKI_REPORT_KEY = ["context-wiki", "report"] as const;
+export const CONTEXT_WIKI_DREAMS_KEY = ["context-wiki", "dreams"] as const;
+export const CONTEXT_WIKI_DREAM_KEY = (sha: string) =>
+ ["context-wiki", "dream", sha] as const;
export const CHANNEL_CONTEXT_WIKI_PAGE_KEY = (channelId: string) =>
["context-wiki", "channel-page", channelId] as const;
@@ -105,6 +110,28 @@ export function useContextWikiPage(path: string) {
);
}
+export function useContextWikiDreams() {
+ return useAuthenticatedQuery<ContextWikiDreamList | null>(
+ CONTEXT_WIKI_DREAMS_KEY,
+ (client) => client.getContextWikiDreams(),
+ {
+ staleTime: 30_000,
+ refetchOnMount: "always",
+ refetchInterval: (query) =>
+ query.state.data?.active_run ? 5_000 : false,
+ },
+ );
+}
+
+/** `null` data means there is no dream run at this sha (404). */
+export function useContextWikiDream(sha: string | null) {
+ return useAuthenticatedQuery<ContextWikiDreamDetail | null>(
+ CONTEXT_WIKI_DREAM_KEY(sha ?? ""),
+ (client) => client.getContextWikiDream(sha as string),
+ { enabled: sha !== null, staleTime: Infinity },
+ );
+}
+
export function useContextWikiHealthReport() {
return useAuthenticatedQuery<ContextWikiHealthReport | null>(
CONTEXT_WIKI_REPORT_KEY,
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index cf0fd783c310..84d1276a5e07 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -207,6 +207,7 @@ __all__ = [
"finalize_task_run_artifact_uploads",
"finalize_task_staged_artifacts",
"get_active_wizard_cloud_run",
+ "get_latest_active_internal_task_run_for_organization",
"get_conversation_task_dtos",
"get_latest_pr_url_by_task",
"get_merged_pr_task_ids",
@@ -1040,6 +1041,30 @@ def get_active_wizard_cloud_run(team_id: int) -> contracts.WizardCloudRunDTO | N
return None
+def get_latest_active_internal_task_run_for_organization(
+ organization_id: str | UUID, *, ai_stage: str
+) -> contracts.TaskRunDTO | None:
+ """Return the newest active cloud run for a server-owned organization flow."""
+ run = (
+ TaskRun.objects.filter(
+ team__organization_id=organization_id,
+ task__team__organization_id=organization_id,
+ task__internal=True,
+ environment=TaskRun.Environment.CLOUD,
+ state__ai_stage=ai_stage,
+ status__in=[
+ TaskRun.Status.NOT_STARTED,
+ TaskRun.Status.QUEUED,
+ TaskRun.Status.IN_PROGRESS,
+ ],
+ )
+ .select_related("task", "task__created_by")
+ .order_by("-created_at", "-id")
+ .first()
+ )
+ return _task_run_to_dto(run) if run is not None else None
+
+
def get_stale_queued_task_run_ids(
older_than: timedelta,
limit: int,
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index 2c09634c3fb2..ee7ad40cf4cf 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -471,6 +471,57 @@ class TestFacadeReadsAndMappers(TestCase):
self.assertEqual(handle.task_id, older_task.id)
self.assertEqual(handle.run_id, active.id)
+ def test_get_latest_active_internal_task_run_for_organization_uses_trusted_markers(self):
+ active_task = self._make_task(internal=True)
+ active = TaskRun.objects.create(
+ task=active_task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ environment=TaskRun.Environment.CLOUD,
+ state={"ai_stage": "context-layer-dream"},
+ )
+ terminal_task = self._make_task(internal=True)
+ TaskRun.objects.create(
+ task=terminal_task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ environment=TaskRun.Environment.CLOUD,
+ state={"ai_stage": "context-layer-dream"},
+ )
+ untrusted_task = self._make_task(internal=False)
+ TaskRun.objects.create(
+ task=untrusted_task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ environment=TaskRun.Environment.CLOUD,
+ state={"ai_stage": "context-layer-dream"},
+ )
+ wrong_stage_task = self._make_task(internal=True)
+ TaskRun.objects.create(
+ task=wrong_stage_task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ environment=TaskRun.Environment.CLOUD,
+ state={"ai_stage": "another-server-flow"},
+ )
+ other_organization = Organization.objects.create(name="Other org")
+ other_team = Team.objects.create(organization=other_organization, name="Other team")
+ other_task = self._make_task(team=other_team, internal=True)
+ TaskRun.objects.create(
+ task=other_task,
+ team=other_team,
+ status=TaskRun.Status.IN_PROGRESS,
+ environment=TaskRun.Environment.CLOUD,
+ state={"ai_stage": "context-layer-dream"},
+ )
+
+ result = facade.get_latest_active_internal_task_run_for_organization(
+ self.organization.id, ai_stage="context-layer-dream"
+ )
+
+ assert result is not None
+ self.assertEqual(result.id, active.id)
+
def test_count_in_progress_runs_for_github_integration_scopes_to_live_runs_of_that_integration(self):
integration = Integration.objects.create(team=self.team, kind="github", config={}, sensitive_config={})
other_integration = Integration.objects.create(team=self.team, kind="github", config={}, sensitive_config={})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5f8870fc05b5..41ee4b15c8cb 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -2744,6 +2744,34 @@ export namespace Schemas {
breakpoints: ActiveBreakpoint[];
}
+ /**
+ * * `not_started` - not_started
+ * * `queued` - queued
+ * * `in_progress` - in_progress
+ */
+ export type ActiveDreamRunRunStatusEnum = typeof ActiveDreamRunRunStatusEnum[keyof typeof ActiveDreamRunRunStatusEnum];
+
+
+ export const ActiveDreamRunRunStatusEnum = {
+ NotStarted: 'not_started',
+ Queued: 'queued',
+ InProgress: 'in_progress',
+ } as const;
+
+ /**
+ * A dreaming task that has not reached a terminal state yet.
+ */
+ export interface ActiveDreamRun {
+ /** The current task-run state for the active dream.
+ *
+ * * `not_started` - not_started
+ * * `queued` - queued
+ * * `in_progress` - in_progress */
+ run_status: ActiveDreamRunRunStatusEnum;
+ /** When the active dream task was created. */
+ started_at: string;
+ }
+
/**
* * `true` - true
* * `false` - false
@@ -29156,6 +29184,79 @@ export namespace Schemas {
has_draft: boolean;
}
+ /**
+ * * `added` - added
+ * * `modified` - modified
+ * * `deleted` - deleted
+ */
+ export type DreamFileDiffStatusEnum = typeof DreamFileDiffStatusEnum[keyof typeof DreamFileDiffStatusEnum];
+
+
+ export const DreamFileDiffStatusEnum = {
+ Added: 'added',
+ Modified: 'modified',
+ Deleted: 'deleted',
+ } as const;
+
+ /**
+ * One file a dream run changed, with its unified patch.
+ */
+ export interface DreamFileDiff {
+ /** Repo-relative path of the changed page. */
+ path: string;
+ /** How the run changed the page.
+ *
+ * * `added` - added
+ * * `modified` - modified
+ * * `deleted` - deleted */
+ status: DreamFileDiffStatusEnum;
+ /** Unified git patch for this file. */
+ patch: string;
+ /** Whether the patch was cut off for size. */
+ truncated: boolean;
+ }
+
+ /**
+ * One dreaming run: the merge commit it landed as, plus what it changed.
+ */
+ export interface DreamRun {
+ /** Merge commit sha the run landed as; pass back as `sha` on the detail read. */
+ sha: string;
+ /** The run's date, `YYYY-MM-DD`. */
+ date: string;
+ /** When the run landed. */
+ committed_at: string;
+ /** The run summary the dreaming agent wrote. */
+ summary: string;
+ /** Pages the run created. */
+ pages_added: number;
+ /** Pages the run edited. */
+ pages_modified: number;
+ /** Pages the run removed. */
+ pages_deleted: number;
+ }
+
+ /**
+ * Response shape for one dream run: the run plus the diff it landed.
+ */
+ export interface DreamRunDetail {
+ run: DreamRun;
+ /** Per-file patches, in diff order. */
+ files: DreamFileDiff[];
+ }
+
+ /**
+ * Response shape for the wiki's dream run listing.
+ */
+ export interface DreamRunList {
+ /** Commit sha of the wiki's current head. */
+ head_sha: string;
+ /** The organization's active dreaming task, or null when no dream is running. */
+ active_run: ActiveDreamRun | null;
+ /** Every landed dream run, newest first. */
+ dreams: DreamRun[];
+ }
+
/**
* * `Up` - Up
* * `Down` - Down