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.

12.0 KB
Raw Blame

Architecture

Read AGENTS.md first. This file documents implementation details.

Layers

apps/<host>
  boot, lifecycle, platform adapters, DI bindings
    |
    v
@posthog/ui
  React views, hooks, view-state stores, contributions
    |
    v
@posthog/core
  services, domain stores, domain schemas
    |
    v
@posthog/api-client              PostHog cloud HTTP API
@posthog/workspace-client        typed client for workspace-server
    |
    v
@posthog/workspace-server        Node capabilities: git, fs, pty, spawn, watchers

@posthog/platform                host-capability interfaces
@posthog/shared                  zero-dependency primitives

Host code boots and binds. Shared packages own reusable logic and UI. core and ui never import host transports.

Two tRPC surfaces exist:

  • @posthog/host-router: Electron main process API for its renderer.
  • @posthog/workspace-server: privileged Node backend API consumed by @posthog/workspace-client.

New task startup

New-task screens wait for the route's browser tab ID before mounting the composer. This keeps prefilled prompts in the tab's draft instead of a temporary session. Consuming a prompt clears its content, but keeps the request ID so model and mode settings can apply after their options load.

Submitting a task keeps the composer busy until creation opens the task's chat. The chat displays the submitted prompt with the current startup status until initialization ends and the transcript or error state takes over. The waiting message and composer use the same outer gutters and column width as the live chat.

Local startup retries retain the original prompt and run configuration after a failure. A failed replacement keeps its session when available, or restores the previous session with an error. A later retry can send the original prompt. A retry without a session reports failure instead of successful recovery.

Provider request rejections are non-retryable prompt failures. Desktop keeps the local session connected, restores the submitted message when the composer is still empty, and suggests starting a new task. It does not restart the session or automatically resend the rejected request.

Claude initialization includes the repository's SessionStart hooks. These hooks can prepare a new worktree and install dependencies before the SDK becomes ready. An observed setup hook gets a separate, bounded wait of ten minutes. Startup with no active setup hooks keeps its 30-second timeout. Hook progress does not extend the hook deadline. Startup phase changes and failures use the desktop log path, without recording hook commands or output. The renderer subscribes before starting an agent, so it can show active setup hooks while session/new is still pending. Startup subscriptions end on success or failure. Updates from an older run cannot change the current run's startup phase. Startup events do not count as conversation history during recovery. The model, effort and fast mode requests that follow initialization each get the same 30-second timeout. A failed or timed-out request stops the Claude process, and the startup fails with an error that names the request.

Worktree creation shows its own preparation screen and setup output. Agent startup shows one status line beside a spinner: "Starting local agent" or "Running repository setup". The submitted prompt stays visible. Prompt retention is normal behavior and needs no extra message. These are observed phases, not estimated progress percentages.

Desktop does not disable repository hooks, change repository settings, or share ignored dependency files between worktrees. Each worktree runs its configured setup in its own directory. A new worktree can need setup that an existing checkout has already completed. Setup time is not a connection failure while an observed hook remains within its deadline. The same rule applies to ordinary checkouts with slow hooks; it does not depend on a repository name or toolchain.

A connected local session only waits for its first prompt when the session still has a prompt to send. A task description or an existing run does not imply that a prompt is pending. This lets an empty session open after a failed startup instead of keeping it in the loading view. Opening it does not resend the description.

A local task without a session is idle in the space sidebar after an app restart. The sidebar shows startup only when a startup marker or a live session reports it. The open chat can still show loading while it waits for its local connection. The shared lifecycle state must not treat an unopened task as an active startup.

New cloud runs seed the full user message before subscribing to setup progress. The chat renders that message immediately, including its space context chip. Reopened transcripts reconcile the plain initial prompt with its context-bearing echo before rendering, so the same submission appears only once.

Cloud creation can succeed while the run is still queued. The pending prompt remains available to the chat after that success; SessionView clears it when initialization ends. Successful submissions are marked as submitted so startup recovery does not reopen them as unsent drafts. Failed creation retains the prompt for recovery into the originating composer.

Dependency Injection

Use plain Inversify through @posthog/di.

  • Define an interface and Symbol.for(...) token in the owning package.
  • Inject dependencies through constructors.
  • Bind services in feature ContainerModules.
  • Load modules in host composition files.
  • Call setRootContainer(container) before React service resolution.
  • Do not call container.get(...) or resolveService(...) inside services or components.
export const FOCUS_SERVICE = Symbol.for("posthog.core.focusService");

export interface IFocusService {
  enableFocus(input: EnableFocusInput): Promise<EnableFocusResult>;
}
@injectable()
export class FocusService implements IFocusService {
  constructor(
    @inject(GIT_SERVICE) private readonly git: IGitService,
    @inject(FOCUS_WORKSPACE_CLIENT) private readonly workspace: FocusWorkspaceClient,
  ) {}

  async enableFocus(input: EnableFocusInput): Promise<EnableFocusResult> {
    // orchestration
  }
}
export const focusCoreModule = new ContainerModule(({ bind }) => {
  bind(FOCUS_SERVICE).to(FocusService).inSingletonScope();
});

React resolves services only at boundaries:

