# Sub-agent view

> A sub-agent's conversation — its text, its reasoning, its tool calls, its own sub-agents — in a pane, a canvas or a dialog beside the chat, live while it works and saved with the conversation.

[A sub-agent's conversation in a pane beside the chat](/preview/demo/subagent-view/?play=Why%20do%20quoted%20fields%20break%3F)

```html
<!-- The chat alone until a sub-agent starts; then its conversation opens in the other pane.
     The model here is scripted. In your app: import { setupSubagents } from '@aparte/plugin-subagents'. -->
<aparte-split position="50" breakpoint="30rem" single style="height: 28rem">
  <aparte-chat id="chat" placeholder="Ask the agent"></aparte-chat>
  <aparte-subagent-view for="chat"></aparte-subagent-view>
</aparte-split>

<script>
  const { aparteGlobalConfig } = window.aparte;
  const { createScenarioProvider, scenarioSubagentTool } = window.apartePlugins.scenario;
  const { setupSubagents } = window.apartePlugins.subagents;

  const model = createScenarioProvider({
    id: 'delegating',
    name: 'Delegating',
    models: [{ id: 'delegating', name: 'Delegating' }],
    turns: [
      [{ text: 'A researcher can read it for you.' }, { subagents: [
        { name: 'Researcher', task: 'Find why quoted fields break', turns: [
          [{ thinking: 'Start with the parser itself.' }, { wait: 800 }, { tool: 'read_file', input: { path: 'src/parser.ts' } }],
          [{ text: 'The parser splits each line on commas. ' }, { wait: 900 }, { tool: 'search_docs', input: { query: 'quoted fields' } }],
          [{ wait: 900 }, { text: 'It never looks for quotes, so a comma inside a quoted field splits it in two.' }],
        ] },
      ] }],
      'The researcher found it: a comma inside quotes splits the field. The fix belongs in the parser.',
    ],
  });
  aparteGlobalConfig.registerAIProvider(model);
  aparteGlobalConfig.setModelConfig({ defaultProvider: 'delegating', defaultModel: 'delegating' });
  const { tool, handler } = scenarioSubagentTool(model);
  aparteGlobalConfig.registerTool(tool, handler);
  setupSubagents();

  // The view follows the sub-agent the chat announces, and the pane opens for it.
  const split = document.querySelector('aparte-split');
  const view = document.querySelector('aparte-subagent-view');
  document.getElementById('chat').addEventListener('aparte-subagent-start', (e) => {
    view.setAttribute('message-id', e.detail.messageId);
    view.setAttribute('agent-id', e.detail.agentId);
    split.removeAttribute('single');
  });
</script>
```

In the reply, a sub-agent is [one line](/guides/sub-agents/): its name, its task, what it is doing now. `<aparte-subagent-view>` shows what it said and did, where you put it: the other pane of a [split](/components/split/), a canvas, a dialog. Its text, its reasoning, its tool rows and its own sub-agents as lines, drawn by the same renderers as the reply. It is the same drawing the line opens on with `setupSubagents({ details: 'transcript' })`.

It keeps nothing of its own. It reads the sub-agent from the chat, live while it works, and from the conversation once it is saved, so a reloaded conversation shows what was saved.

## Usage

[Section titled “Usage”](#usage)

```bash
npm install @aparte/plugin-subagents @aparte/core
```

```html
<aparte-split position="50" single>
  <aparte-chat id="chat"></aparte-chat>
  <aparte-subagent-view for="chat"></aparte-subagent-view>
</aparte-split>
```

* Vanilla

  ```ts
  import { setupSubagents } from '@aparte/plugin-subagents';

  setupSubagents();

  const split = document.querySelector('aparte-split')!;
  const view = document.querySelector('aparte-subagent-view')!;
  document.getElementById('chat')!.addEventListener('aparte-subagent-start', (event) => {
    view.setAttribute('message-id', event.detail.messageId);
    view.setAttribute('agent-id', event.detail.agentId);
    split.removeAttribute('single');
  });
  ```

* React

  ```tsx
  import { useState } from 'react';
  import { AparteChat, useAparteChat, useAparteEvent } from '@aparte/react';
  import { setupSubagents } from '@aparte/plugin-subagents';   // its events join HTMLElementEventMap

  setupSubagents();

  export function Workspace() {
    const chat = useAparteChat();
    const [shown, setShown] = useState<{ messageId: string; agentId: string }>();

    useAparteEvent(chat.ref, 'aparte-subagent-start', (event) =>
      setShown({ messageId: event.detail.messageId, agentId: event.detail.agentId }));

    return (
      <aparte-split position="50" single={shown ? undefined : ''}>
        <AparteChat id="chat" ref={chat.ref} messages={chat.messages} onMessagesChange={chat.setMessages} />
        {shown && <aparte-subagent-view for="chat" message-id={shown.messageId} agent-id={shown.agentId} />}
      </aparte-split>
    );
  }
  ```

* Vue

  ```vue
  <script setup lang="ts">
  import { ref } from 'vue';
  import { AparteChat } from '@aparte/vue';
  import { setupSubagents } from '@aparte/plugin-subagents';

  setupSubagents();

  const shown = ref<{ messageId: string; agentId: string }>();
  </script>

  <template>
    <aparte-split position="50" :single="shown ? undefined : ''">
      <AparteChat id="chat" @aparte-subagent-start="(event) => (shown = event.detail)" />
      <aparte-subagent-view v-if="shown" for="chat" :message-id="shown.messageId" :agent-id="shown.agentId" />
    </aparte-split>
  </template>
  ```

* Svelte

  ```svelte
  <script lang="ts">
    import { AparteChat } from '@aparte/svelte/runes';
    import { setupSubagents } from '@aparte/plugin-subagents';

    setupSubagents();

    let shown = $state<{ messageId: string; agentId: string }>();
  </script>

  <aparte-split position="50" single={shown ? undefined : ''}>
    <AparteChat id="chat" onaparte-subagent-start={(event) => (shown = event.detail)} />
    {#if shown}
      <aparte-subagent-view for="chat" message-id={shown.messageId} agent-id={shown.agentId}></aparte-subagent-view>
    {/if}
  </aparte-split>
  ```

  On Svelte 4, `bind:this` the chat and listen on `chat.getElement()` in `onMount` ([Svelte](/frameworks/svelte/#control-it-from-code)).

* Angular

  ```ts
  import { Component, CUSTOM_ELEMENTS_SCHEMA, signal } from '@angular/core';
  import { AparteChatComponent, AparteSplitDirective } from '@aparte/angular';
  import { setupSubagents } from '@aparte/plugin-subagents';
  import type { AparteSubagentStartEventDetail } from '@aparte/plugin-subagents';

  setupSubagents();

  @Component({
    selector: 'app-workspace',
    standalone: true,
    imports: [AparteChatComponent, AparteSplitDirective],
    schemas: [CUSTOM_ELEMENTS_SCHEMA],
    template: `
      <aparte-split position="50" [single]="!shown()">
        <aparte-chat id="chat" (aparte-subagent-start)="shown.set($any($event).detail)"></aparte-chat>
        @if (shown(); as agent) {
          <aparte-subagent-view for="chat" [attr.message-id]="agent.messageId" [attr.agent-id]="agent.agentId"></aparte-subagent-view>
        }
      </aparte-split>
    `,
  })
  export class WorkspaceComponent {
    readonly shown = signal<AparteSubagentStartEventDetail | null>(null);
  }
  ```

Importing the package defines the element. Three attributes say what it shows: `for`, the `id` of the chat (`<aparte-chat>`, its viewport, or any element with `getMessages()`); `message-id`, the reply; `agent-id`, the sub-agent. A chat with no `id` is handed through the `chat` property (`SubagentViewSource`) instead. Until the three name a sub-agent that has started, the element draws nothing and carries `data-empty`, so a layout can fold the pane against it:

```css
aparte-subagent-view[data-empty] {
  display: none;
}
```

### Open a sub-agent beside the chat

[Section titled “Open a sub-agent beside the chat”](#open-a-sub-agent-beside-the-chat)

Let the reader pick which sub-agent the view shows: `setupSubagents({ open: 'event' })` puts an Open button at the end of each sub-agent’s line, and `connectSubagentView` does the rest.

```html
<aparte-split position="55">
  <aparte-chat id="chat"></aparte-chat>
  <aparte-subagent-view for="chat"></aparte-subagent-view>
</aparte-split>
```

```ts
import { connectSubagentView, setupSubagents } from '@aparte/plugin-subagents';
import type { SubagentViewSplit } from '@aparte/plugin-subagents';

setupSubagents({ open: 'event' });

const disconnect = connectSubagentView({
  chat: document.getElementById('chat')!,
  view: document.querySelector('aparte-subagent-view')!,
  split: document.querySelector<SubagentViewSplit>('aparte-split')!,
});
```

The split starts with the chat alone. Pressing a line’s Open button (click, Enter or Space) dispatches `aparte-subagent-open` with `messageId` and `agentId`; the wiring points the view at that sub-agent, opens the split’s second pane, and marks the line (`data-current` on the row, `aria-current="true"` on its button). It sets `closable` on the view: the sub-agent’s name and a Close button above its conversation. Close, or Escape inside the view, sends `aparte-subagent-view-close`; the wiring folds the pane and puts the focus back on the line’s button. On a phone, where the split shows one pane at a time, the same two steps show the view and then the chat again.

Without a split (a tab, a drawer), pass `onOpen` and `onClose` instead and show the view yourself: `ConnectSubagentViewOptions` holds them all (`chat`, `view`, `split`, `pane`, `onOpen`, `onClose`). The [sub-agents guide](/guides/sub-agents/#open-a-sub-agent-beside-the-chat) says how the button and a line’s `details` share the line.

### Which sub-agents a reply has

[Section titled “Which sub-agents a reply has”](#which-sub-agents-a-reply-has)

The chat dispatches two events, both bubbling:

* `aparte-subagent-start` (`AparteSubagentStartEventDetail`) when a sub-agent starts, or starts again after a pause: `messageId`, `agentId`, `name`, `description` (its task), `model` when its producer names the model it runs on, and `toolCallId` or `parentId` for the call or the sub-agent that opened it.
* `aparte-subagent-end` (`AparteSubagentEndEventDetail`) when it ends, or the run ends without it: `messageId`, `agentId` and `status` — `done`, `failed`, `waiting`, `stopped`, or `partial` when it was cut short, with `reason` (its turn limit, a call its run could not make).

Both carry the chat’s `id` as `targetId`, so a page with several chats can tell them apart. Together they are enough to keep a list of a reply’s sub-agents and open the one a person picks:

* Vanilla

  ```ts
  import type { AparteSubagentStatus } from '@aparte/plugin-subagents';

  const chat = document.getElementById('chat')!;
  const agents = new Map<string, { name?: string; status: AparteSubagentStatus }>();

  chat.addEventListener('aparte-subagent-start', (event) => {
    agents.set(event.detail.agentId, { name: event.detail.name, status: 'running' });
  });
  chat.addEventListener('aparte-subagent-end', (event) => {
    const agent = agents.get(event.detail.agentId);
    if (agent) agent.status = event.detail.status;
  });
  ```

* React

  ```tsx
  import { useRef } from 'react';
  import { useAparteChat, useAparteEvent } from '@aparte/react';
  import type { AparteSubagentStatus } from '@aparte/plugin-subagents';

  export function useSubagents() {
    const chat = useAparteChat();   // with ref={chat.ref} on <AparteChat>
    const agents = useRef(new Map<string, { name?: string; status: AparteSubagentStatus }>());

    useAparteEvent(chat.ref, 'aparte-subagent-start', (event) => {
      agents.current.set(event.detail.agentId, { name: event.detail.name, status: 'running' });
    });
    useAparteEvent(chat.ref, 'aparte-subagent-end', (event) => {
      const agent = agents.current.get(event.detail.agentId);
      if (agent) agent.status = event.detail.status;
    });

    return { chat, agents };
  }
  ```

* Vue

  ```vue
  <script setup lang="ts">
  import { reactive } from 'vue';
  import { AparteChat } from '@aparte/vue';
  import type { AparteSubagentStatus } from '@aparte/plugin-subagents';

  const agents = reactive(new Map<string, { name?: string; status: AparteSubagentStatus }>());
  </script>

  <template>
    <AparteChat
      @aparte-subagent-start="(event) => agents.set(event.detail.agentId, { name: event.detail.name, status: 'running' })"
      @aparte-subagent-end="(event) => { const agent = agents.get(event.detail.agentId); if (agent) agent.status = event.detail.status; }"
    />
  </template>
  ```

* Svelte

  ```svelte
  <script lang="ts">
    import { SvelteMap } from 'svelte/reactivity';
    import { AparteChat } from '@aparte/svelte/runes';
    import type { AparteSubagentStatus } from '@aparte/plugin-subagents';

    const agents = new SvelteMap<string, { name?: string; status: AparteSubagentStatus }>();
  </script>

  <AparteChat
    onaparte-subagent-start={(event) => agents.set(event.detail.agentId, { name: event.detail.name, status: 'running' })}
    onaparte-subagent-end={(event) => {
      const agent = agents.get(event.detail.agentId);
      if (agent) agent.status = event.detail.status;
    }}
  />
  ```

  On Svelte 4, `bind:this` the chat and listen on `chat.getElement()` in `onMount`.

* Angular

  ```ts
  import { Component } from '@angular/core';
  import { AparteChatComponent } from '@aparte/angular';
  import type {
    AparteSubagentEndEventDetail,
    AparteSubagentStartEventDetail,
    AparteSubagentStatus,
  } from '@aparte/plugin-subagents';

  @Component({
    selector: 'app-agents',
    standalone: true,
    imports: [AparteChatComponent],
    template: `<aparte-chat (aparte-subagent-start)="start($any($event).detail)" (aparte-subagent-end)="end($any($event).detail)"></aparte-chat>`,
  })
  export class AgentsComponent {
    private readonly agents = new Map<string, { name?: string; status: AparteSubagentStatus }>();

    start(detail: AparteSubagentStartEventDetail) {
      this.agents.set(detail.agentId, { name: detail.name, status: 'running' });
    }

    end(detail: AparteSubagentEndEventDetail) {
      const agent = this.agents.get(detail.agentId);
      if (agent) agent.status = detail.status;
    }
  }
  ```

### Reading a saved sub-agent

[Section titled “Reading a saved sub-agent”](#reading-a-saved-sub-agent)

A sub-agent is saved with the conversation, on the segment that stands for it: the call that opened it, or a `subagent` segment of the plugin’s own (`AparteSubagentSegment`, `SUBAGENT_SEGMENT_TYPE`) for one no call opened. `subagentOf(segment)` returns it, an `AparteSubagent` (`id`, `name`, `description`, `status`, `result`, `error`, `parentId`, and its conversation in `segments`), and `subagentStatus(segment)` its state. Both are exported for Node too. The messages come from the message list in plain HTML, and from the chat’s `messages` in a framework:

* Vanilla

  ```ts
  import type { AparteChatViewport } from '@aparte/core';
  import { subagentOf, subagentStatus } from '@aparte/plugin-subagents';

  const viewport = document.querySelector<AparteChatViewport>('aparte-chat-viewport')!;

  for (const message of viewport.getMessages()) {
    for (const segment of message.segments ?? []) {
      const agent = subagentOf(segment);
      if (agent) console.info(agent.name, subagentStatus(segment), agent.result ?? agent.error ?? '');
    }
  }
  ```

* React

  ```tsx
  import { useAparteChat } from '@aparte/react';
  import { subagentOf, subagentStatus } from '@aparte/plugin-subagents';

  const chat = useAparteChat();   // in your component, with messages={chat.messages} on <AparteChat>

  for (const message of chat.messages) {
    for (const segment of message.segments ?? []) {
      const agent = subagentOf(segment);
      if (agent) console.info(agent.name, subagentStatus(segment), agent.result ?? agent.error ?? '');
    }
  }
  ```

* Vue

  ```vue
  <script setup lang="ts">
  import { AparteChat, useAparteChat } from '@aparte/vue';
  import { subagentOf, subagentStatus } from '@aparte/plugin-subagents';

  const chat = useAparteChat();

  function logSubagents() {
    for (const message of chat.messages.value) {
      for (const segment of message.segments ?? []) {
        const agent = subagentOf(segment);
        if (agent) console.info(agent.name, subagentStatus(segment), agent.result ?? agent.error ?? '');
      }
    }
  }
  </script>

  <template>
    <AparteChat :ref="chat.chatRef" :messages="chat.messages.value" @messages-change="chat.onMessagesChange" />
  </template>
  ```

* Svelte

  ```svelte
  <script lang="ts">
    import { AparteChat } from '@aparte/svelte/runes';
    import type { AparteMessage } from '@aparte/core';
    import { subagentOf, subagentStatus } from '@aparte/plugin-subagents';

    let messages = $state<AparteMessage[]>([]);

    function logSubagents() {
      for (const message of messages) {
        for (const segment of message.segments ?? []) {
          const agent = subagentOf(segment);
          if (agent) console.info(agent.name, subagentStatus(segment), agent.result ?? agent.error ?? '');
        }
      }
    }
  </script>

  <AparteChat bind:messages />
  ```

* Angular

  ```ts
  import { Component } from '@angular/core';
  import { AparteChatComponent } from '@aparte/angular';
  import type { AparteMessage } from '@aparte/core';
  import { subagentOf, subagentStatus } from '@aparte/plugin-subagents';

  @Component({
    selector: 'app-chat',
    standalone: true,
    imports: [AparteChatComponent],
    template: `<aparte-chat [messages]="messages" (messagesChange)="messages = $event"></aparte-chat>`,
  })
  export class ChatComponent {
    messages: AparteMessage[] = [];

    logSubagents() {
      for (const message of this.messages) {
        for (const segment of message.segments ?? []) {
          const agent = subagentOf(segment);
          if (agent) console.info(agent.name, subagentStatus(segment), agent.result ?? agent.error ?? '');
        }
      }
    }
  }
  ```

`subagentStatus` reads `stopped` for a sub-agent a reload or a Stop left unfinished, where the saved `status` still says how it was when the page closed. The sub-agent’s conversation is never part of what the model reads.

## In a framework

[Section titled “In a framework”](#in-a-framework)

The element is a plain tag in every framework, and the plugin’s events reach the chat’s root like any other, so each wrapper hears `aparte-subagent-start` and the rest by the event’s own name, as the tabs above do (`useAparteEvent`, `@aparte-…`, `onaparte-…`, `(aparte-…)`). A Vue or Svelte template accepts the tag as it is; Angular needs `CUSTOM_ELEMENTS_SCHEMA` on the component that hosts it, and `[attr.message-id]` to bind an attribute. In a React `.tsx` file the tag is a compile error until you declare it once, which the [sub-agents guide](/guides/sub-agents/#show-the-conversation-elsewhere) shows. The class is exported as `AparteSubagentView`, for the type of a `ref`.

## Customize

[Section titled “Customize”](#customize)

The view is light DOM, like the chat: its rows are the chat’s, and they take your theme as they do in the reply. `--aparte-subagent-indent` is the space between the rule down its leading edge and the conversation.

## API

[Section titled “API”](#api)

`<aparte-subagent-view>` · class `AparteSubagentView`

**Attributes**

| Attribute     | Description                                                                                                                                                                                                             |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `for`         | The `id` of the chat: `<aparte-chat>`, its viewport, or any element with `getMessages()`. Or set the `chat` property.                                                                                                   |
| `message-id`  | The reply the sub-agent worked for (`aparte-subagent-start`’s `messageId`).                                                                                                                                             |
| `agent-id`    | Which sub-agent (`aparte-subagent-start`’s `agentId`).                                                                                                                                                                  |
| `closable`    | A pane of its own: the sub-agent’s name and a Close button above its conversation, and Escape inside it closes too. Both only say so (`aparte-subagent-view-close`): the app, or `connectSubagentView`, folds the pane. |
| `data-empty`  | Written BY the element while there is nothing to show (an unknown sub-agent, or one not started yet): it then draws nothing. Read-only; style or fold your layout against it.                                           |
| `data-inline` | Written BY the element when it is a line’s detail rather than a view of its own. Read-only.                                                                                                                             |

**Properties**

| Property | Type                         | Description                                                                                          |
| -------- | ---------------------------- | ---------------------------------------------------------------------------------------------------- |
| `chat`   | `SubagentViewSource \| null` | The chat, when it has no `id` for the `for` attribute: an element, or anything with `getMessages()`. |

**Methods**

| Method               | Description                                                                                        |
| -------------------- | -------------------------------------------------------------------------------------------------- |
| `focusTitle(): void` | Put the focus on the sub-agent’s name, in a `closable` view: where a pane that just opened starts. |
| `refresh(): void`    | Read the sub-agent again and draw it: what the element does on every change it hears.              |

**Events**

| Event                        | Type                                      | Description                                                                                                                                                                                                                                                                                                                               |
| ---------------------------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `aparte-subagent-view-close` | `CustomEvent`                             | The Close button, or Escape inside a `closable` view. The view does not hide itself: the app owns the layout. Bubbles.                                                                                                                                                                                                                    |
| `aparte-link-click`          | `CustomEvent<AparteLinkClickEventDetail>` | A link the sub-agent wrote is about to be followed. Sent on the chat (`for` or `chat`; the view itself when it names none), as a message sends its own, so the listener that routes a reply’s links routes these. Cancelable: `preventDefault()` keeps the browser from navigating. Under a line, inside the reply, the message sends it. |

**CSS variables**

| Variable                   | Default                 | Description                                                                                  |
| -------------------------- | ----------------------- | -------------------------------------------------------------------------------------------- |
| `--aparte-subagent-indent` | `var(--aparte-space-6)` | The space between the rule down the leading edge and the conversation, in a standalone view. |

## Related

[Section titled “Related”](#related)

* [Sub-agents](/guides/sub-agents/) — the line in the reply, and the three ways sub-agents reach the page.
* [Split](/components/split/) — the two panes this view usually sits in.
* [Tool](/components/tool/) — the row a sub-agent’s line is drawn on.
