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): context wiki explorer in the desktop nav (#85360)

Peter Kirkham034d1b450e2d
diff --git a/products/context_layer/backend/pages.py b/products/context_layer/backend/pages.py
index a8408f3650b9..1f2d22d61dfe 100644
--- a/products/context_layer/backend/pages.py
+++ b/products/context_layer/backend/pages.py
@@ -36,6 +36,7 @@ class WikiPage:
path: str
content: str
head_sha: str
+ updated_at: datetime
@frozen
@@ -110,8 +111,18 @@ def get_tree(organization_id: uuid.UUID | str) -> WikiTree:
def get_page(organization_id: uuid.UUID | str, path: str) -> WikiPage:
path = normalize_page_path(path)
head_sha = store.get_config(organization_id).head_sha
- content = get_safe_cache(_page_cache_key(organization_id, head_sha, path))
- if content is None:
+ cached = get_safe_cache(_page_cache_key(organization_id, head_sha, path))
+ page = (
+ WikiPage(
+ path=path,
+ content=cached["content"],
+ head_sha=head_sha,
+ updated_at=datetime.fromisoformat(cached["updated_at"]),
+ )
+ if isinstance(cached, dict) and "content" in cached and "updated_at" in cached
+ else None
+ )
+ if page is None:
# Answer misses from the cached tree when we can: repeated requests for
# a nonexistent path must 404 cheaply, not re-download the bundle.
known_paths = get_safe_cache(_tree_cache_key(organization_id, head_sha))
@@ -119,10 +130,10 @@ def get_page(organization_id: uuid.UUID | str, path: str) -> WikiPage:
raise PageNotFoundError(f"no page at {path}")
warmed = _warm_cache(organization_id)
head_sha = warmed.head_sha
- content = warmed.pages.get(path)
- if content is None:
+ page = warmed.pages.get(path)
+ if page is None:
raise PageNotFoundError(f"no page at {path}")
- return WikiPage(path=path, content=content, head_sha=head_sha)
+ return page
def get_health_report(organization_id: uuid.UUID | str) -> WikiHealthReport:
@@ -180,22 +191,32 @@ class WarmedWiki:
head_sha: str
paths: list[str]
- pages: dict[str, str]
+ pages: dict[str, WikiPage]
def _warm_cache(organization_id: uuid.UUID | str) -> WarmedWiki:
"""One checkout warms the tree and every page for the checkout's head."""
with store.checkout_repo(organization_id) as checkout:
- pages: dict[str, str] = {}
+ pages: dict[str, WikiPage] = {}
for file_path in sorted(checkout.path.rglob("*.md")):
if ".git" in file_path.parts or file_path.is_symlink() or not file_path.is_file():
continue
relative = str(file_path.relative_to(checkout.path))
# The linter rejects non-UTF-8 pages at land time; replacement here
# keeps one legacy file from turning every read into a 500.
- pages[relative] = file_path.read_text(encoding="utf-8", errors="replace")
+ updated_at = store.get_path_updated_at(checkout, relative)
+ pages[relative] = WikiPage(
+ path=relative,
+ content=file_path.read_text(encoding="utf-8", errors="replace"),
+ head_sha=checkout.head_sha,
+ updated_at=updated_at,
+ )
paths = sorted(pages)
safe_cache_set(_tree_cache_key(organization_id, checkout.head_sha), paths, CACHE_TTL_SECONDS)
- for relative, content in pages.items():
- safe_cache_set(_page_cache_key(organization_id, checkout.head_sha, relative), content, CACHE_TTL_SECONDS)
+ for relative, page in pages.items():
+ safe_cache_set(
+ _page_cache_key(organization_id, checkout.head_sha, relative),
+ {"content": page.content, "updated_at": page.updated_at.isoformat()},
+ CACHE_TTL_SECONDS,
+ )
return WarmedWiki(head_sha=checkout.head_sha, paths=paths, pages=pages)
diff --git a/products/context_layer/backend/presentation/serializers.py b/products/context_layer/backend/presentation/serializers.py
index 3d31bea024e9..6ab52a5cd6fd 100644
--- a/products/context_layer/backend/presentation/serializers.py
+++ b/products/context_layer/backend/presentation/serializers.py
@@ -30,6 +30,7 @@ class WikiPageSerializer(serializers.Serializer):
head_sha = serializers.CharField(
help_text="Commit sha the content was read at; pass back as `base_head` on writes."
)
+ updated_at = serializers.DateTimeField(help_text="When this page was last changed in the wiki history.")
class WikiHealthFindingSerializer(serializers.Serializer):
diff --git a/products/context_layer/backend/store.py b/products/context_layer/backend/store.py
index 5d28e6db3027..0bc822340a3c 100644
--- a/products/context_layer/backend/store.py
+++ b/products/context_layer/backend/store.py
@@ -17,6 +17,7 @@ import threading
import subprocess
from collections.abc import Callable, Iterator
from contextlib import contextmanager
+from datetime import datetime
from pathlib import Path
from django.utils import timezone
@@ -334,6 +335,10 @@ def checkout_repo(organization_id: uuid.UUID | str) -> Iterator[RepoCheckout]:
yield RepoCheckout(path=workdir, head_sha=config.head_sha)
+def get_path_updated_at(checkout: RepoCheckout, path: str) -> datetime:
+ return datetime.fromisoformat(_run_git(["log", "-1", "--format=%cI", "--", path], checkout.path))
+
+
def initialize_repo(
organization_id: uuid.UUID | str,
*,
diff --git a/products/context_layer/backend/test/test_api.py b/products/context_layer/backend/test/test_api.py
index 19f6e187c781..ae52672c775a 100644
--- a/products/context_layer/backend/test/test_api.py
+++ b/products/context_layer/backend/test/test_api.py
@@ -100,6 +100,7 @@ class TestContextLayerAPI(APIBaseTest):
assert "AGENTS.md" in tree["paths"]
assert "channels/growth.md" in tree["paths"]
page = self.client.get(f"{self.base_url}/pages/", {"path": "channels/growth.md"}).json()
+ assert page["updated_at"]
assert f"channel_id: {channel.id}" in page["content"]
assert "Focus on activation." in page["content"]
diff --git a/products/context_layer/frontend/generated/api.schemas.ts b/products/context_layer/frontend/generated/api.schemas.ts
index caa8a162f470..be34555e9f9e 100644
--- a/products/context_layer/frontend/generated/api.schemas.ts
+++ b/products/context_layer/frontend/generated/api.schemas.ts
@@ -64,6 +64,8 @@ export interface WikiPageApi {
content: string
/** Commit sha the content was read at; pass back as `base_head` on writes. */
head_sha: string
+ /** When this page was last changed in the wiki history. */
+ updated_at: string
}
/**
diff --git a/products/desktop/packages/api-client/src/posthog-client.context-wiki.test.ts b/products/desktop/packages/api-client/src/posthog-client.context-wiki.test.ts
new file mode 100644
index 000000000000..c44486c79334
--- /dev/null
+++ b/products/desktop/packages/api-client/src/posthog-client.context-wiki.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it, vi } from "vitest";
+import type { FetchImplementation } from "./fetcher";
+import {
+ ContextWikiConflictError,
+ ContextWikiLintError,
+ ContextWikiUnavailableError,
+ PostHogAPIClient,
+} from "./posthog-client";
+
+function makeClient(fetch: ReturnType<typeof vi.fn>): PostHogAPIClient {
+ return new PostHogAPIClient(
+ "https://app.posthog.test",
+ async () => "token",
+ async () => "token",
+ 42,
+ { fetch: fetch as unknown as FetchImplementation },
+ );
+}
+
+const PAGE_INPUT = {
+ path: "channels/growth.md",
+ content: "# Growth\n",
+ baseHead: "abc123",
+};
+
+describe("context wiki client", () => {
+ it("returns null from getContextWikiTree when the wiki is not enabled", async () => {
+ const fetch = vi.fn().mockResolvedValue(new Response("", { status: 404 }));
+ await expect(makeClient(fetch).getContextWikiTree()).resolves.toBeNull();
+ });
+
+ it("maps a 403 tree read to ContextWikiUnavailableError with the server detail", async () => {
+ const fetch = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({ detail: "Organization has private projects" }),
+ {
+ status: 403,
+ },
+ ),
+ );
+ await expect(makeClient(fetch).getContextWikiTree()).rejects.toThrow(
+ ContextWikiUnavailableError,
+ );
+ });
+
+ it("sends base_head on page writes and returns the new head", async () => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValue(
+ new Response(JSON.stringify({ head_sha: "def456" }), { status: 200 }),
+ );
+ await expect(
+ makeClient(fetch).putContextWikiPage(PAGE_INPUT),
+ ).resolves.toEqual({ head_sha: "def456" });
+ const request = fetch.mock.calls[0][1] as RequestInit;
+ expect(JSON.parse(request.body as string)).toEqual({
+ path: "channels/growth.md",
+ content: "# Growth\n",
+ base_head: "abc123",
+ });
+ });
+
+ it("maps a stale-head 409 to ContextWikiConflictError carrying the current head", async () => {
+ const fetch = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ current_head: "fff999" }), {
+ status: 409,
+ }),
+ );
+ const error = await makeClient(fetch)
+ .putContextWikiPage(PAGE_INPUT)
+ .catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(ContextWikiConflictError);
+ expect((error as ContextWikiConflictError).currentHead).toBe("fff999");
+ });
+
+ it("maps a lint 400 to ContextWikiLintError with the violation list", async () => {
+ const fetch = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ detail: "The change violates the wiki structure.",
+ errors: ["AGENTS.md must keep its heading"],
+ }),
+ { status: 400 },
+ ),
+ );
+ const error = await makeClient(fetch)
+ .putContextWikiPage(PAGE_INPUT)
+ .catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(ContextWikiLintError);
+ expect((error as ContextWikiLintError).errors).toEqual([
+ "AGENTS.md must keep its heading",
+ ]);
+ });
+});
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index 56422ed21f4d..55c30ef6566f 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -732,6 +732,70 @@ export interface PostHogObjectReferenceInput {
source_message_id: string;
}
+export interface ContextWikiTree {
+ head_sha: string;
+ paths: string[];
+}
+
+export interface ContextWikiPage {
+ path: string;
+ content: string;
+ head_sha: string;
+ updated_at: string;
+}
+
+export interface ContextWikiHealthFinding {
+ category: string;
+ path: string;
+ message: string;
+}
+
+export interface ContextWikiHealthReport {
+ head_sha: string;
+ findings: ContextWikiHealthFinding[];
+}
+
+// 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.
+export class ContextWikiConflictError extends Error {
+ status = 409;
+ currentHead: string | null;
+ constructor(currentHead: string | null) {
+ super("The wiki changed since you started editing");
+ this.name = "ContextWikiConflictError";
+ this.currentHead = currentHead;
+ }
+}
+
+// Thrown when a page write fails the wiki's structure lint; `errors` lists the
+// violations for inline display.
+export class ContextWikiLintError extends Error {
+ status = 400;
+ errors: string[];
+ constructor(detail: string, errors: string[]) {
+ super(detail);
+ this.name = "ContextWikiLintError";
+ this.errors = errors;
+ }
+}
+
+// Thrown on 403: the organization has private projects, so its wiki is
+// deliberately unavailable. Distinct from 404 (wiki never enabled).
+export class ContextWikiUnavailableError extends Error {
+ status = 403;
+ constructor(message: string) {
+ super(message);
+ this.name = "ContextWikiUnavailableError";
+ }
+}
+
+/** DRF error bodies carry the human-readable message in `detail`. */
+function readDetail(error: ApiRequestError): string {
+ const body = error.body as { detail?: string } | null;
+ return body?.detail ?? error.message;
+}
+
export interface TaskArtifactUploadRequest {
name: string;
type: "output" | "user_attachment" | "skill_bundle";
@@ -2943,6 +3007,121 @@ export class PostHogAPIClient {
return all;
}
+ // ---- Organization context wiki (context_layer) ------------------------
+ // Org-scoped: the wiki is one repo per organization, shared across projects.
+ // 404 means the wiki was never enabled; 403 means it exists but is dark
+ // because the organization has private projects.
+
+ // GET with the wiki's shared read semantics: 404 (never enabled or missing
+ // page) reads as null, 403 (privacy guard) as ContextWikiUnavailableError.
+ private async getContextWikiResource<T>(urlPath: string): Promise<T | null> {
+ try {
+ const response = await this.api.fetcher.fetch({
+ method: "get",
+ url: new URL(`${this.api.baseUrl}${urlPath}`),
+ path: urlPath,
+ });
+ return (await response.json()) as T;
+ } catch (error) {
+ if (error instanceof ApiRequestError) {
+ if (error.status === 404) return null;
+ if (error.status === 403) {
+ throw new ContextWikiUnavailableError(readDetail(error));
+ }
+ }
+ throw error;
+ }
+ }
+
+ async getContextWikiTree(): Promise<ContextWikiTree | null> {
+ return this.getContextWikiResource<ContextWikiTree>(
+ `/api/organizations/@current/context_layer/tree/`,
+ );
+ }
+
+ async getContextWikiPage(path: string): Promise<ContextWikiPage | null> {
+ return this.getContextWikiResource<ContextWikiPage>(
+ `/api/organizations/@current/context_layer/pages/?path=${encodeURIComponent(path)}`,
+ );
+ }
+
+ async getContextWikiHealthReport(): Promise<ContextWikiHealthReport | null> {
+ return this.getContextWikiResource<ContextWikiHealthReport>(
+ `/api/organizations/@current/context_layer/wiki/report/`,
+ );
+ }
+
+ /**
+ * Full-content page write guarded by `baseHead` optimistic concurrency.
+ * The server holds a per-org writer lock shared with agent commit landings;
+ * a lock-busy 429 surfaces as ApiRequestError and is safe to retry with the
+ * same base head — callers configure that retry (see
+ * `useContextWikiPageMutation`). 409 (stale base head) and 400 (lint) are
+ * the actionable failures.
+ */
+ async putContextWikiPage(input: {
+ path: string;
+ content: string;
+ baseHead: string;
+ }): Promise<{ head_sha: string }> {
+ const urlPath = `/api/organizations/@current/context_layer/pages/`;
+ try {
+ const response = await this.api.fetcher.fetch({
+ method: "put",
+ url: new URL(`${this.api.baseUrl}${urlPath}`),
+ path: urlPath,
+ overrides: {
+ body: JSON.stringify({
+ path: input.path,
+ content: input.content,
+ base_head: input.baseHead,
+ }),
+ },
+ });
+ return (await response.json()) as { head_sha: string };
+ } catch (error) {
+ if (!(error instanceof ApiRequestError)) throw error;
+ if (error.status === 409) {
+ const body = error.body as { current_head?: string } | null;
+ throw new ContextWikiConflictError(body?.current_head ?? null);
+ }
+ if (error.status === 400) {
+ const body = error.body as {
+ detail?: string;
+ errors?: string[];
+ } | null;
+ throw new ContextWikiLintError(
+ body?.detail ?? "The change violates the wiki structure.",
+ body?.errors ?? [],
+ );
+ }
+ if (error.status === 403) {
+ throw new ContextWikiUnavailableError(readDetail(error));
+ }
+ throw error;
+ }
+ }
+
+ async enableContextWiki(): Promise<{ head_sha: string }> {
+ const urlPath = `/api/organizations/@current/context_layer/enable/`;
+ try {
+ const response = await this.api.fetcher.fetch({
+ method: "post",
+ url: new URL(`${this.api.baseUrl}${urlPath}`),
+ path: urlPath,
+ overrides: { body: JSON.stringify({}) },
+ });
+ return (await response.json()) as { head_sha: string };
+ } catch (error) {
+ if (error instanceof ApiRequestError) {
+ throw new Error(
+ `Failed to enable the context wiki: ${readDetail(error)}`,
+ );
+ }
+ throw error;
+ }
+ }
+
// A channel's system-announcement feed (context created, CONTEXT.md being
// built), chronological. Durable + team-visible, rendered alongside task cards.
async getChannelFeed(channelId: string): Promise<ChannelFeedMessage[]> {
diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.ts
index ee551cf5ec88..2f33adbba72a 100644
--- a/products/desktop/packages/shared/src/flags.ts
+++ b/products/desktop/packages/shared/src/flags.ts
@@ -75,3 +75,5 @@ export const BEDROCK_LLM_GATEWAY_FLAG = "bedrock-llm-gateway";
export const BEDROCK_GATEWAY_VARIANTS = ["test", "control"] as const;
export type BedrockGatewayVariant = (typeof BEDROCK_GATEWAY_VARIANTS)[number];
+/** Gates the organization context wiki: the Context explorer in the nav rails. */
+export const CONTEXT_LAYER_FLAG = "context-layer";
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx b/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx
index 1842430b83ca..70b7d9af3445 100644
--- a/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx
+++ b/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx
@@ -1,4 +1,5 @@
import {
+ BookOpenTextIcon,
BrainIcon,
PlugsConnectedIcon,
RobotIcon,
@@ -121,7 +122,13 @@ type TabRef = {
// The top-level app pages that can be a tab. Keyed by useAppView's view.type;
// each maps to its canonical route (a task/canvas/channel tab has its own
// route, these don't) plus the strip's label + icon.
-type AppView = "inbox" | "agents" | "skills" | "mcp-servers" | "command-center";
+type AppView =
+ | "inbox"
+ | "agents"
+ | "skills"
+ | "mcp-servers"
+ | "command-center"
+ | "context";
const APP_VIEW_META: Record<AppView, { label: string; icon: ReactNode }> = {
inbox: { label: "Inbox", icon: <TrayIcon size={14} /> },
@@ -135,6 +142,7 @@ const APP_VIEW_META: Record<AppView, { label: string; icon: ReactNode }> = {
label: "Command center",
icon: <SquaresFourIcon size={14} />,
},
+ context: { label: "Context", icon: <BookOpenTextIcon size={14} /> },
};
function isAppView(value: string): value is AppView {
@@ -609,6 +617,9 @@ export function BrowserTabStrip() {
case "command-center":
navigate({ to: "/command-center", state });
break;
+ case "context":
+ navigate({ to: "/context", state });
+ break;
default: {
// Exhaustiveness guard: a new AppView value fails to compile here
// until its canonical route is wired above — so the tab-target set
diff --git a/products/desktop/packages/ui/src/features/canvas/components/NavRail.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/NavRail.test.tsx
index 96d31a19ae5e..288e4d57ff8a 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/NavRail.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/NavRail.test.tsx
@@ -52,6 +52,7 @@ vi.mock("@posthog/ui/router/navigationBridge", () => ({
navigateToInbox: (...a: unknown[]) => mocks.navigateToInbox(...a),
navigateToLoops: vi.fn(),
navigateToCommandCenter: vi.fn(),
+ navigateToSpacesContext: vi.fn(),
}));
vi.mock("@posthog/ui/shell/analytics", () => ({ track: vi.fn() }));
vi.mock("@posthog/ui/features/canvas/components/ActivityHoverCard", () => ({
diff --git a/products/desktop/packages/ui/src/features/canvas/components/NavRail.tsx b/products/desktop/packages/ui/src/features/canvas/components/NavRail.tsx
index 0e5d801e01ed..adfe70c26053 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/NavRail.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/NavRail.tsx
@@ -22,6 +22,7 @@ import {
import { useRailPane } from "@posthog/ui/features/canvas/hooks/useRailSurface";
import { useTaskActivity } from "@posthog/ui/features/canvas/hooks/useTaskActivity";
import { useCommandCenterActiveCount } from "@posthog/ui/features/command-center/useCommandCenterActiveCount";
+import { useContextLayerFlag } from "@posthog/ui/features/feature-flags/useContextLayerFlag";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
import { useInboxAllReports } from "@posthog/ui/features/inbox/hooks/useInboxAllReports";
import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";
@@ -173,6 +174,7 @@ function ActivityNavItem({
export function NavRail() {
const homeEnabled = useFeatureFlag(DESKTOP_HOME_FLAG);
const loopsEnabled = useFeatureFlag(LOOPS_FLAG, import.meta.env.DEV);
+ const contextEnabled = useContextLayerFlag();
const { counts: inboxCounts } = useInboxAllReports({
ignoreFilters: true,
@@ -195,6 +197,7 @@ export function NavRail() {
order: navItemOrder,
home: homeEnabled,
loops: loopsEnabled,
+ context: contextEnabled,
});
const settingsVisible = isNavItemVisible(navItemOverrides, "configure");
diff --git a/products/desktop/packages/ui/src/features/canvas/components/railDestinations.ts b/products/desktop/packages/ui/src/features/canvas/components/railDestinations.ts
index ffa20aa22d12..05ed113d633c 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/railDestinations.ts
+++ b/products/desktop/packages/ui/src/features/canvas/components/railDestinations.ts
@@ -1,5 +1,6 @@
import {
BellIcon,
+ BookOpenTextIcon,
EnvelopeSimple,
HouseSimple,
type IconProps,
@@ -36,6 +37,7 @@ import {
navigateToInbox,
navigateToLoops,
navigateToSpaces,
+ navigateToSpacesContext,
} from "@posthog/ui/router/navigationBridge";
import { getRouterOrNull } from "@posthog/ui/router/routerRef";
import type { ComponentType } from "react";
@@ -62,7 +64,11 @@ export interface RailDestination {
shortcut?: string;
count?: (counts: RailCounts) => number;
countTone?: CountBadgeTone;
- enabled?: (flags: { home: boolean; loops: boolean }) => boolean;
+ enabled?: (flags: {
+ home: boolean;
+ loops: boolean;
+ context: boolean;
+ }) => boolean;
}
/**
@@ -168,6 +174,15 @@ export const RAIL_DESTINATIONS: readonly RailDestination[] = [
onPick: () => navigateToLoops(),
enabled: (flags) => flags.loops,
},
+ {
+ pane: "context",
+ customizableId: "contexts",
+ label: "Context",
+ analyticsId: "contexts",
+ Icon: BookOpenTextIcon,
+ onPick: navigateToSpacesContext,
+ enabled: (flags) => flags.context,
+ },
];
// Deliberately not the shared `orderedNavItems`: its adjacency rule pins
@@ -177,15 +192,17 @@ export function visibleRailDestinations({
order,
home,
loops,
+ context,
}: {
overrides: NavItemOverrides;
order: readonly CustomizableNavItemId[];
home: boolean;
loops: boolean;
+ context: boolean;
}): readonly RailDestination[] {
const shown = RAIL_DESTINATIONS.filter(
({ customizableId, enabled }) =>
- (enabled?.({ home, loops }) ?? true) &&
+ (enabled?.({ home, loops, context }) ?? true) &&
(!customizableId || isNavItemVisible(overrides, customizableId)),
);
if (order.length === 0) return shown;
diff --git a/products/desktop/packages/ui/src/features/canvas/railPane.ts b/products/desktop/packages/ui/src/features/canvas/railPane.ts
index 7f0524c8166a..6beb67cdfaef 100644
--- a/products/desktop/packages/ui/src/features/canvas/railPane.ts
+++ b/products/desktop/packages/ui/src/features/canvas/railPane.ts
@@ -14,7 +14,8 @@ export type NavRailPane =
| "activity"
| "inbox"
| "command-center"
- | "loops";
+ | "loops"
+ | "context";
/**
* The root path of each destination.
@@ -30,6 +31,7 @@ export const RAIL_PANE_ROOT: Readonly<Record<NavRailPane, string>> = {
inbox: "/inbox",
"command-center": "/command-center",
loops: "/loops",
+ context: "/spaces/context",
};
// Spaces is absent: it takes everything nothing else claims, so listing it
@@ -40,6 +42,7 @@ const CLAIMED: readonly NavRailPane[] = [
"inbox",
"command-center",
"loops",
+ "context",
];
export function railPaneForPath(fullPath: string): NavRailPane {
diff --git a/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiHealthPane.test.ts b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiHealthPane.test.ts
new file mode 100644
index 000000000000..1be172322ee6
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiHealthPane.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+import { groupFindings } from "./ContextWikiHealthPane";
+
+describe("groupFindings", () => {
+ it("groups findings by category for the health tab", () => {
+ const findings = [
+ { category: "orphan", path: "areas/a.md", message: "No links" },
+ { category: "stale", path: "areas/b.md", message: "Old" },
+ { category: "orphan", path: "areas/c.md", message: "No links" },
+ ];
+
+ expect(groupFindings(findings)).toEqual({
+ orphan: [findings[0], findings[2]],
+ stale: [findings[1]],
+ });
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiHealthPane.tsx b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiHealthPane.tsx
new file mode 100644
index 000000000000..d17ae29aee0e
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiHealthPane.tsx
@@ -0,0 +1,95 @@
+import { WarningCircleIcon } from "@phosphor-icons/react";
+import type { ContextWikiHealthFinding } from "@posthog/api-client/posthog-client";
+import {
+ Button,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+ Heading,
+ Spinner,
+ Text,
+} from "@posthog/quill";
+import { useMemo } from "react";
+import { useContextWikiHealthReport } from "../hooks/useContextWiki";
+
+export function ContextWikiHealthPane({
+ onOpenPage,
+}: {
+ onOpenPage: (path: string) => void;
+}) {
+ const { data, isLoading, error, refetch } = useContextWikiHealthReport();
+ const groups = useMemo(() => groupFindings(data?.findings ?? []), [data]);
+
+ if (isLoading) {
+ return <Spinner className="m-auto" />;
+ }
+ if (error) {
+ return (
+ <Empty>
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <WarningCircleIcon />
+ </EmptyMedia>
+ <EmptyTitle>Couldn't load wiki health</EmptyTitle>
+ <EmptyDescription>{error.message}</EmptyDescription>
+ </EmptyHeader>
+ <Button variant="outline" onClick={() => refetch()}>
+ Try again
+ </Button>
+ </Empty>
+ );
+ }
+ if (!data?.findings.length) {
+ return (
+ <Empty>
+ <EmptyHeader>
+ <EmptyTitle>No findings — the wiki is healthy.</EmptyTitle>
+ </EmptyHeader>
+ </Empty>
+ );
+ }
+ return (
+ <div className="flex flex-col gap-4 overflow-auto p-4">
+ {Object.entries(groups).map(([category, findings]) => (
+ <section key={category} className="flex flex-col gap-2">
+ <Heading size="sm">{category.replaceAll("_", " ")}</Heading>
+ <div className="flex flex-col gap-1">
+ {findings.map((finding, index) => (
+ <Button
+ key={`${finding.path}-${index}`}
+ variant="link-muted"
+ className="h-auto justify-start"
+ onClick={() => onOpenPage(finding.path)}
+ >
+ <span className="flex flex-col items-start gap-1 text-left">
+ <Text size="sm" weight="medium">
+ {finding.path}
+ </Text>
+ <Text size="xs" variant="muted">
+ {finding.message}
+ </Text>
+ </span>
+ </Button>
+ ))}
+ </div>
+ </section>
+ ))}
+ </div>
+ );
+}
+
+export function groupFindings(
+ findings: ContextWikiHealthFinding[],
+): Record<string, ContextWikiHealthFinding[]> {
+ return findings.reduce<Record<string, ContextWikiHealthFinding[]>>(
+ (groups, finding) => {
+ const group = groups[finding.category] ?? [];
+ group.push(finding);
+ groups[finding.category] = group;
+ return groups;
+ },
+ {},
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiPagePane.images.test.tsx b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiPagePane.images.test.tsx
new file mode 100644
index 000000000000..54e3481c78d7
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiPagePane.images.test.tsx
@@ -0,0 +1,60 @@
+import { Theme } from "@radix-ui/themes";
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it, vi } from "vitest";
+
+// MarkdownRenderer's chart cards resolve data through the app shell's query
+// client; stub it so the real renderer mounts here.
+vi.mock("../../../hooks/useAuthenticatedQuery", () => ({
+ useAuthenticatedQuery: () => ({
+ isPending: true,
+ isError: false,
+ isFetched: false,
+ data: undefined,
+ }),
+}));
+
+const hoisted = vi.hoisted(() => ({
+ page: {
+ path: "AGENTS.md",
+ content: "![internal service](http://127.0.0.1/action)",
+ head_sha: "head-1",
+ } as { path: string; content: string; head_sha: string } | null,
+}));
+
+vi.mock("../hooks/useContextWiki", () => ({
+ useContextWikiPage: () => ({
+ data: hoisted.page,
+ isLoading: false,
+ error: null,
+ refetch: vi.fn(),
+ }),
+ useContextWikiPageMutation: () => ({
+ mutate: vi.fn(),
+ error: null,
+ isPending: false,
+ reset: vi.fn(),
+ }),
+}));
+
+// The real client pulls in @posthog/shared, which this package's vitest config
+// does not resolve; the pane only needs these two error classes for instanceof.
+vi.mock("@posthog/api-client/posthog-client", () => ({
+ ContextWikiConflictError: class ContextWikiConflictError extends Error {},
+ ContextWikiLintError: class ContextWikiLintError extends Error {},
+}));
+
+import { ContextWikiPagePane } from "./ContextWikiPagePane";
+
+describe("ContextWikiPagePane markdown", () => {
+ it("does not load remote images embedded in a wiki page", () => {
+ const html = renderToStaticMarkup(
+ <Theme>
+ <ContextWikiPagePane path="AGENTS.md" />
+ </Theme>,
+ );
+
+ expect(html).toContain("Remote image blocked: internal service");
+ expect(html).not.toContain("<img");
+ expect(html).not.toContain("http://127.0.0.1/action");
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiPagePane.test.tsx b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiPagePane.test.tsx
new file mode 100644
index 000000000000..1298a1414a8e
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiPagePane.test.tsx
@@ -0,0 +1,147 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { ContextWikiPagePane } from "./ContextWikiPagePane";
+
+const hoisted = vi.hoisted(() => ({
+ page: {
+ path: "AGENTS.md",
+ content: "original content",
+ head_sha: "head-1",
+ updated_at: "2026-08-22T12:00:00Z",
+ } as {
+ path: string;
+ content: string;
+ head_sha: string;
+ updated_at: string;
+ } | null,
+ saveError: null as Error | null,
+ mutate: vi.fn(),
+ reset: vi.fn(),
+ refetch: vi.fn(),
+}));
+
+vi.mock("../hooks/useContextWiki", () => ({
+ useContextWikiPage: () => ({
+ data: hoisted.page,
+ isLoading: false,
+ error: null,
+ refetch: hoisted.refetch,
+ }),
+ useContextWikiPageMutation: () => ({
+ mutate: hoisted.mutate,
+ error: hoisted.saveError,
+ isPending: false,
+ reset: hoisted.reset,
+ }),
+}));
+
+vi.mock("@posthog/ui/features/editor/components/MarkdownRenderer", () => ({
+ MarkdownRenderer: ({ content }: { content: string }) => <div>{content}</div>,
+}));
+
+// The real client pulls in @posthog/shared, which this package's vitest config
+// does not resolve. The pane only needs these two classes for the instanceof
+// checks on a failed save.
+vi.mock("@posthog/api-client/posthog-client", () => ({
+ ContextWikiConflictError: class ContextWikiConflictError extends Error {
+ currentHead: string | null;
+ constructor(currentHead: string | null) {
+ super("The wiki changed since you started editing");
+ this.currentHead = currentHead;
+ }
+ },
+ ContextWikiLintError: class ContextWikiLintError extends Error {},
+}));
+
+const { ContextWikiConflictError } = await import(
+ "@posthog/api-client/posthog-client"
+);
+
+describe("ContextWikiPagePane", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ hoisted.saveError = null;
+ hoisted.page = {
+ path: "AGENTS.md",
+ content: "original content",
+ head_sha: "head-1",
+ updated_at: "2026-08-22T12:00:00Z",
+ };
+ });
+
+ it("shows when the page was last updated", () => {
+ render(<ContextWikiPagePane path="AGENTS.md" />);
+
+ expect(screen.getByText("Updated")).toBeVisible();
+ });
+
+ it("saves against the head the draft was seeded from, not a head that moved under it mid-edit", async () => {
+ const user = userEvent.setup();
+
+ const { rerender } = render(<ContextWikiPagePane path="AGENTS.md" />);
+
+ await user.click(screen.getByRole("button", { name: "Edit" }));
+ fireEvent.change(
+ screen.getByPlaceholderText("Write markdown for this page…"),
+ { target: { value: "my local edits" } },
+ );
+
+ // An agent lands a commit in the background; a focus refetch moves the
+ // page head under the live draft.
+ hoisted.page = {
+ path: "AGENTS.md",
+ content: "agent content",
+ head_sha: "head-2",
+ updated_at: "2026-08-22T12:05:00Z",
+ };
+ rerender(<ContextWikiPagePane path="AGENTS.md" />);
+
+ await user.click(screen.getByRole("button", { name: "Save" }));
+
+ expect(hoisted.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: "my local edits",
+ baseHead: "head-1",
+ }),
+ expect.anything(),
+ );
+ });
+
+ it("keeps the draft when a save conflicts, and retries it against the new head", async () => {
+ const user = userEvent.setup();
+
+ const { rerender } = render(<ContextWikiPagePane path="AGENTS.md" />);
+ await user.click(screen.getByRole("button", { name: "Edit" }));
+ fireEvent.change(
+ screen.getByPlaceholderText("Write markdown for this page…"),
+ { target: { value: "my local edits" } },
+ );
+
+ // The save loses the race, and the refetch that follows brings in the
+ // other writer's content.
+ hoisted.saveError = new ContextWikiConflictError("head-9");
+ hoisted.page = {
+ path: "AGENTS.md",
+ content: "their content",
+ head_sha: "head-9",
+ updated_at: "2026-08-22T12:10:00Z",
+ };
+ rerender(<ContextWikiPagePane path="AGENTS.md" />);
+
+ // The draft the banner tells them about has to still be there.
+ expect(
+ screen.getByPlaceholderText("Write markdown for this page…"),
+ ).toHaveValue("my local edits");
+
+ await user.click(screen.getByRole("button", { name: "Save mine anyway" }));
+
+ expect(hoisted.mutate).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ content: "my local edits",
+ baseHead: "head-9",
+ }),
+ expect.anything(),
+ );
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiPagePane.tsx b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiPagePane.tsx
new file mode 100644
index 000000000000..95de3d4b47ec
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiPagePane.tsx
@@ -0,0 +1,288 @@
+import {
+ ContextWikiConflictError,
+ ContextWikiLintError,
+} from "@posthog/api-client/posthog-client";
+import {
+ Button,
+ cn,
+ Spinner,
+ Textarea,
+ ToggleGroup,
+ ToggleGroupItem,
+} from "@posthog/quill";
+import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";
+import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";
+import { useState } from "react";
+import type { Components } from "react-markdown";
+import {
+ useContextWikiPage,
+ useContextWikiPageMutation,
+} from "../hooks/useContextWiki";
+
+type Mode = "rendered" | "edit";
+
+/** An unsaved edit, plus the head it is based on. */
+export interface WikiDraft {
+ content: string;
+ baseHead: string | null;
+}
+
+interface ContextWikiPagePaneProps {
+ path: string;
+ /**
+ * Drafts can be held above the pane so they survive it unmounting — the
+ * explorer keys the pane by path, so a page switch would otherwise destroy
+ * one. Omit all three and the pane keeps its own draft instead.
+ */
+ draft?: WikiDraft;
+ onDraftChange?: (path: string, draft: WikiDraft) => void;
+ onDraftDiscard?: (path: string) => void;
+}
+
+// The draft lives above the pane when the caller manages it, and inside
+// otherwise. `useState` runs either way, so the branch is safe.
+function useDraft(
+ external: WikiDraft | undefined,
+ onChange: ContextWikiPagePaneProps["onDraftChange"],
+ onDiscard: ContextWikiPagePaneProps["onDraftDiscard"],
+): [
+ WikiDraft | undefined,
+ (path: string, draft: WikiDraft) => void,
+ (path: string) => void,
+] {
+ const [internal, setInternal] = useState<WikiDraft | undefined>(undefined);
+ if (onChange && onDiscard) {
+ return [external, onChange, onDiscard];
+ }
+ return [
+ internal,
+ (_path, draft) => setInternal(draft),
+ () => setInternal(undefined),
+ ];
+}
+
+// Wiki pages are org-shared and agent-writable, so their markdown is untrusted.
+// A remote <img> would make every viewer's machine issue a GET to an
+// author-chosen URL, which is a tracking beacon or an internal-network probe.
+// Block images the way ChatMarkdown does; there is no wiki image-upload path,
+// so nothing legitimate is lost.
+const wikiMarkdownComponents: Partial<Components> = {
+ img: ({ alt }) => (
+ <span className="text-[13px] text-gray-10">
+ Remote image blocked{alt ? `: ${alt}` : ""}
+ </span>
+ ),
+};
+
+/**
+ * One wiki page: rendered markdown, or a plain-text editor. Saves send the
+ * head the page was loaded at, so a write that races another editor (or an
+ * agent's commit) comes back as a conflict banner instead of clobbering.
+ */
+export function ContextWikiPagePane({
+ path,
+ draft: externalDraft,
+ onDraftChange,
+ onDraftDiscard,
+}: ContextWikiPagePaneProps) {
+ const { data: page, isLoading, error, refetch } = useContextWikiPage(path);
+ const save = useContextWikiPageMutation();
+
+ // Reopen straight into the editor when this page already has a draft, so
+ // coming back to it shows the unsaved text rather than the saved page.
+ const [mode, setMode] = useState<Mode>(externalDraft ? "edit" : "rendered");
+ const [draft, setDraft, discardDraft] = useDraft(
+ externalDraft,
+ onDraftChange,
+ onDraftDiscard,
+ );
+
+ // A draft carries the head it was based on. Pinned at the first keystroke so a
+ // background refetch (refetchOnWindowFocus fires on app-switch) can't move it
+ // under the draft — otherwise a save would adopt the moved head and silently
+ // overwrite the concurrent commit instead of coming back as a 409 conflict.
+ const hasDraft = draft !== undefined;
+ const content = draft?.content ?? page?.content ?? "";
+ const baseHead = draft?.baseHead ?? page?.head_sha ?? null;
+
+ if (isLoading) {
+ return (
+ <div className="flex flex-1 items-center justify-center">
+ <Spinner className="size-5" />
+ </div>
+ );
+ }
+
+ if (error || !page) {
+ return (
+ <div className="flex flex-1 flex-col items-center justify-center gap-2 text-[13px] text-gray-10">
+ <span>
+ {error
+ ? `Couldn't load this page: ${error.message}`
+ : "This page no longer exists in the wiki."}
+ </span>
+ <Button variant="outline" size="sm" onClick={() => refetch()}>
+ Try again
+ </Button>
+ </div>
+ );
+ }
+
+ const commit = (against: string | null) => {
+ save.mutate(
+ { path, content, baseHead: against ?? page.head_sha },
+ {
+ onSuccess: () => {
+ discardDraft(path);
+ setMode("rendered");
+ },
+ // Pull the page the other writer landed so the Rendered tab shows what
+ // the draft is now up against. The draft itself is left alone.
+ onError: () => void refetch(),
+ },
+ );
+ };
+
+ const conflict =
+ save.error instanceof ContextWikiConflictError ? save.error : null;
+ const lintError =
+ save.error instanceof ContextWikiLintError ? save.error : null;
+
+ return (
+ <div className="flex min-w-0 flex-1 flex-col overflow-hidden">
+ <div className="flex shrink-0 items-center justify-between gap-3 border-b border-b-(--gray-5) px-4 py-2">
+ <div className="flex min-w-0 items-center gap-3">
+ <ToggleGroup
+ value={[mode]}
+ onValueChange={(next: string[]) => {
+ const selected = next[0];
+ if (selected) setMode(selected as Mode);
+ }}
+ aria-label="Page view mode"
+ className="gap-1"
+ >
+ <ToggleGroupItem value="rendered" size="sm" variant="outline">
+ Rendered
+ </ToggleGroupItem>
+ <ToggleGroupItem value="edit" size="sm" variant="outline">
+ Edit
+ </ToggleGroupItem>
+ </ToggleGroup>
+ {/* The page's location inside the wiki repo, for agents and deep
+ links: this is the path harnesses see under the mounted wiki. */}
+ <code className="truncate text-[12px] text-gray-10">{path}</code>
+ <span className="flex shrink-0 items-center gap-1 text-[11px] text-gray-10">
+ Updated <RelativeTimestamp timestamp={page.updated_at} />
+ </span>
+ </div>
+ {mode === "edit" ? (
+ <div className="flex shrink-0 items-center gap-2">
+ {hasDraft ? (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ discardDraft(path);
+ save.reset();
+ }}
+ disabled={save.isPending}
+ >
+ Discard
+ </Button>
+ ) : null}
+ <Button
+ variant="primary"
+ size="sm"
+ onClick={() => commit(baseHead)}
+ disabled={save.isPending || !hasDraft}
+ >
+ {save.isPending ? <Spinner className="size-3.5" /> : null}
+ Save
+ </Button>
+ </div>
+ ) : null}
+ </div>
+
+ {save.error ? (
+ <div
+ className={cn(
+ "mx-4 mt-3 rounded-(--radius-2) border px-3 py-2 text-[12px]",
+ conflict
+ ? "border-(--amber-6) bg-(--amber-2) text-(--amber-11)"
+ : "border-(--red-6) bg-(--red-2) text-(--red-11)",
+ )}
+ >
+ {conflict ? (
+ <div className="flex items-center justify-between gap-3">
+ <span>
+ Someone else changed this page while you were editing. Your
+ edits are still here — switch to Rendered to read their version.
+ </span>
+ <div className="flex shrink-0 items-center gap-2">
+ {/* Both ways out are explicit: nothing throws the draft away
+ on the user's behalf. */}
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ discardDraft(path);
+ save.reset();
+ }}
+ disabled={save.isPending}
+ >
+ Discard mine
+ </Button>
+ <Button
+ variant="primary"
+ size="sm"
+ onClick={() => commit(conflict.currentHead)}
+ disabled={save.isPending}
+ >
+ Save mine anyway
+ </Button>
+ </div>
+ </div>
+ ) : lintError ? (
+ <div className="flex flex-col gap-1">
+ <span>{lintError.message}</span>
+ {lintError.errors.length > 0 ? (
+ <ul className="list-disc pl-4">
+ {lintError.errors.map((message) => (
+ <li key={message}>{message}</li>
+ ))}
+ </ul>
+ ) : null}
+ </div>
+ ) : (
+ <span>Couldn't save this page: {save.error.message}</span>
+ )}
+ </div>
+ ) : null}
+
+ {mode === "edit" ? (
+ <div className="flex min-h-0 flex-1 p-4">
+ <Textarea
+ value={content}
+ onChange={(e) =>
+ setDraft(path, { content: e.target.value, baseHead })
+ }
+ // Locked while the write is in flight: a successful save drops the
+ // draft, so anything typed during the window would be lost.
+ disabled={save.isPending}
+ placeholder="Write markdown for this page…"
+ className="min-h-0 flex-1 resize-none font-mono text-[13px]"
+ />
+ </div>
+ ) : (
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <div className="p-4 text-[13px]">
+ <MarkdownRenderer
+ content={page.content}
+ componentsOverride={wikiMarkdownComponents}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiView.test.tsx b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiView.test.tsx
new file mode 100644
index 000000000000..29dc8ed4a295
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiView.test.tsx
@@ -0,0 +1,108 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { ContextWikiView } from "./ContextWikiView";
+
+const hoisted = vi.hoisted(() => ({
+ paths: ["AGENTS.md", "channels/growth.md"],
+ mutate: vi.fn(),
+ reset: vi.fn(),
+ refetch: vi.fn(),
+}));
+
+vi.mock("../hooks/useContextWiki", () => ({
+ useContextWikiTree: () => ({
+ data: { head_sha: "head-1", paths: hoisted.paths },
+ isLoading: false,
+ error: null,
+ refetch: hoisted.refetch,
+ }),
+ useContextWikiHealthReport: () => ({
+ data: { head_sha: "head-1", findings: [] },
+ isLoading: false,
+ error: null,
+ refetch: hoisted.refetch,
+ }),
+ useEnableContextWiki: () => ({
+ mutate: vi.fn(),
+ isPending: false,
+ error: null,
+ }),
+ useContextWikiPage: (path: string) => ({
+ data: { path, content: `saved ${path}`, head_sha: "head-1" },
+ isLoading: false,
+ error: null,
+ refetch: hoisted.refetch,
+ }),
+ useContextWikiPageMutation: () => ({
+ mutate: hoisted.mutate,
+ error: null,
+ isPending: false,
+ reset: hoisted.reset,
+ }),
+}));
+
+// Stand in for the shared tree so the test drives selection through a stable
+// button per page instead of the explorer's internal DOM.
+vi.mock("@posthog/ui/primitives/FileExplorer", () => ({
+ FileExplorer: ({
+ onSelectPath,
+ children,
+ }: {
+ onSelectPath: (path: string) => void;
+ children: React.ReactNode;
+ }) => (
+ <div>
+ {hoisted.paths.map((path) => (
+ <button key={path} type="button" onClick={() => onSelectPath(path)}>
+ {`select ${path}`}
+ </button>
+ ))}
+ {children}
+ </div>
+ ),
+}));
+
+vi.mock("@posthog/ui/hooks/useSetHeaderContent", () => ({
+ useSetHeaderContent: () => {},
+}));
+
+vi.mock("@posthog/ui/features/editor/components/MarkdownRenderer", () => ({
+ MarkdownRenderer: ({ content }: { content: string }) => <div>{content}</div>,
+}));
+
+vi.mock("@posthog/api-client/posthog-client", () => ({
+ ContextWikiConflictError: class ContextWikiConflictError extends Error {},
+ ContextWikiLintError: class ContextWikiLintError extends Error {},
+ ContextWikiUnavailableError: class ContextWikiUnavailableError extends Error {},
+}));
+
+describe("ContextWikiView", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("keeps an unsaved draft when another page is opened and this one comes back", async () => {
+ const user = userEvent.setup();
+ render(<ContextWikiView />);
+
+ await user.click(screen.getByRole("button", { name: "Edit" }));
+ fireEvent.change(
+ screen.getByPlaceholderText("Write markdown for this page…"),
+ { target: { value: "half-written thought" } },
+ );
+
+ // The explorer sits beside the editor, so clicking a sibling page mid-edit
+ // is ordinary use — and used to discard the draft with the pane.
+ await user.click(
+ screen.getByRole("button", { name: "select channels/growth.md" }),
+ );
+ expect(screen.queryByDisplayValue("half-written thought")).toBeNull();
+
+ await user.click(screen.getByRole("button", { name: "select AGENTS.md" }));
+
+ expect(
+ screen.getByPlaceholderText("Write markdown for this page…"),
+ ).toHaveValue("half-written thought");
+ });
+});
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
new file mode 100644
index 000000000000..47e00827abc9
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/context-wiki/components/ContextWikiView.tsx
@@ -0,0 +1,198 @@
+import { BookOpenTextIcon, LockSimpleIcon } from "@phosphor-icons/react";
+import { ContextWikiUnavailableError } from "@posthog/api-client/posthog-client";
+import {
+ Button,
+ Empty,
+ EmptyContent,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+ Spinner,
+} from "@posthog/quill";
+import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";
+import { FileExplorer } from "@posthog/ui/primitives/FileExplorer";
+import {
+ PageHeader,
+ PageHeaderDescription,
+ PageHeaderHeading,
+ PageHeaderTitle,
+ PageHeaderTitleRow,
+} from "@posthog/ui/primitives/PageHeader";
+import { useCallback, useMemo, useState } from "react";
+import {
+ useContextWikiTree,
+ useEnableContextWiki,
+} from "../hooks/useContextWiki";
+import { buildWikiTree } from "../wikiTree";
+import { ContextWikiPagePane, type WikiDraft } from "./ContextWikiPagePane";
+
+/**
+ * The organization context wiki explorer: a tree of every wiki page on the
+ * left, the selected page (rendered or editable) on the right. Reads and
+ * writes go through the same head-guarded pages API agents use, so concurrent
+ * edits surface as conflicts instead of overwrites.
+ */
+export function ContextWikiView() {
+ // Root-level page: its own header names the view, so the breadcrumb row
+ // collapses (same treatment as Command Center).
+ useSetHeaderContent(null);
+
+ return (
+ <div className="flex h-full flex-col overflow-hidden">
+ <PageHeader>
+ <PageHeaderHeading>
+ <PageHeaderTitleRow>
+ <PageHeaderTitle>Context</PageHeaderTitle>
+ </PageHeaderTitleRow>
+ <PageHeaderDescription>
+ The shared wiki agents read before they work and update as they
+ learn. Pages are markdown files in one organization-wide repo.
+ </PageHeaderDescription>
+ </PageHeaderHeading>
+ </PageHeader>
+ <div className="min-h-0 flex-1">
+ <ContextWikiBody />
+ </div>
+ </div>
+ );
+}
+
+// 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.
+function ContextWikiBody() {
+ const { data: tree, isLoading, error, refetch } = useContextWikiTree();
+ const enable = useEnableContextWiki();
+ const [selectedPath, setSelectedPath] = useState<string | null>(null);
+ // Drafts are keyed by path and held here rather than in the pane, which the
+ // explorer remounts on every selection — so switching pages mid-edit, or
+ // being moved off a page an agent deleted, no longer destroys the text.
+ const [drafts, setDrafts] = useState<Record<string, WikiDraft>>({});
+
+ const setDraft = useCallback((path: string, draft: WikiDraft) => {
+ setDrafts((current) => ({ ...current, [path]: draft }));
+ }, []);
+
+ const discardDraft = useCallback((path: string) => {
+ setDrafts(({ [path]: _discarded, ...rest }) => rest);
+ }, []);
+
+ const wikiRoot = useMemo(
+ () => (tree ? buildWikiTree(tree.paths) : null),
+ [tree],
+ );
+
+ // Fall back to the wiki's entry page (or the first page) when nothing is
+ // selected yet, or when the selected page disappeared from the tree.
+ const effectivePath = useMemo(() => {
+ if (!tree) return null;
+ if (selectedPath && tree.paths.includes(selectedPath)) return selectedPath;
+ return tree.paths.includes("AGENTS.md")
+ ? "AGENTS.md"
+ : (tree.paths[0] ?? null);
+ }, [tree, selectedPath]);
+
+ if (isLoading) {
+ return (
+ <div className="flex h-full items-center justify-center">
+ <Spinner className="size-5" />
+ </div>
+ );
+ }
+
+ if (error instanceof ContextWikiUnavailableError) {
+ return (
+ <Empty>
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <LockSimpleIcon size={28} />
+ </EmptyMedia>
+ <EmptyTitle>Context wiki unavailable</EmptyTitle>
+ <EmptyDescription>{error.message}</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ );
+ }
+
+ if (error) {
+ return (
+ <Empty>
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <BookOpenTextIcon size={28} />
+ </EmptyMedia>
+ <EmptyTitle>Couldn't load the context wiki</EmptyTitle>
+ <EmptyDescription>{error.message}</EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <Button variant="outline" size="default" onClick={() => refetch()}>
+ Try again
+ </Button>
+ </EmptyContent>
+ </Empty>
+ );
+ }
+
+ if (!wikiRoot) {
+ return (
+ <Empty>
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <BookOpenTextIcon size={28} />
+ </EmptyMedia>
+ <EmptyTitle>Set up your context wiki</EmptyTitle>
+ <EmptyDescription>
+ The context wiki is a shared set of markdown pages that agents read
+ before they work and update as they learn. Enabling it imports the
+ context your spaces already have.
+ </EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <div className="flex flex-col items-center gap-2">
+ <Button
+ variant="primary"
+ size="default"
+ onClick={() => enable.mutate()}
+ disabled={enable.isPending}
+ >
+ {enable.isPending ? <Spinner className="size-4" /> : null}
+ Enable context wiki
+ </Button>
+ {enable.error ? (
+ <span className="text-[12px] text-red-11">
+ Couldn't enable the wiki: {enable.error.message}
+ </span>
+ ) : null}
+ </div>
+ </EmptyContent>
+ </Empty>
+ );
+ }
+
+ 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>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/context-wiki/hooks/useContextWiki.test.ts b/products/desktop/packages/ui/src/features/context-wiki/hooks/useContextWiki.test.ts
new file mode 100644
index 000000000000..e1e694d229fb
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/context-wiki/hooks/useContextWiki.test.ts
@@ -0,0 +1,49 @@
+import { ApiRequestError } from "@posthog/api-client/fetcher";
+import { describe, expect, it } from "vitest";
+import { shouldRetryWikiWrite, wikiWriteRetryDelay } from "./useContextWiki";
+
+describe("context wiki write retry", () => {
+ const lockBusy = new ApiRequestError(429, "writer lock busy");
+
+ it.each([
+ [0, true],
+ [1, true],
+ [2, true],
+ [3, false],
+ [4, false],
+ ])(
+ "retries a lock-busy 429 only while under the attempt cap (failureCount %i -> %s)",
+ (failureCount, expected) => {
+ expect(shouldRetryWikiWrite(failureCount, lockBusy)).toBe(expected);
+ },
+ );
+
+ // A conflict (409) or lint rejection (400) must surface to the caller's
+ // banner, not be retried — retrying would mask it and hammer the lock.
+ it.each([[409], [400], [404], [500]])(
+ "never retries a non-429 status (%i)",
+ (status) => {
+ expect(shouldRetryWikiWrite(0, new ApiRequestError(status, "x"))).toBe(
+ false,
+ );
+ },
+ );
+
+ it.each([
+ ["a plain Error", new Error("network down")],
+ ["undefined", undefined],
+ ])("never retries a non-API error (%s)", (_label, error) => {
+ expect(shouldRetryWikiWrite(0, error)).toBe(false);
+ });
+
+ it.each([
+ [0, 400],
+ [1, 800],
+ [2, 1200],
+ ])(
+ "backs off linearly between retries (attempt %i -> %ims)",
+ (attempt, ms) => {
+ expect(wikiWriteRetryDelay(attempt)).toBe(ms);
+ },
+ );
+});
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
new file mode 100644
index 000000000000..d32335e98554
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/context-wiki/hooks/useContextWiki.ts
@@ -0,0 +1,107 @@
+import { requestErrorStatus } from "@posthog/api-client/fetcher";
+import type {
+ ContextWikiHealthReport,
+ ContextWikiPage,
+ ContextWikiTree,
+} from "@posthog/api-client/posthog-client";
+import { useAuthenticatedMutation } from "@posthog/ui/hooks/useAuthenticatedMutation";
+import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";
+import { useQueryClient } from "@tanstack/react-query";
+
+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;
+
+/** `null` data means the wiki was never enabled for this organization (404). */
+export function useContextWikiTree() {
+ return useAuthenticatedQuery<ContextWikiTree | null>(
+ CONTEXT_WIKI_TREE_KEY,
+ (client) => client.getContextWikiTree(),
+ // Agents land wiki commits in the background (dream runs, task edits), so
+ // a mounted explorer revalidates rather than trusting a session-old tree.
+ { staleTime: 30_000, refetchOnMount: "always" },
+ );
+}
+
+export function useContextWikiPage(path: string) {
+ return useAuthenticatedQuery<ContextWikiPage | null>(
+ CONTEXT_WIKI_PAGE_KEY(path),
+ (client) => client.getContextWikiPage(path),
+ // The pane remounts per selection, so revisits inside this window render
+ // from cache; a stale-head save still fails safe via the 409 conflict.
+ { staleTime: 30_000 },
+ );
+}
+
+export function useContextWikiHealthReport() {
+ return useAuthenticatedQuery<ContextWikiHealthReport | null>(
+ CONTEXT_WIKI_REPORT_KEY,
+ (client) => client.getContextWikiHealthReport(),
+ { staleTime: 30_000, refetchOnMount: "always" },
+ );
+}
+
+// How many times a lock-busy write is retried before the 429 surfaces.
+const WIKI_WRITE_MAX_RETRIES = 3;
+
+/**
+ * A 429 means the org's wiki writer lock is busy (an agent is landing a
+ * commit). Retrying with the same base head is safe; anything else — a 409
+ * conflict, a 400 lint rejection, a network error — must fall through to the
+ * caller's conflict/lint handling rather than being retried.
+ */
+export function shouldRetryWikiWrite(
+ failureCount: number,
+ error: unknown,
+): boolean {
+ return (
+ failureCount < WIKI_WRITE_MAX_RETRIES && requestErrorStatus(error) === 429
+ );
+}
+
+// Backoff between lock-busy retries: 400ms, 800ms, then 1200ms.
+export function wikiWriteRetryDelay(failureCount: number): number {
+ return 400 * (failureCount + 1);
+}
+
+export function useContextWikiPageMutation() {
+ const queryClient = useQueryClient();
+ return useAuthenticatedMutation<
+ { head_sha: string },
+ Error,
+ { path: string; content: string; baseHead: string }
+ >((client, input) => client.putContextWikiPage(input), {
+ retry: shouldRetryWikiWrite,
+ retryDelay: wikiWriteRetryDelay,
+ onSuccess: (result, input) => {
+ // The PUT echoes everything the caches need, so write them in place
+ // instead of refetching content the client just uploaded.
+ queryClient.setQueryData<ContextWikiPage>(
+ CONTEXT_WIKI_PAGE_KEY(input.path),
+ {
+ path: input.path,
+ content: input.content,
+ head_sha: result.head_sha,
+ updated_at: new Date().toISOString(),
+ },
+ );
+ queryClient.setQueryData<ContextWikiTree | null>(
+ CONTEXT_WIKI_TREE_KEY,
+ (tree) => (tree ? { ...tree, head_sha: result.head_sha } : tree),
+ );
+ },
+ });
+}
+
+export function useEnableContextWiki() {
+ const queryClient = useQueryClient();
+ return useAuthenticatedMutation<{ head_sha: string }, Error, void>(
+ (client) => client.enableContextWiki(),
+ {
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: CONTEXT_WIKI_TREE_KEY });
+ },
+ },
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/context-wiki/wikiTree.test.ts b/products/desktop/packages/ui/src/features/context-wiki/wikiTree.test.ts
new file mode 100644
index 000000000000..303c428a7c2d
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/context-wiki/wikiTree.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vitest";
+import { buildWikiTree } from "./wikiTree";
+
+describe("buildWikiTree", () => {
+ it("nests flat paths into folders, creating missing intermediates", () => {
+ const root = buildWikiTree([
+ "AGENTS.md",
+ "guides/deep/nested.md",
+ "channels/growth.md",
+ ]);
+
+ expect(root.children).toEqual([
+ { type: "file", name: "AGENTS", path: "AGENTS.md" },
+ {
+ type: "folder",
+ name: "channels",
+ children: [
+ { type: "file", name: "growth", path: "channels/growth.md" },
+ ],
+ },
+ {
+ type: "folder",
+ name: "guides",
+ children: [
+ {
+ type: "folder",
+ name: "deep",
+ children: [
+ { type: "file", name: "nested", path: "guides/deep/nested.md" },
+ ],
+ },
+ ],
+ },
+ ]);
+ });
+
+ it("sorts AGENTS.md first within its folder, other pages alphabetically", () => {
+ const root = buildWikiTree([
+ "channels/zeta.md",
+ "channels/AGENTS.md",
+ "channels/alpha.md",
+ ]);
+ expect(root.children?.[0].children?.map((node) => node.name)).toEqual([
+ "AGENTS",
+ "alpha",
+ "zeta",
+ ]);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/context-wiki/wikiTree.ts b/products/desktop/packages/ui/src/features/context-wiki/wikiTree.ts
new file mode 100644
index 000000000000..ffbff880ba08
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/context-wiki/wikiTree.ts
@@ -0,0 +1,51 @@
+import type { FileTreeNode } from "@posthog/ui/primitives/FileExplorer";
+
+/**
+ * Folds the tree endpoint's flat path list into a FileExplorer tree.
+ * Within a directory, pages come before subdirectories and sort
+ * alphabetically — except AGENTS.md, which leads its directory because it is
+ * the wiki's entry page. Directories carry no `path`, so they toggle rather
+ * than select.
+ */
+export function buildWikiTree(paths: string[]): FileTreeNode {
+ const root: FileTreeNode = { type: "folder", name: "", children: [] };
+ const dirsByPath = new Map<string, FileTreeNode>([["", root]]);
+
+ const ensureDir = (dirPath: string): FileTreeNode => {
+ const existing = dirsByPath.get(dirPath);
+ if (existing) return existing;
+ const separator = dirPath.lastIndexOf("/");
+ const parent = ensureDir(
+ separator === -1 ? "" : dirPath.slice(0, separator),
+ );
+ const dir: FileTreeNode = {
+ type: "folder",
+ name: dirPath.slice(separator + 1),
+ children: [],
+ };
+ parent.children?.push(dir);
+ dirsByPath.set(dirPath, dir);
+ return dir;
+ };
+
+ for (const path of paths) {
+ const separator = path.lastIndexOf("/");
+ const dir = ensureDir(separator === -1 ? "" : path.slice(0, separator));
+ const fileName = path.slice(separator + 1);
+ dir.children?.push({
+ type: "file",
+ name: fileName.replace(/\.md$/, ""),
+ path,
+ });
+ }
+
+ for (const dir of dirsByPath.values()) {
+ dir.children?.sort((a, b) => {
+ if (a.type !== b.type) return a.type === "file" ? -1 : 1;
+ if (a.name === "AGENTS" && a.type === "file") return -1;
+ if (b.name === "AGENTS" && b.type === "file") return 1;
+ return a.name.localeCompare(b.name);
+ });
+ }
+ return root;
+}
diff --git a/products/desktop/packages/ui/src/features/feature-flags/useContextLayerFlag.test.tsx b/products/desktop/packages/ui/src/features/feature-flags/useContextLayerFlag.test.tsx
new file mode 100644
index 000000000000..550b3a905def
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/feature-flags/useContextLayerFlag.test.tsx
@@ -0,0 +1,15 @@
+import { CONTEXT_LAYER_FLAG } from "@posthog/shared";
+import { renderHook } from "@testing-library/react";
+import { expect, it, vi } from "vitest";
+import { useContextLayerFlag } from "./useContextLayerFlag";
+
+const useFeatureFlag = vi.hoisted(() => vi.fn(() => false));
+
+vi.mock("./useFeatureFlag", () => ({ useFeatureFlag }));
+
+it("keeps the context layer disabled when its flag is off", () => {
+ const { result } = renderHook(() => useContextLayerFlag());
+
+ expect(result.current).toBe(false);
+ expect(useFeatureFlag).toHaveBeenCalledWith(CONTEXT_LAYER_FLAG);
+});
diff --git a/products/desktop/packages/ui/src/features/feature-flags/useContextLayerFlag.ts b/products/desktop/packages/ui/src/features/feature-flags/useContextLayerFlag.ts
new file mode 100644
index 000000000000..2e8f968cfe81
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/feature-flags/useContextLayerFlag.ts
@@ -0,0 +1,6 @@
+import { CONTEXT_LAYER_FLAG } from "@posthog/shared";
+import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
+
+export function useContextLayerFlag(): boolean {
+ return useFeatureFlag(CONTEXT_LAYER_FLAG);
+}
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/CustomizeSidebarDialog.test.tsx b/products/desktop/packages/ui/src/features/sidebar/components/CustomizeSidebarDialog.test.tsx
index 5c62bacbc637..570865096443 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/CustomizeSidebarDialog.test.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/CustomizeSidebarDialog.test.tsx
@@ -174,6 +174,7 @@ describe("CustomizeSidebarSettings", () => {
"inbox",
"activity",
"command-center",
+ "contexts",
"configure",
]);
expect(track).toHaveBeenCalledWith(ANALYTICS_EVENTS.SIDEBAR_REORDERED, {
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/CustomizeSidebarDialog.tsx b/products/desktop/packages/ui/src/features/sidebar/components/CustomizeSidebarDialog.tsx
index 0ad24065b76e..a26f06dff83b 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/CustomizeSidebarDialog.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/CustomizeSidebarDialog.tsx
@@ -2,6 +2,7 @@ import { type DragDropEvents, DragDropProvider } from "@dnd-kit/react";
import { useSortable } from "@dnd-kit/react/sortable";
import {
Bell,
+ BookOpenTextIcon,
DotsSixVertical,
EnvelopeSimple,
SlidersHorizontal,
@@ -9,6 +10,7 @@ import {
} from "@phosphor-icons/react";
import { LOOPS_FLAG, PROJECT_BLUEBIRD_FLAG } from "@posthog/shared";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
+import { useContextLayerFlag } from "@posthog/ui/features/feature-flags/useContextLayerFlag";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
import {
CUSTOMIZABLE_NAV_ITEMS,
@@ -33,6 +35,7 @@ const ITEM_ICONS: Record<
activity: Bell,
configure: SlidersHorizontal,
loops: LoopIcon,
+ contexts: BookOpenTextIcon,
};
function sameOrder(
@@ -48,6 +51,7 @@ export function CustomizeSidebarSettings() {
PROJECT_BLUEBIRD_FLAG,
import.meta.env.DEV,
);
+ const contextEnabled = useContextLayerFlag();
const navItemOverrides = useSidebarStore((s) => s.navItemOverrides);
const navItemOrder = useSidebarStore((s) => s.navItemOrder);
const setNavItemVisible = useSidebarStore((s) => s.setNavItemVisible);
@@ -73,6 +77,7 @@ export function CustomizeSidebarSettings() {
({ id }) => {
if (id === "loops") return loopsEnabled;
if (id === "activity") return bluebirdEnabled;
+ if (id === "contexts") return contextEnabled;
return true;
},
);
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx
index 44cbd58d7c9f..c45065aedd7c 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx
@@ -48,11 +48,13 @@ vi.mock("@posthog/ui/router/navigationBridge", () => ({
navigateToActivity,
navigateToAgents,
navigateToCommandCenter,
+ navigateToContext: vi.fn(),
navigateToInbox,
navigateToLoops: vi.fn(),
navigateToMcpServers,
navigateToSkills,
navigateToWebsiteCommandCenter: vi.fn(),
+ navigateToWebsiteContext: vi.fn(),
navigateToWebsiteMcpServers: vi.fn(),
navigateToWebsiteSkills: vi.fn(),
}));
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx
index 14b7c757fc77..e7d1d4a3926b 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx
@@ -4,6 +4,7 @@ import {
type SidebarNavItem,
} from "@posthog/shared/analytics-events";
import { useCommandCenterActiveCount } from "@posthog/ui/features/command-center/useCommandCenterActiveCount";
+import { useContextLayerFlag } from "@posthog/ui/features/feature-flags/useContextLayerFlag";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
import { useInboxAllReports } from "@posthog/ui/features/inbox/hooks/useInboxAllReports";
import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";
@@ -17,18 +18,22 @@ import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";
import {
navigateToActivity,
navigateToCommandCenter,
+ navigateToContext,
navigateToInbox,
navigateToLoops,
+ navigateToSpacesContext,
} from "@posthog/ui/router/navigationBridge";
import { useAppView } from "@posthog/ui/router/useAppView";
import { openTaskInput } from "@posthog/ui/router/useOpenTask";
import { track } from "@posthog/ui/shell/analytics";
import { useCommandMenuStore } from "@posthog/ui/shell/commandMenuStore";
import { Box, Flex } from "@radix-ui/themes";
+import { useRouterState } from "@tanstack/react-router";
import type { ReactNode } from "react";
import { ActivityItem } from "./items/ActivityItem";
import { CommandCenterItem } from "./items/CommandCenterItem";
import { ConfigureItem } from "./items/ConfigureItem";
+import { ContextItem } from "./items/ContextItem";
import { InboxItem } from "./items/InboxItem";
import { LoopsItem } from "./items/LoopsItem";
import { NewTaskItem } from "./items/NewTaskItem";
@@ -66,6 +71,11 @@ export function SidebarNavSection({
PROJECT_BLUEBIRD_FLAG,
import.meta.env.DEV,
);
+ const contextEnabled = useContextLayerFlag();
+ const inSpaces = useRouterState({
+ select: (state) => state.location.pathname.startsWith("/spaces"),
+ });
+ const goContext = inSpaces ? navigateToSpacesContext : navigateToContext;
const goNewTask = () => openTaskInput();
// Active flags are pure functions of the current view — mirror what
@@ -76,6 +86,7 @@ export function SidebarNavSection({
const isInboxActive = view.type === "inbox";
const isLoopsActive = view.type === "loops";
const isCommandCenterActive = view.type === "command-center";
+ const isContextActive = view.type === "context";
// Open pull requests in the inbox — the main CTA, and the same count the inbox
// Pull requests tab shows, so the badge and the tab always agree.
@@ -123,6 +134,7 @@ export function SidebarNavSection({
const navItemAvailable: Record<CustomizableNavItemId, boolean> = {
inbox: true,
"command-center": true,
+ contexts: contextEnabled,
activity: bluebirdEnabled,
configure: true,
loops: loopsEnabled,
@@ -170,6 +182,13 @@ export function SidebarNavSection({
onClick={withNavTrack("loops", navigateToLoops, depth)}
/>
),
+ contexts: (depth) => (
+ <ContextItem
+ depth={depth}
+ isActive={isContextActive}
+ onClick={withNavTrack("contexts", goContext, depth)}
+ />
+ ),
};
const topLevelItems = orderedItems.filter(
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/ContextItem.tsx b/products/desktop/packages/ui/src/features/sidebar/components/items/ContextItem.tsx
new file mode 100644
index 000000000000..bef60c226336
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/ContextItem.tsx
@@ -0,0 +1,26 @@
+import { BookOpenTextIcon } from "@phosphor-icons/react";
+import { SidebarItem } from "../SidebarItem";
+
+interface ContextItemProps {
+ isActive: boolean;
+ onClick: () => void;
+ depth?: number;
+}
+
+export function ContextItem({
+ isActive,
+ onClick,
+ depth = 0,
+}: ContextItemProps) {
+ return (
+ <SidebarItem
+ depth={depth}
+ icon={
+ <BookOpenTextIcon size={16} weight={isActive ? "fill" : "regular"} />
+ }
+ label="Context"
+ isActive={isActive}
+ onClick={onClick}
+ />
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/sidebar/constants.test.ts b/products/desktop/packages/ui/src/features/sidebar/constants.test.ts
index 6a09f9613129..5874ab5e47e3 100644
--- a/products/desktop/packages/ui/src/features/sidebar/constants.test.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/constants.test.ts
@@ -32,7 +32,7 @@ describe("orderedNavItems", () => {
const ids = orderedNavItems(withoutConfigure).map((item) => item.id);
- expect(ids.indexOf("configure")).toBe(ids.indexOf("command-center") + 1);
+ expect(ids.indexOf("configure")).toBe(ids.indexOf("contexts") + 1);
});
it("keeps Activity directly below Inbox in an existing persisted order", () => {
@@ -45,10 +45,13 @@ describe("orderedNavItems", () => {
]).map((item) => item.id);
expect(ids.indexOf("activity")).toBe(ids.indexOf("inbox") + 1);
+ // "contexts" is absent from the persisted order (it shipped later), so it
+ // slots in after its default predecessor.
expect(ids.filter((id) => id !== "activity")).toEqual([
"inbox",
"loops",
"command-center",
+ "contexts",
"configure",
]);
});
diff --git a/products/desktop/packages/ui/src/features/sidebar/constants.ts b/products/desktop/packages/ui/src/features/sidebar/constants.ts
index d563d357e172..0962f48ca68f 100644
--- a/products/desktop/packages/ui/src/features/sidebar/constants.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/constants.ts
@@ -34,6 +34,12 @@ export const CUSTOMIZABLE_NAV_ITEMS = [
analyticsId: "command_center",
defaultVisible: true,
},
+ {
+ id: "contexts",
+ label: "Context",
+ analyticsId: "contexts",
+ defaultVisible: true,
+ },
{
id: "configure",
label: "Settings",
diff --git a/products/desktop/packages/ui/src/primitives/FileExplorer.tsx b/products/desktop/packages/ui/src/primitives/FileExplorer.tsx
new file mode 100644
index 000000000000..2c7268a2cfe7
--- /dev/null
+++ b/products/desktop/packages/ui/src/primitives/FileExplorer.tsx
@@ -0,0 +1,361 @@
+import {
+ CaretDownIcon,
+ CaretRightIcon,
+ FileIcon,
+ FolderIcon,
+ FolderOpenIcon,
+ MagnifyingGlassIcon,
+} from "@phosphor-icons/react";
+import { type ReactNode, useMemo, useState } from "react";
+import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";
+
+export interface FileTreeNode {
+ type: "file" | "folder";
+ name: string;
+ /** Set on files (and optionally folders) — the click target for selection. */
+ path?: string;
+ /** One-line annotation under the name (e.g. a skill/memory description). */
+ description?: string;
+ /** Icon override for the row. Defaults to a generic file/folder icon. */
+ icon?: ReactNode;
+ /** Right-aligned slot (e.g. an approval lock or a "needs attention" badge). */
+ trailing?: ReactNode;
+ children?: FileTreeNode[];
+}
+
+export interface FileExplorerSearchResult {
+ path: string;
+ name?: string;
+ description?: string;
+ snippet?: string;
+ score?: number;
+}
+
+interface SearchConfig {
+ query: string;
+ onChange: (query: string) => void;
+ /** Non-null = results mode (flat list). Null/undefined = tree mode. */
+ results?: FileExplorerSearchResult[] | null;
+ placeholder?: string;
+ loading?: boolean;
+}
+
+export interface FileExplorerProps {
+ tree: FileTreeNode | null;
+ selectedPath: string | null;
+ onSelectPath: (path: string) => void;
+ /** Optional search input + flat results override (e.g. memory BM25 search). */
+ search?: SearchConfig;
+ /** Top-of-left-pane action (e.g. a "+ New" button). */
+ topAction?: ReactNode;
+ /** Right-pane content — the consumer renders whatever fits the selection. */
+ children: ReactNode;
+ emptyMessage?: string;
+ loading?: boolean;
+ error?: Error | null;
+ /**
+ * Distinct localStorage key per surface so the bundle tree and the memory
+ * tree persist their widths independently.
+ */
+ storageKey: string;
+}
+
+/**
+ * Generic two-pane file explorer: a collapsible folder tree (or flat search
+ * results) on the left, arbitrary `children` on the right. Selection is
+ * controlled so URL state + refetch stay with the consumer. The same wrapper
+ * backs the read-only config bundle and the editable memory surface, so the
+ * two feel identical to navigate. Ported from the agent-console's FileExplorer.
+ */
+export function FileExplorer({
+ tree,
+ selectedPath,
+ onSelectPath,
+ search,
+ topAction,
+ children,
+ emptyMessage = "No files yet.",
+ loading,
+ error,
+ storageKey,
+}: FileExplorerProps) {
+ const searching = !!search && search.query.trim().length > 0;
+
+ return (
+ <PanelGroup
+ direction="horizontal"
+ autoSaveId={storageKey}
+ className="h-full overflow-hidden bg-(--color-panel-solid)"
+ >
+ <Panel defaultSize={24} minSize={15} maxSize={42} order={1}>
+ <div className="flex h-full flex-col bg-(--gray-2)">
+ {search || topAction ? (
+ <div className="space-y-2 border-(--gray-5) border-b px-2 py-2">
+ {search ? (
+ <div className="relative">
+ <MagnifyingGlassIcon
+ size={12}
+ className="-translate-y-1/2 pointer-events-none absolute top-1/2 left-2 text-gray-10"
+ />
+ <input
+ type="search"
+ value={search.query}
+ onChange={(e) => search.onChange(e.currentTarget.value)}
+ placeholder={search.placeholder ?? "Search…"}
+ className="h-7 w-full rounded-(--radius-1) border border-border bg-(--color-panel-solid) pr-2 pl-7 text-[12px]"
+ />
+ </div>
+ ) : null}
+ {topAction ? <div>{topAction}</div> : null}
+ </div>
+ ) : null}
+ <div className="min-h-0 flex-1 overflow-y-auto py-1.5">
+ {loading ? (
+ <div className="px-3 py-2 text-[12px] text-gray-10">Loading…</div>
+ ) : error ? (
+ <div className="px-3 py-2 text-(--red-11) text-[12px]">
+ {error.message}
+ </div>
+ ) : searching ? (
+ <SearchResultsList
+ results={search?.results ?? []}
+ loading={search?.loading}
+ selectedPath={selectedPath}
+ onSelectPath={onSelectPath}
+ />
+ ) : tree?.children && tree.children.length > 0 ? (
+ <TreeView
+ node={tree}
+ selected={selectedPath}
+ onSelect={onSelectPath}
+ depth={0}
+ />
+ ) : (
+ <div className="px-3 py-2 text-[12px] text-gray-10">
+ {emptyMessage}
+ </div>
+ )}
+ </div>
+ </div>
+ </Panel>
+ <PanelResizeHandle className="w-px bg-(--gray-5) transition-colors hover:bg-(--gray-7) data-[resize-handle-state=drag]:bg-(--accent-9)" />
+ <Panel order={2}>
+ <div className="flex h-full min-h-0 min-w-0 flex-col overflow-hidden">
+ {children}
+ </div>
+ </Panel>
+ </PanelGroup>
+ );
+}
+
+const ROW_SELECTED =
+ "bg-(--accent-3) font-medium text-gray-12 shadow-[inset_2px_0_0_0_var(--accent-9)]";
+const ROW_IDLE = "text-gray-11 hover:bg-(--gray-3) hover:text-gray-12";
+
+function subtreeContains(node: FileTreeNode, path: string | null): boolean {
+ if (!path) return false;
+ for (const child of node.children ?? []) {
+ if (child.path === path || subtreeContains(child, path)) return true;
+ }
+ return false;
+}
+
+function TreeView({
+ node,
+ selected,
+ onSelect,
+ depth,
+}: {
+ node: FileTreeNode;
+ selected: string | null;
+ onSelect: (path: string) => void;
+ depth: number;
+}) {
+ return (
+ <ul className="text-[12px]">
+ {(node.children ?? []).map((child) =>
+ child.type === "folder" ? (
+ <FolderRow
+ key={`d:${child.name}:${child.path ?? ""}`}
+ node={child}
+ selected={selected}
+ onSelect={onSelect}
+ depth={depth}
+ />
+ ) : (
+ <FileRow
+ key={`f:${child.path}`}
+ node={child}
+ selected={!!child.path && selected === child.path}
+ onSelect={onSelect}
+ depth={depth}
+ />
+ ),
+ )}
+ </ul>
+ );
+}
+
+function FolderRow({
+ node,
+ selected,
+ onSelect,
+ depth,
+}: {
+ node: FileTreeNode;
+ selected: string | null;
+ onSelect: (path: string) => void;
+ depth: number;
+}) {
+ const [open, setOpen] = useState(true);
+ const isSelected = !!node.path && selected === node.path;
+ const hasSelectedChild = useMemo(
+ () => subtreeContains(node, selected),
+ [node, selected],
+ );
+ // Auto-expand when the selection moves into a descendant. Reconciled during
+ // render (not in an effect) so the folder opens before paint.
+ const [prevHasSelectedChild, setPrevHasSelectedChild] =
+ useState(hasSelectedChild);
+ if (hasSelectedChild !== prevHasSelectedChild) {
+ setPrevHasSelectedChild(hasSelectedChild);
+ if (hasSelectedChild) setOpen(true);
+ }
+
+ return (
+ <li>
+ <button
+ type="button"
+ onClick={() => {
+ setOpen((o) => !o);
+ if (node.path) onSelect(node.path);
+ }}
+ aria-current={isSelected ? "true" : undefined}
+ className={`flex w-full cursor-pointer items-center gap-1 px-2 py-1 text-left transition-colors ${isSelected ? ROW_SELECTED : ROW_IDLE}`}
+ style={{ paddingLeft: `${8 + depth * 12}px` }}
+ >
+ {open ? (
+ <CaretDownIcon size={11} className="shrink-0" />
+ ) : (
+ <CaretRightIcon size={11} className="shrink-0" />
+ )}
+ {node.icon ??
+ (open ? (
+ <FolderOpenIcon size={14} className="shrink-0" />
+ ) : (
+ <FolderIcon size={14} className="shrink-0" />
+ ))}
+ <span className="min-w-0 flex-1 truncate">{node.name}</span>
+ {node.trailing ? (
+ <span className="ml-auto shrink-0 pl-1">{node.trailing}</span>
+ ) : null}
+ </button>
+ {open && node.children && node.children.length > 0 ? (
+ <TreeView
+ node={{ type: "folder", name: node.name, children: node.children }}
+ selected={selected}
+ onSelect={onSelect}
+ depth={depth + 1}
+ />
+ ) : null}
+ </li>
+ );
+}
+
+function FileRow({
+ node,
+ selected,
+ onSelect,
+ depth,
+}: {
+ node: FileTreeNode;
+ selected: boolean;
+ onSelect: (path: string) => void;
+ depth: number;
+}) {
+ if (!node.path) return null;
+ const path = node.path;
+ return (
+ <li>
+ <button
+ type="button"
+ onClick={() => onSelect(path)}
+ aria-current={selected ? "true" : undefined}
+ className={`flex w-full cursor-pointer items-start gap-1.5 px-2 py-1 text-left transition-colors ${selected ? ROW_SELECTED : ROW_IDLE}`}
+ style={{ paddingLeft: `${8 + depth * 12 + 16}px` }}
+ >
+ <span className="mt-px shrink-0">
+ {node.icon ?? <FileIcon size={14} className="shrink-0" />}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate">{node.name}</span>
+ {node.description ? (
+ <span className="block truncate text-[10.5px] text-gray-9">
+ {node.description}
+ </span>
+ ) : null}
+ </span>
+ {node.trailing ? (
+ <span className="mt-px shrink-0 pl-1">{node.trailing}</span>
+ ) : null}
+ </button>
+ </li>
+ );
+}
+
+function SearchResultsList({
+ results,
+ loading,
+ selectedPath,
+ onSelectPath,
+}: {
+ results: FileExplorerSearchResult[];
+ loading?: boolean;
+ selectedPath: string | null;
+ onSelectPath: (path: string) => void;
+}) {
+ if (loading) {
+ return <div className="px-3 py-2 text-[12px] text-gray-10">Searching…</div>;
+ }
+ if (results.length === 0) {
+ return (
+ <div className="px-3 py-2 text-[12px] text-gray-10">No matches.</div>
+ );
+ }
+ return (
+ <ul className="space-y-0.5 px-1">
+ {results.map((r) => {
+ const isActive = selectedPath === r.path;
+ return (
+ <li key={r.path}>
+ <button
+ type="button"
+ onClick={() => onSelectPath(r.path)}
+ aria-current={isActive ? "true" : undefined}
+ className={`flex w-full cursor-pointer flex-col gap-0.5 rounded-(--radius-1) px-2 py-1 text-left text-[12px] transition-colors ${isActive ? ROW_SELECTED : ROW_IDLE}`}
+ >
+ <div className="flex items-center justify-between gap-2">
+ <span className="truncate font-medium">{r.name ?? r.path}</span>
+ {typeof r.score === "number" ? (
+ <span className="shrink-0 text-[10px] text-gray-9">
+ {r.score.toFixed(2)}
+ </span>
+ ) : null}
+ </div>
+ {r.description ? (
+ <span className="truncate text-[10.5px] text-gray-10">
+ {r.description}
+ </span>
+ ) : null}
+ {r.snippet ? (
+ <span className="truncate text-[10.5px] text-gray-9 italic">
+ {r.snippet}
+ </span>
+ ) : null}
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
diff --git a/products/desktop/packages/ui/src/router/navigationBridge.ts b/products/desktop/packages/ui/src/router/navigationBridge.ts
index 805be5715141..7666a34719fb 100644
--- a/products/desktop/packages/ui/src/router/navigationBridge.ts
+++ b/products/desktop/packages/ui/src/router/navigationBridge.ts
@@ -195,6 +195,10 @@ export function navigateToCommandCenter(): void {
void getRouterOrNull()?.navigate({ to: "/command-center" });
}
+export function navigateToContext(): void {
+ void getRouterOrNull()?.navigate({ to: "/context" });
+}
+
export function navigateToSkills(): void {
void getRouterOrNull()?.navigate({ to: "/skills" });
}
@@ -208,6 +212,10 @@ export function navigateToSpaces(): void {
void getRouterOrNull()?.navigate({ to: "/spaces" });
}
+export function navigateToSpacesContext(): void {
+ void getRouterOrNull()?.navigate({ to: "/spaces/context" });
+}
+
export function navigateToSettings(
category: SettingsCategory,
options?: { replace?: boolean },
diff --git a/products/desktop/packages/ui/src/router/routeTree.gen.ts b/products/desktop/packages/ui/src/router/routeTree.gen.ts
index 4bbf0347f11c..720c7cc90a73 100644
--- a/products/desktop/packages/ui/src/router/routeTree.gen.ts
+++ b/products/desktop/packages/ui/src/router/routeTree.gen.ts
@@ -12,6 +12,7 @@ import { Route as rootRouteImport } from './routes/__root'
import { Route as UsageRouteImport } from './routes/usage'
import { Route as PrRouteImport } from './routes/pr'
import { Route as InboxRouteImport } from './routes/inbox'
+import { Route as ContextRouteImport } from './routes/context'
import { Route as ArchivedRouteImport } from './routes/archived'
import { Route as AgentsRouteImport } from './routes/agents'
import { Route as ShellRouteImport } from './routes/_shell'
@@ -56,6 +57,7 @@ import { Route as InboxDismissedReportIdRouteImport } from './routes/inbox/dismi
import { Route as AgentsScoutsScratchpadRouteImport } from './routes/agents/scouts.scratchpad'
import { Route as AgentsScoutsFindingsRouteImport } from './routes/agents/scouts.findings'
import { Route as AgentsScoutsSkillNameRouteImport } from './routes/agents/scouts.$skillName'
+import { Route as ShellSpacesContextRouteImport } from './routes/_shell/spaces/context'
import { Route as ShellFeedsFeedIdRouteImport } from './routes/_shell/feeds/$feedId'
import { Route as AgentsScoutsSkillNameIndexRouteImport } from './routes/agents/scouts.$skillName.index'
import { Route as ShellSpacesChannelIdIndexRouteImport } from './routes/_shell/spaces/$channelId/index'
@@ -83,6 +85,11 @@ const InboxRoute = InboxRouteImport.update({
path: '/inbox',
getParentRoute: () => rootRouteImport,
} as any)
+const ContextRoute = ContextRouteImport.update({
+ id: '/context',
+ path: '/context',
+ getParentRoute: () => rootRouteImport,
+} as any)
const ArchivedRoute = ArchivedRouteImport.update({
id: '/archived',
path: '/archived',
@@ -302,6 +309,11 @@ const AgentsScoutsSkillNameRoute = AgentsScoutsSkillNameRouteImport.update({
path: '/$skillName',
getParentRoute: () => AgentsScoutsRoute,
} as any)
+const ShellSpacesContextRoute = ShellSpacesContextRouteImport.update({
+ id: '/spaces/context',
+ path: '/spaces/context',
+ getParentRoute: () => ShellRoute,
+} as any)
const ShellFeedsFeedIdRoute = ShellFeedsFeedIdRouteImport.update({
id: '/feeds/$feedId',
path: '/feeds/$feedId',
@@ -371,6 +383,7 @@ export interface FileRoutesByFullPath {
'/': typeof ShellIndexRoute
'/agents': typeof AgentsRouteWithChildren
'/archived': typeof ArchivedRoute
+ '/context': typeof ContextRoute
'/inbox': typeof InboxRouteWithChildren
'/pr': typeof PrRoute
'/usage': typeof UsageRoute
@@ -399,6 +412,7 @@ export interface FileRoutesByFullPath {
'/settings/': typeof SettingsIndexRoute
'/website/': typeof WebsiteIndexRoute
'/feeds/$feedId': typeof ShellFeedsFeedIdRoute
+ '/spaces/context': typeof ShellSpacesContextRoute
'/agents/scouts/$skillName': typeof AgentsScoutsSkillNameRouteWithChildren
'/agents/scouts/findings': typeof AgentsScoutsFindingsRoute
'/agents/scouts/scratchpad': typeof AgentsScoutsScratchpadRoute
@@ -428,6 +442,7 @@ export interface FileRoutesByFullPath {
}
export interface FileRoutesByTo {
'/archived': typeof ArchivedRoute
+ '/context': typeof ContextRoute
'/pr': typeof PrRoute
'/usage': typeof UsageRoute
'/activity': typeof ShellActivityRoute
@@ -450,6 +465,7 @@ export interface FileRoutesByTo {
'/settings': typeof SettingsIndexRoute
'/website': typeof WebsiteIndexRoute
'/feeds/$feedId': typeof ShellFeedsFeedIdRoute
+ '/spaces/context': typeof ShellSpacesContextRoute
'/agents/scouts/findings': typeof AgentsScoutsFindingsRoute
'/agents/scouts/scratchpad': typeof AgentsScoutsScratchpadRoute
'/inbox/dismissed/$reportId': typeof InboxDismissedReportIdRoute
@@ -481,6 +497,7 @@ export interface FileRoutesById {
'/_shell': typeof ShellRouteWithChildren
'/agents': typeof AgentsRouteWithChildren
'/archived': typeof ArchivedRoute
+ '/context': typeof ContextRoute
'/inbox': typeof InboxRouteWithChildren
'/pr': typeof PrRoute
'/usage': typeof UsageRoute
@@ -510,6 +527,7 @@ export interface FileRoutesById {
'/settings/': typeof SettingsIndexRoute
'/website/': typeof WebsiteIndexRoute
'/_shell/feeds/$feedId': typeof ShellFeedsFeedIdRoute
+ '/_shell/spaces/context': typeof ShellSpacesContextRoute
'/agents/scouts/$skillName': typeof AgentsScoutsSkillNameRouteWithChildren
'/agents/scouts/findings': typeof AgentsScoutsFindingsRoute
'/agents/scouts/scratchpad': typeof AgentsScoutsScratchpadRoute
@@ -543,6 +561,7 @@ export interface FileRouteTypes {
| '/'
| '/agents'
| '/archived'
+ | '/context'
| '/inbox'
| '/pr'
| '/usage'
@@ -571,6 +590,7 @@ export interface FileRouteTypes {
| '/settings/'
| '/website/'
| '/feeds/$feedId'
+ | '/spaces/context'
| '/agents/scouts/$skillName'
| '/agents/scouts/findings'
| '/agents/scouts/scratchpad'
@@ -600,6 +620,7 @@ export interface FileRouteTypes {
fileRoutesByTo: FileRoutesByTo
to:
| '/archived'
+ | '/context'
| '/pr'
| '/usage'
| '/activity'
@@ -622,6 +643,7 @@ export interface FileRouteTypes {
| '/settings'
| '/website'
| '/feeds/$feedId'
+ | '/spaces/context'
| '/agents/scouts/findings'
| '/agents/scouts/scratchpad'
| '/inbox/dismissed/$reportId'
@@ -652,6 +674,7 @@ export interface FileRouteTypes {
| '/_shell'
| '/agents'
| '/archived'
+ | '/context'
| '/inbox'
| '/pr'
| '/usage'
@@ -681,6 +704,7 @@ export interface FileRouteTypes {
| '/settings/'
| '/website/'
| '/_shell/feeds/$feedId'
+ | '/_shell/spaces/context'
| '/agents/scouts/$skillName'
| '/agents/scouts/findings'
| '/agents/scouts/scratchpad'
@@ -713,6 +737,7 @@ export interface RootRouteChildren {
ShellRoute: typeof ShellRouteWithChildren
AgentsRoute: typeof AgentsRouteWithChildren
ArchivedRoute: typeof ArchivedRoute
+ ContextRoute: typeof ContextRoute
InboxRoute: typeof InboxRouteWithChildren
PrRoute: typeof PrRoute
UsageRoute: typeof UsageRoute
@@ -753,6 +778,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof InboxRouteImport
parentRoute: typeof rootRouteImport
}
+ '/context': {
+ id: '/context'
+ path: '/context'
+ fullPath: '/context'
+ preLoaderRoute: typeof ContextRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/archived': {
id: '/archived'
path: '/archived'
@@ -1061,6 +1093,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AgentsScoutsSkillNameRouteImport
parentRoute: typeof AgentsScoutsRoute
}
+ '/_shell/spaces/context': {
+ id: '/_shell/spaces/context'
+ path: '/spaces/context'
+ fullPath: '/spaces/context'
+ preLoaderRoute: typeof ShellSpacesContextRouteImport
+ parentRoute: typeof ShellRoute
+ }
'/_shell/feeds/$feedId': {
id: '/_shell/feeds/$feedId'
path: '/feeds/$feedId'
@@ -1149,6 +1188,7 @@ interface ShellRouteChildren {
ShellSkillsRoute: typeof ShellSkillsRoute
ShellIndexRoute: typeof ShellIndexRoute
ShellFeedsFeedIdRoute: typeof ShellFeedsFeedIdRoute
+ ShellSpacesContextRoute: typeof ShellSpacesContextRoute
ShellSpacesIndexRoute: typeof ShellSpacesIndexRoute
ShellSpacesChannelIdArtifactsRoute: typeof ShellSpacesChannelIdArtifactsRoute
ShellSpacesChannelIdCanvasesRoute: typeof ShellSpacesChannelIdCanvasesRoute
@@ -1169,6 +1209,7 @@ const ShellRouteChildren: ShellRouteChildren = {
ShellSkillsRoute: ShellSkillsRoute,
ShellIndexRoute: ShellIndexRoute,
ShellFeedsFeedIdRoute: ShellFeedsFeedIdRoute,
+ ShellSpacesContextRoute: ShellSpacesContextRoute,
ShellSpacesIndexRoute: ShellSpacesIndexRoute,
ShellSpacesChannelIdArtifactsRoute: ShellSpacesChannelIdArtifactsRoute,
ShellSpacesChannelIdCanvasesRoute: ShellSpacesChannelIdCanvasesRoute,
@@ -1322,6 +1363,7 @@ const rootRouteChildren: RootRouteChildren = {
ShellRoute: ShellRouteWithChildren,
AgentsRoute: AgentsRouteWithChildren,
ArchivedRoute: ArchivedRoute,
+ ContextRoute: ContextRoute,
InboxRoute: InboxRouteWithChildren,
PrRoute: PrRoute,
UsageRoute: UsageRoute,
diff --git a/products/desktop/packages/ui/src/router/routes/_shell/spaces/context.tsx b/products/desktop/packages/ui/src/router/routes/_shell/spaces/context.tsx
new file mode 100644
index 000000000000..dd69ae211966
--- /dev/null
+++ b/products/desktop/packages/ui/src/router/routes/_shell/spaces/context.tsx
@@ -0,0 +1,6 @@
+import { ContextWikiView } from "@posthog/ui/features/context-wiki/components/ContextWikiView";
+import { createFileRoute } from "@tanstack/react-router";
+
+export const Route = createFileRoute("/_shell/spaces/context")({
+ component: ContextWikiView,
+});
diff --git a/products/desktop/packages/ui/src/router/routes/context.tsx b/products/desktop/packages/ui/src/router/routes/context.tsx
new file mode 100644
index 000000000000..d2a45b583e85
--- /dev/null
+++ b/products/desktop/packages/ui/src/router/routes/context.tsx
@@ -0,0 +1,11 @@
+import { ContextWikiView } from "@posthog/ui/features/context-wiki/components/ContextWikiView";
+import {
+ AppPageSkeleton,
+ withRouteSkeleton,
+} from "@posthog/ui/router/routeSkeletons";
+import { createFileRoute } from "@tanstack/react-router";
+
+export const Route = createFileRoute("/context")({
+ component: ContextWikiView,
+ ...withRouteSkeleton(AppPageSkeleton),
+});
diff --git a/products/desktop/packages/ui/src/router/useAppView.ts b/products/desktop/packages/ui/src/router/useAppView.ts
index eba00b87288c..5403dca2cc85 100644
--- a/products/desktop/packages/ui/src/router/useAppView.ts
+++ b/products/desktop/packages/ui/src/router/useAppView.ts
@@ -18,6 +18,7 @@ export type AppViewType =
| "loops"
| "archived"
| "command-center"
+ | "context"
| "skills"
| "mcp-servers"
| "settings";
@@ -75,6 +76,9 @@ function deriveFromMatches(matches: Match[]): AppView {
return { type: "archived" };
case "/command-center":
return { type: "command-center" };
+ case "/context":
+ case "/spaces/context":
+ return { type: "context" };
case "/skills":
return { type: "skills" };
case "/mcp-servers":
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ddc3284006f0..68138a8472c8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -83328,6 +83328,8 @@ export namespace Schemas {
content: string;
/** Commit sha the content was read at; pass back as `base_head` on writes. */
head_sha: string;
+ /** When this page was last changed in the wiki history. */
+ updated_at: string;
}
/**