> ## 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.

<CodeGroup>
  ```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);
  ```

  ```python Python theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  import os

  from pierre_storage import GitStorage

  session_id = os.environ["SESSION_ID"]

  storage_client = GitStorage({
      "key": os.environ["PIERRE_PRIVATE_KEY"],
      "name": "acme",
  })

  repository_id = "acme/storefront"
  repo = await storage_client.find_one(id=repository_id)

  session_branch = f"sessions/{session_id}"

  view = await repo.get_branch_diff(
      base=repo.default_branch,
      branch=session_branch,
      ephemeral=True,
  )

  print(view["stats"])
  print(view["files"])
  ```

  ```go Go theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  sessionID := os.Getenv("SESSION_ID")

  client, err := storage.NewClient(storage.Options{
  	Key:  os.Getenv("PIERRE_PRIVATE_KEY"),
  	Name: "acme",
  })

  ctx := context.Background()
  repositoryID := "acme/storefront"
  repo, err := client.FindOne(ctx, storage.FindOneOptions{ID: repositoryID})

  sessionBranch := fmt.Sprintf("sessions/%s", sessionID)
  ephemeral := true
  view, err := repo.GetBranchDiff(ctx, storage.GetBranchDiffOptions{
  	Base:      repo.DefaultBranch,
  	Branch:    sessionBranch,
  	Ephemeral: &ephemeral,
  })

  fmt.Println(view.Stats)
  fmt.Println(view.Files)
  ```
</CodeGroup>

`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.

<CodeGroup>
  ```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);
  ```

  ```python Python theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  response = await repo.get_file_stream(
      ephemeral=True,
      path="src/auth.ts",
      ref=session_branch,
  )

  source = (await response.aread()).decode()
  print(source)
  ```

  ```go Go theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  response, err := repo.FileStream(ctx, storage.GetFileOptions{
  	Ephemeral: &ephemeral,
  	Path:      "src/auth.ts",
  	Ref:       sessionBranch,
  })
  defer response.Body.Close()

  source, err := io.ReadAll(response.Body)
  fmt.Println(string(source))
  ```
</CodeGroup>

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

<CodeGroup>
  ```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);
  ```

  ```python Python theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  state_sha = "4f53cda18c2baa0c0354bb5f9a3ecbe5f6b3f858"
  base_sha = "081b0449cdb51a6fd5c495e7fa329119b3a5dc26"

  fixed_diff = await repo.get_commit_diff(
      base_sha=base_sha,
      sha=state_sha,
  )

  print(fixed_diff["stats"])
  ```

  ```go Go theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
  stateSHA := "4f53cda18c2baa0c0354bb5f9a3ecbe5f6b3f858"
  baseSHA := "081b0449cdb51a6fd5c495e7fa329119b3a5dc26"

  fixedDiff, err := repo.GetCommitDiff(ctx, storage.GetCommitDiffOptions{
  	BaseSHA: baseSHA,
  	SHA:     stateSHA,
  })

  fmt.Println(fixedDiff.Stats)
  ```
</CodeGroup>

## 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.
