> ## Documentation Index
> Fetch the complete documentation index at: https://code.storage/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Show Live Diffs

> Render an agent branch as a live diff and refresh the view when a new state arrives.

Render an agent's work from its ephemeral branch while the agent runs. Your product can show current
and prior states without a second file store or diff service.

This guide uses the branch layout from [Store Session State](/docs/guides/session-state).

## Read the current diff

Compare the session branch with its normal base branch.

```typescript TypeScript theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
import { GitStorage } from '@pierre/storage';

const sessionId = process.env.SESSION_ID;

const store = new GitStorage({
  key: process.env.PIERRE_PRIVATE_KEY,
  name: 'acme',
});

const repositoryId = 'acme/storefront';
const repo = await store.findOne({ id: repositoryId });

const sessionBranch = `sessions/${sessionId}`;

const view = await repo.getBranchDiff({
  base: repo.defaultBranch,
  branch: sessionBranch,
  ephemeral: true,
});

console.log(view.stats);
console.log(view.files);
```

`view.files` contains the file changes and diff text. `view.stats` contains the file, line, and
change totals.

Use [`getBranchDiff()`](/docs/reference/sdk/get-branch-diff) to filter the response to selected paths.

## Read one file

Use the session branch for the latest content, or use a commit SHA for a fixed view.

```typescript TypeScript theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
const response = await repo.getFileStream({
  ephemeral: true,
  path: 'src/auth.ts',
  ref: sessionBranch,
});

const source = await response.text();
console.log(source);
```

For a fixed review link, store the state SHA and pass it as `ref`. The same SHA can also select a
commit diff.

```typescript TypeScript theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
const stateSha = '4f53cda18c2baa0c0354bb5f9a3ecbe5f6b3f858';
const baseSha = '081b0449cdb51a6fd5c495e7fa329119b3a5dc26';

const fixedDiff = await repo.getCommitDiff({
  baseSha,
  sha: stateSha,
});

console.log(fixedDiff.stats);
```

## Refresh after each state

Use either of these refresh signals:

1. Poll the session branch tip, then reload the diff when the SHA changes.
2. Subscribe to `push` webhooks, validate each delivery, and reload the diff for the same repository
   and branch.

Treat the webhook as a signal. Read the branch again after each event. Do not use the event as your
state store.

See [Webhooks](/docs/guides/webhooks) for subscriptions, signatures, and retries.

## Keep credentials on the server

Call Code Storage from your backend. Do not send your organization private key or a write token to
the browser.

Cache a diff by its head SHA when many viewers request the same state. A new state gets a new SHA
and a new cache key.
