# How Pi‑Web Handles Session Compaction Events and UI Updates

> Discover how Pi-Web manages session compaction events and UI updates. Learn about state synchronization and the abort compaction command.

- Repository: [Alex Yang/pi-web](https://github.com/agegr/pi-web)
- Tags: internals
- Published: 2026-08-13

---

**Pi‑Web manages session compaction by capturing `compaction_start` and `compaction_end` events from the Pi SDK in the `useAgentSession` hook, synchronizing the `isCompacting` state to control UI indicators, and exposing an `abort_compaction` command through [`rpc-manager.ts`](https://github.com/agegr/pi-web/blob/main/rpc-manager.ts) that allows users to terminate active compaction processes.**

Session compaction automatically archives aging conversation history when pi-web sessions exceed token or message thresholds, preventing performance degradation. The `agegr/pi-web` repository implements a real-time event propagation system that streams compaction notifications from the backend Pi SDK to React frontend components. This article dissects the event handling logic, user interface implementation, and automatic triggers governing the compaction lifecycle.

## Event Handling Architecture for Session Compaction

The frontend receives compaction signals as discrete RPC events and translates them into React state updates that drive the user interface.

### Processing Compaction Events in useAgentSession

The `useAgentSession` hook located in [`hooks/useAgentSession.ts`](https://github.com/agegr/pi-web/blob/main/hooks/useAgentSession.ts) contains the primary event listener for compaction state changes around lines 1041–1048. This hook monitors four distinct event types emitted by the Pi SDK: `compaction_start`, `compaction_end`, `auto_compaction_start`, and `auto_compaction_end`.

When either start event fires, the hook sets an **`isCompacting`** boolean flag to `true`, disabling certain controls and displaying progress indicators. When the corresponding end event arrives, the flag resets to `false`. This dual-event architecture ensures the UI remains synchronized even if network latency causes events to arrive out of order.

```typescript
// hooks/useAgentSession.ts – Handling compaction state transitions
case "auto_compaction_start":
case "compaction_start":
  setIsCompacting(true);
  break;
case "auto_compaction_end":
case "compaction_end":
  setIsCompacting(false);
  break;

```

### Aborting Compaction via RPC Manager

Users can terminate an ongoing compaction through the **`abort_compaction`** command implemented in [`lib/rpc-manager.ts`](https://github.com/agegr/pi-web/blob/main/lib/rpc-manager.ts) at approximately line 578. This RPC method sends an immediate termination signal to the Pi SDK backend, halting the summarization process and restoring normal session operation.

```typescript
// lib/rpc-manager.ts – Abort compaction command handler
async function abortCompaction(sessionId: string) {
  await sendAgentCommand(sessionId, { type: "abort_compaction" });
}

```

## User Interface Components for Session Compaction

The UI layer consumes the `isCompacting` state and specialized message types to provide visual feedback during automatic maintenance.

### Displaying Compaction Status and Summaries

When compaction completes, the backend inserts a special message entry with **`type: "compaction"`** into the session history, defined in [`lib/types.ts`](https://github.com/agegr/pi-web/blob/main/lib/types.ts). The frontend renders this entry using a dedicated view component that displays a summary of the archived content.

While compaction is active, components check the `isCompacting` flag to render a "Compacting…" indicator and temporarily disable input controls to prevent state corruption.

```tsx
// Component rendering compaction summary entries
{msg.type === "compaction" && (
  <div className="compaction-summary">
    <strong>{t("i18n.compactionDescription")}</strong>
    <pre>{msg.summary}</pre>
  </div>
)}

```

### Internationalization and User Messaging

All user-visible compaction text is centralized in [`lib/i18n/messages/en.ts`](https://github.com/agegr/pi-web/blob/main/lib/i18n/messages/en.ts) at line 418 through the **`i18n.compactionDescription`** key. This string provides context explaining that older messages have been summarized to conserve memory, ensuring users understand why portions of their conversation history appear collapsed.

## What Triggers Session Compaction in Pi‑Web

Compaction triggers automatically within the Pi SDK when session files exceed internal thresholds for token count or message volume. The backend initiates the process silently, emitting `compaction_start` when summarization begins and `compaction_end` when the archived summary has been written to the session JSONL file. No manual intervention is required to start compaction, though users retain the ability to abort the process via the UI controls described above.

## Implementation Examples

The following patterns demonstrate complete integration of compaction handling in pi-web applications.

**Listening for compaction events:**

```typescript
// hooks/useAgentSession.ts
useEffect(() => {
  const unsubscribe = onAgentEvent((event) => {
    switch (event.type) {
      case "compaction_start":
      case "auto_compaction_start":
        setIsCompacting(true);
        break;
      case "compaction_end":
      case "auto_compaction_end":
        setIsCompacting(false);
        break;
    }
  });
  return unsubscribe;
}, []);

```

**Sending an abort request:**

```typescript
// Handler for "Stop compaction" button
const handleStopCompaction = async () => {
  if (!sessionId) return;
  await rpcManager.sendCommand(sessionId, { type: "abort_compaction" });
};

```

**Rendering compaction entries:**

```tsx
// MessageView.tsx
import { useTranslation } from 'react-i18next';

export function MessageView({ message }) {
  const { t } = useTranslation();
  
  if (message.type === "compaction") {
    return (
      <div className="compaction-notice">
        <span>{t("i18n.compactionDescription")}</span>
        <details>
          <summary>View archived context</summary>
          <pre>{message.summary}</pre>
        </details>
      </div>
    );
  }
  
  return <div className="message">{message.content}</div>;
}

```

## Summary

- **Event-driven architecture**: Pi‑Web listens for `compaction_start` and `compaction_end` events in [`hooks/useAgentSession.ts`](https://github.com/agegr/pi-web/blob/main/hooks/useAgentSession.ts) to maintain accurate compaction state.
- **State synchronization**: The `isCompacting` boolean flag controls UI indicators and prevents user actions during active compaction.
- **User control**: The `abort_compaction` command in [`lib/rpc-manager.ts`](https://github.com/agegr/pi-web/blob/main/lib/rpc-manager.ts) allows immediate termination of unwanted compaction processes.
- **Type safety**: [`lib/types.ts`](https://github.com/agegr/pi-web/blob/main/lib/types.ts) defines the `"compaction"` message entry type for strongly-typed session histories.
- **Automatic triggers**: The Pi SDK initiates compaction when token counts or message volumes exceed performance thresholds, requiring no manual configuration.

## Frequently Asked Questions

### What triggers session compaction in pi-web?

The Pi SDK backend automatically triggers compaction when a session's cumulative token count or message history exceeds internal performance thresholds. This process runs silently until the frontend receives the `compaction_start` event, at which point the UI updates to reflect the active maintenance state.

### How does the UI indicate that compaction is in progress?

The frontend monitors the `isCompacting` state managed by [`useAgentSession.ts`](https://github.com/agegr/pi-web/blob/main/useAgentSession.ts). When `true`, the interface displays a "Compacting…" indicator and temporarily disables chat input controls to prevent state conflicts. This state persists until the `compaction_end` or `auto_compaction_end` event resets the flag.

### Can users stop an ongoing compaction process?

Yes. Pi‑Web exposes a **Stop compaction** button that invokes the `abort_compaction` command through [`lib/rpc-manager.ts`](https://github.com/agegr/pi-web/blob/main/lib/rpc-manager.ts). This sends an immediate termination signal to the backend Pi SDK, halting the summarization process and restoring full session functionality without waiting for natural completion.

### Where are compaction events defined in the codebase?

Compaction event types are handled in [`hooks/useAgentSession.ts`](https://github.com/agegr/pi-web/blob/main/hooks/useAgentSession.ts) (lines 1041–1048) for state management, while the underlying message type is declared in [`lib/types.ts`](https://github.com/agegr/pi-web/blob/main/lib/types.ts). The abort command implementation resides in [`lib/rpc-manager.ts`](https://github.com/agegr/pi-web/blob/main/lib/rpc-manager.ts) (line 578), and user-facing strings are located in [`lib/i18n/messages/en.ts`](https://github.com/agegr/pi-web/blob/main/lib/i18n/messages/en.ts) (line 418).