const focus = useService(FOCUS_SERVICE);

Unit tests construct services with fakes instead of using the container.

Contributions

Boot side effects are Contributions:

  • subscriptions
  • routes
  • commands
  • menus
  • feature initialization

Bind contributions in feature modules. boot() resolves and starts them before rendering.

bind(CONTRIBUTION).to(FileWatcherContribution).inSingletonScope();
setRootContainer(container);

import "./desktop-services";
import "./desktop-contributions";

await boot(container);

Components do not start long-lived subscriptions. A contribution starts the subscription, writes to a store, and components render store state.

Host Router

@posthog/host-router is the Electron main-to-renderer API. Router files live at:

packages/host-router/src/routers/<feature>.router.ts

Router rules:

  • Import service tokens and schemas from the owning package.
  • Resolve the service from ctx.container.
  • Validate input with Zod.
  • Forward to the service.
  • Do not add business logic.
export const focusRouter = router({
  enableFocus: publicProcedure
    .input(enableFocusInput)
    .mutation(({ ctx, input }) =>
      ctx.container.get<IFocusService>(FOCUS_SERVICE).enableFocus(input)
    ),
});

The renderer imports HostRouter as a type and uses useHostTRPC. trpcClient remains in host glue under apps/<host>.

Workspace Server

@posthog/workspace-server owns privileged Node work:

  • git
  • filesystem
  • pty
  • process spawn
  • watchers

It exposes colocated tRPC routers. @posthog/workspace-client is the typed client. core services inject narrow workspace-client slices and call those procedures.

Disk Cache

The Electron main process owns one on-disk cache at userData/disk-cache/<namespace>/ (apps/code/src/main/services/disk-cache/service.ts). An entry is bytes plus a content type and a stored-at time. Readers pass a max age and get stale entries back flagged, so a consumer can serve them when a refresh fails. "Clear application storage" removes the whole directory, which is why the directory is not named cache: userData is also Electron's sessionData, and on a case-insensitive filesystem that would be Chromium's own Cache.

A namespace can take a maxBytes budget. Nothing else removes entries, so a namespace without one grows for as long as callers reach for new keys. With one, a write that passes the budget drops the oldest entries until the namespace fits again.

Consumers take a namespace and serve it over the posthog-cache:// protocol (apps/code/src/main/protocols/disk-cache.ts). Today images/ serves remote images: the renderer rewrites an https: URL with cachedImageUrl() from @posthog/ui/shell/cachedImageUrl, backed by the IDiskCacheImages platform interface. Hosts without a disk cache leave the URL unchanged.

The protocol is registered on the session that also renders untrusted artifact HTML, so treat every source as attacker-chosen. A source must be public https: with no embedded credentials: intranet and loopback addresses are refused, and a response that redirected onto one is thrown away. Bodies are read against a size cap while they stream, refreshes carry a deadline and a concurrency limit, and the namespace budget bounds what one preview can put on disk. A stale copy is served with no-cache so Chromium cannot hold it past the point where the disk layer would replace it.

Schemas

Use Zod at runtime boundaries. Infer TypeScript types from schemas.

export const getDataInput = z.object({
  id: z.string(),
});

export type GetDataInput = z.infer<typeof getDataInput>;

Use schemas for tRPC inputs/outputs, API boundary data, persisted data, and external tool payloads.

Events

Use typed events for real-time push. Services may extend TypedEventEmitter. Routers expose streams as subscriptions.

@injectable()
export class FocusService extends TypedEventEmitter<FocusServiceEvents> {
  async checkout(input: CheckoutInput) {
    this.emit(FocusServiceEvent.Switched, { sessionId, branch });
  }
}

For per-instance streams, filter server-side by id.

State

Store each fact once.

Domain state:

  • lives in @posthog/core
  • uses zustand/vanilla
  • represents facts read by business logic

View state:

  • lives in @posthog/ui
  • uses React Zustand create
  • represents selection, panel state, scroll position, drafts, and filters

Compute counts, labels, filtered lists, and status summaries from source facts.

Adding a Feature

  1. Choose the data source.
  2. Add a core service when the feature has orchestration, retries, rules, sagas, or decisions.
  3. Define Zod schemas in schemas.ts.
  4. Define interface and token in identifiers.ts.
  5. Bind the service in <feature>.module.ts.
  6. Expose the service through host-router, or expose Node work through workspace-server.
  7. Build UI in packages/ui/src/features/<feature>/.
  8. Add hooks that each wrap one query, mutation, subscription, or selector.
  9. Add a contribution for subscriptions, routes, commands, or feature boot.
  10. Wire host adapters in apps/<host>.
  11. Run node scripts/check-host-boundaries.mjs.

MCP Apps

MCP Apps render tool-provided HTML UIs inside sandboxed iframes.

  • Shared schemas: @posthog/shared.
  • Service: packages/core/src/mcp-apps/.
  • UI feature: packages/ui/src/features/mcp-apps/.
  • Desktop host glue: apps/code/src/renderer/features/mcp-apps/.

The core service manages MCP server connections, caches resources, and proxies UI calls. useAppBridge handles @modelcontextprotocol/ext-apps host communication, tRPC routing, theme, display mode, and dimensions.

References