Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

42.1 KB
Raw Blame
// @vitest-environment jsdom
import { act, renderHook, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import {
  AGENT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY,
  CHAT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY,
  DRAFT_SPEC_PREFERENCES_STORAGE_KEY,
  readDraftSpecPreferences,
} from '@/server/draftSpecPreferences.js';
import { ServerProvider, useServerCapabilities, useServerCapabilitiesSettled } from '@/server/ServerContext.js';
import { ShellModeProvider, useOptionalShellMode, useShellMode, type AgentConfig } from '@/server/ShellModeContext.js';
import type { AgentUIServer } from '@/server/types.js';
import { createMockAgentSessionsServer, createMockAgentUIServer, createMockCatalog } from './mockServer.js';

function wrap(agentConfig?: AgentConfig, initialSettingsOpen?: boolean) {
  const server = createMockAgentUIServer({
    catalog: createMockCatalog(),
    sessions: createMockAgentSessionsServer(),
  });
  return function Wrapper({ children }: { children: ReactNode }) {
    return (
      <ServerProvider server={server}>
        <ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}>
          {children}
        </ShellModeProvider>
      </ServerProvider>
    );
  };
}

function wrapWithoutCatalog(agentConfig?: AgentConfig, initialSettingsOpen?: boolean) {
  const server = createMockAgentUIServer({ catalog: undefined });
  return function Wrapper({ children }: { children: ReactNode }) {
    return (
      <ServerProvider server={server}>
        <ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}>
          {children}
        </ShellModeProvider>
      </ServerProvider>
    );
  };
}

function wrapWithoutSessions(agentConfig?: AgentConfig) {
  const server = createMockAgentUIServer({ catalog: createMockCatalog() });
  return function Wrapper({ children }: { children: ReactNode }) {
    return (
      <ServerProvider server={server}>
        <ShellModeProvider agentConfig={agentConfig}>{children}</ShellModeProvider>
      </ServerProvider>
    );
  };
}

function wrapWithServer(server: AgentUIServer, agentConfig?: AgentConfig) {
  return function Wrapper({ children }: { children: ReactNode }) {
    return (
      <ServerProvider server={server}>
        <ShellModeProvider agentConfig={agentConfig}>{children}</ShellModeProvider>
      </ServerProvider>
    );
  };
}

describe('ShellModeProvider', () => {
  beforeEach(() => {
    window.localStorage.removeItem(DRAFT_SPEC_PREFERENCES_STORAGE_KEY);
    window.localStorage.removeItem(CHAT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY);
    window.localStorage.removeItem(AGENT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY);
  });

  it('requires a provider for useShellMode', () => {
    expect(() => renderHook(() => useShellMode())).toThrow('useShellMode must be used within a ShellModeProvider.');
  });

  it('returns null from useOptionalShellMode outside a provider', () => {
    const { result } = renderHook(() => useOptionalShellMode());

    expect(result.current).toBeNull();
  });

  it('waits for explicit capability before honoring initialSettingsOpen', async () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrap(undefined, true) });
    expect(result.current.settingsOpen).toBe(false);
    await waitFor(() => expect(result.current.settingsOpen).toBe(true));
    expect(result.current.settingsSection).toBe('models');

    act(() => result.current.setSettingsOpen(false));
    expect(result.current.settingsOpen).toBe(false);
    act(() => result.current.openDraft());
    expect(result.current.settingsOpen).toBe(false);
  });

  it('ignores initialSettingsOpen when Settings chrome has no catalog', () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrapWithoutCatalog(undefined, true) });
    expect(result.current.settingsOpen).toBe(false);
    act(() => result.current.setSettingsOpen(true));
    expect(result.current.settingsOpen).toBe(false);
  });

  it('ignores initialSettingsOpen when Settings capability is disabled', async () => {
    const server = createMockAgentUIServer({
      catalog: createMockCatalog(),
      getCapabilities: async () => ({
        data: {
          sandbox: { enabled: true },
          skill: { enabled: true },
          settings: { enabled: false },
        },
      }),
    });
    const { result } = renderHook(
      () => ({
        shell: useShellMode(),
        capabilities: useServerCapabilities(),
      }),
      {
        wrapper: function Wrapper({ children }: { children: ReactNode }) {
          return (
            <ServerProvider server={server}>
              <ShellModeProvider initialSettingsOpen>{children}</ShellModeProvider>
            </ServerProvider>
          );
        },
      },
    );

    expect(result.current.shell.settingsOpen).toBe(false);
    await waitFor(() => expect(result.current.capabilities?.settings?.enabled).toBe(false));
    act(() => result.current.shell.setSettingsOpen(true));
    expect(result.current.shell.settingsOpen).toBe(false);
  });

  it('opens settings to a requested section', async () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });

    await waitFor(() => {
      act(() => result.current.setSettingsOpen(true, 'connectors'));
      expect(result.current.settingsOpen).toBe(true);
    });
    expect(result.current.settingsSection).toBe('connectors');
  });

  it('closes the library when settings opens and vice versa', async () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });

    act(() => result.current.setLibraryOpen(true));
    expect(result.current.libraryOpen).toBe(true);
    expect(result.current.settingsOpen).toBe(false);

    await waitFor(() => {
      act(() => result.current.setSettingsOpen(true));
      expect(result.current.settingsOpen).toBe(true);
    });
    expect(result.current.libraryOpen).toBe(false);

    act(() => result.current.setLibraryOpen(true));
    expect(result.current.libraryOpen).toBe(true);
    expect(result.current.settingsOpen).toBe(false);
  });

  it('keeps agent config exclusive to New Agent surfaces', () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });

    act(() => result.current.openAgentBuilder());
    expect(result.current.mode).toMatchObject({ isMutable: true, isCreateAgent: true });
    expect(result.current.agentConfigOpen).toBe(true);

    act(() => result.current.setSettingsOpen(true));
    expect(result.current.agentConfigOpen).toBe(false);

    act(() => result.current.openAgentBuilder());
    expect(result.current.agentConfigOpen).toBe(true);
    act(() => result.current.selectLibraryAgent({ isMutable: false, agentName: 'support' }));
    expect(result.current.agentConfigOpen).toBe(false);
  });

  it('resumes the active agent builder without resetting its runtime', () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });

    act(() => result.current.openAgentBuilder());
    const builderRuntimeKey = result.current.runtimeKey;

    act(() => result.current.setLibraryOpen(true));
    expect(result.current.libraryOpen).toBe(true);
    expect(result.current.agentConfigOpen).toBe(false);

    act(() => result.current.openAgentBuilder());
    expect(result.current.libraryOpen).toBe(false);
    expect(result.current.agentConfigOpen).toBe(true);
    expect(result.current.runtimeKey).toBe(builderRuntimeKey);
  });

  it('starts a fresh agent builder after leaving a saved builder', () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });

    act(() => result.current.openAgentBuilder());
    act(() =>
      result.current.rememberDraftSpec(
        {
          model: { name: 'saved/model' },
          instructions: 'Keep building trips.',
          mcpServers: [{ name: 'exa' }],
          skills: [{ name: 'research' }],
          config: { sandbox: { enabled: true } },
        },
        'agent',
      ),
    );
    act(() =>
      result.current.bindMutableAgent({
        agentId: 'saved',
        agentName: 'saved',
        agentSpec: {
          model: { name: 'saved/model' },
          instructions: 'Keep building trips.',
          mcpServers: [{ name: 'exa' }],
          skills: [{ name: 'research' }],
          config: { sandbox: { enabled: true } },
        },
      }),
    );
    expect(result.current.mode).toMatchObject({ agentId: 'saved', agentName: 'saved' });

    act(() => result.current.setLibraryOpen(true));
    act(() => result.current.openAgentBuilder());

    expect(result.current.mode).toMatchObject({
      status: 'active',
      isMutable: true,
      isCreateAgent: true,
      agentSpec: {
        model: { name: 'saved/model' },
        config: { sandbox: { enabled: true } },
      },
    });
    if (result.current.mode.status !== 'active') throw new Error('expected active mode');
    expect(result.current.mode.agentId).toBeUndefined();
    expect(result.current.mode.agentName).toBeUndefined();
    expect(result.current.mode.agentSpec).not.toHaveProperty('instructions');
    expect(result.current.mode.agentSpec).not.toHaveProperty('mcpServers');
    expect(result.current.mode.agentSpec).not.toHaveProperty('skills');
  });

  it('resetAgentBuilder clears config mounts and saved identity', () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });

    act(() => result.current.openAgentBuilder());
    act(() =>
      result.current.bindMutableAgent({
        agentId: 'saved',
        agentName: 'saved',
        agentSpec: {
          model: { name: 'saved/model' },
          instructions: 'Keep building trips.',
          mcpServers: [{ name: 'exa' }],
          skills: [{ name: 'research' }],
          config: { sandbox: { enabled: true } },
        },
      }),
    );

    const beforeKey = result.current.runtimeKey;
    act(() => result.current.resetAgentBuilder());

    expect(result.current.runtimeKey).not.toBe(beforeKey);
    expect(result.current.mode).toMatchObject({
      status: 'active',
      isMutable: true,
      isCreateAgent: true,
      agentSpec: {
        model: { name: 'saved/model' },
        config: { sandbox: { enabled: true } },
      },
    });
    if (result.current.mode.status !== 'active') throw new Error('expected active mode');
    expect(result.current.mode.agentId).toBeUndefined();
    expect(result.current.mode.agentSpec).not.toHaveProperty('mcpServers');
  });

  it('keeps left panel clean after save → New Chat → Build Agent', () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });

    act(() => result.current.openAgentBuilder());
    act(() =>
      result.current.rememberDraftSpec(
        {
          model: { name: 'saved/model' },
          instructions: 'Keep building trips.',
          mcpServers: [{ name: 'exa' }],
          skills: [{ name: 'research' }],
          config: { sandbox: { enabled: true } },
        },
        'agent',
      ),
    );
    act(() =>
      result.current.bindMutableAgent({
        agentId: 'saved',
        agentName: 'saved',
        agentSpec: {
          model: { name: 'saved/model' },
          instructions: 'Keep building trips.',
          mcpServers: [{ name: 'exa' }],
          skills: [{ name: 'research' }],
          config: { sandbox: { enabled: true } },
        },
      }),
    );

    act(() => result.current.openDraft());
    act(() => result.current.openAgentBuilder());

    expect(result.current.mode).toMatchObject({
      status: 'active',
      isMutable: true,
      isCreateAgent: true,
      agentSpec: {
        model: { name: 'saved/model' },
        config: { sandbox: { enabled: true } },
      },
    });
    if (result.current.mode.status !== 'active') throw new Error('expected active mode');
    expect(result.current.mode.agentSpec).not.toHaveProperty('mcpServers');
    expect(result.current.mode.agentSpec).not.toHaveProperty('skills');
    expect(result.current.mode.agentSpec).not.toHaveProperty('instructions');
  });

  it('resetAgentBuilder prefers the live draft over the open/save snapshot', () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });

    act(() => result.current.openAgentBuilder());
    act(() =>
      result.current.rememberDraftSpec(
        {
          model: { name: 'opened/model' },
          config: { sandbox: { enabled: false } },
        },
        'agent',
      ),
    );

    act(() =>
      result.current.resetAgentBuilder({
        model: { name: 'live/model' },
        mcpServers: [{ name: 'exa' }],
        config: { sandbox: { enabled: true }, webSearch: { enabled: true } },
      }),
    );

    expect(result.current.mode).toMatchObject({
      status: 'active',
      isMutable: true,
      isCreateAgent: true,
      agentSpec: {
        model: { name: 'live/model' },
        config: { sandbox: { enabled: true }, webSearch: { enabled: true } },
      },
    });
    if (result.current.mode.status !== 'active') throw new Error('expected active mode');
    expect(result.current.mode.agentSpec).not.toHaveProperty('mcpServers');
  });

  it('restores the active agent draft after visiting New Chat', () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });
    const agentDraft = {
      model: { name: 'chosen/model' },
      instructions: 'Keep these instructions.',
    };

    act(() => result.current.openAgentBuilder());
    act(() => result.current.rememberDraftSpec(agentDraft, 'agent'));
    act(() => result.current.openDraft());
    act(() => result.current.openAgentBuilder());

    expect(result.current.mode).toMatchObject({
      status: 'active',
      isMutable: true,
      isCreateAgent: true,
      agentSpec: agentDraft,
    });
    expect(readDraftSpecPreferences('agent')).not.toHaveProperty('instructions');
  });

  it('openDraft starts New Chat without agent config; openAgentBuilder opens config', () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });

    expect(result.current.mode).toMatchObject({ isMutable: true, isCreateAgent: false });
    expect(result.current.agentConfigOpen).toBe(false);

    act(() => result.current.openAgentBuilder());
    expect(result.current.mode).toMatchObject({ isMutable: true, isCreateAgent: true });
    expect(result.current.agentConfigOpen).toBe(true);

    act(() => result.current.openDraft());
    expect(result.current.mode).toMatchObject({ isMutable: true, isCreateAgent: false });
    expect(result.current.agentConfigOpen).toBe(false);
  });

  it('openHistorySession applies isCreateAgent only when mutable', () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });

    act(() => result.current.openHistorySession({ sessionId: 'sess-builder', isMutable: true, isCreateAgent: true }));
    expect(result.current.mode).toMatchObject({ isMutable: true, isCreateAgent: true });
    expect(result.current.agentConfigOpen).toBe(true);
    expect(result.current.pendingSessionId).toBe('sess-builder');

    act(() => result.current.openHistorySession({ sessionId: 'sess-chat', isMutable: true }));
    expect(result.current.mode).toMatchObject({ isMutable: true, isCreateAgent: false });
    expect(result.current.agentConfigOpen).toBe(false);
  });

  it('opens agent details and returns to the library list', () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });

    act(() => result.current.openLibraryAgent('agent-1'));
    expect(result.current.libraryOpen).toBe(true);
    expect(result.current.libraryAgentId).toBe('agent-1');

    act(() => result.current.closeLibraryAgent());
    expect(result.current.libraryOpen).toBe(true);
    expect(result.current.libraryAgentId).toBeNull();

    act(() => result.current.setLibraryAgentId('agent-2'));
    expect(result.current.libraryAgentId).toBe('agent-2');

    act(() => result.current.setLibraryOpen(false));
    expect(result.current.libraryOpen).toBe(false);
    expect(result.current.libraryAgentId).toBeNull();
  });

  it('ignores openLibraryAgent and sessions open when sessions port is missing', () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrapWithoutSessions() });

    act(() => result.current.openLibraryAgent('agent-1'));
    expect(result.current.libraryOpen).toBe(false);
    expect(result.current.libraryAgentId).toBeNull();

    act(() => result.current.setSessionsOpen(true));
    expect(result.current.sessionsOpen).toBe(false);
  });

  it('defaults to AgentLibraryWithComposer (mutable + library)', () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });
    expect(result.current.mode).toMatchObject({ status: 'active', isMutable: true, locked: false });
    expect(result.current.isLibraryEnabled).toBe(true);
    expect(result.current.isComposerEnabled).toBe(true);
    expect(result.current.isNewChatEnabled).toBe(true);
  });

  it('locks SingleAgent and ignores selectAgent / openDraft', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'SingleAgent', name: 'locked' }),
    });
    expect(result.current.mode).toEqual({
      status: 'active',
      isMutable: false,
      isCreateAgent: false,
      agentId: 'locked',
      agentName: 'locked',
      locked: true,
    });
    expect(result.current.isLibraryEnabled).toBe(false);
    expect(result.current.isComposerEnabled).toBe(false);

    act(() => result.current.selectAgent('other'));
    act(() => result.current.openDraft());
    expect(result.current.mode).toEqual({
      status: 'active',
      isMutable: false,
      isCreateAgent: false,
      agentId: 'locked',
      agentName: 'locked',
      locked: true,
    });
  });

  it('starts AgentLibrary idle, then selectAgent → immutable', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibrary' }),
    });
    expect(result.current.mode.status).toBe('idle');
    expect(result.current.isNewChatEnabled).toBe(false);
    expect(result.current.isComposerEnabled).toBe(false);
    expect(result.current.isLibraryEnabled).toBe(true);

    act(() => result.current.selectAgent('alpha'));
    expect(result.current.mode).toEqual({
      status: 'active',
      isMutable: false,
      isCreateAgent: false,
      agentId: 'alpha',
      agentName: 'alpha',
      locked: false,
    });

    const keyBefore = result.current.runtimeKey;
    act(() => result.current.clearChat());
    expect(result.current.mode.status).toBe('active');
    expect(result.current.mode).toMatchObject({ isMutable: false });
    expect(result.current.runtimeKey).not.toBe(keyBefore);
  });

  it('re-picking the current agent still changes runtimeKey', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibrary' }),
    });

    act(() => result.current.selectAgent('alpha'));
    const keyBefore = result.current.runtimeKey;

    act(() => result.current.selectAgent('alpha'));
    expect(result.current.mode).toEqual({
      status: 'active',
      isMutable: false,
      isCreateAgent: false,
      agentId: 'alpha',
      agentName: 'alpha',
      locked: false,
    });
    expect(result.current.runtimeKey).not.toBe(keyBefore);
  });

  it('AgentComposer stays mutable; clearChat bumps epoch', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({
        mode: 'AgentComposer',
        defaultAgentSpec: { model: { name: 'openai-main/gpt-4.1' } },
      }),
    });
    expect(result.current.mode).toMatchObject({ status: 'active', isMutable: true });
    expect(result.current.isLibraryEnabled).toBe(false);
    expect(result.current.isComposerEnabled).toBe(true);

    act(() => result.current.selectAgent('nope'));
    expect(result.current.mode).toMatchObject({ status: 'active', isMutable: true });

    const keyBefore = result.current.runtimeKey;
    act(() => result.current.clearChat());
    expect(result.current.mode).toMatchObject({ status: 'active', isMutable: true });
    expect(result.current.runtimeKey).not.toBe(keyBefore);
  });

  it('clearChat and openDraft keep a disabled chat web-search preference', async () => {
    const { result } = renderHook(() => ({ shell: useShellMode(), settled: useServerCapabilitiesSettled() }), {
      wrapper: wrap({
        mode: 'AgentComposer',
        defaultAgentSpec: {
          model: { name: 'openai-main/gpt-4.1' },
          config: { webSearch: { enabled: true } },
        },
      }),
    });
    await waitFor(() => expect(result.current.settled).toBe(true));

    act(() =>
      result.current.shell.rememberDraftSpec(
        {
          model: { name: 'openai-main/gpt-4.1' },
          config: { webSearch: { enabled: false } },
        },
        'chat',
      ),
    );

    act(() => result.current.shell.clearChat());
    expect(result.current.shell.mode).toMatchObject({
      status: 'active',
      isMutable: true,
      isCreateAgent: false,
      agentSpec: { config: { webSearch: { enabled: false } } },
    });

    act(() =>
      result.current.shell.rememberDraftSpec(
        {
          model: { name: 'openai-main/gpt-4.1' },
          config: { webSearch: { enabled: false } },
        },
        'chat',
      ),
    );
    act(() => result.current.shell.openDraft());
    expect(result.current.shell.mode).toMatchObject({
      agentSpec: { config: { webSearch: { enabled: false } } },
    });
  });

  it('openDraft and clearChat enable web search on New Chat when the capability is available', async () => {
    const getCapabilities = vi.fn(async () => ({
      data: {
        sandbox: { enabled: true },
        skill: { enabled: true },
        settings: { enabled: true },
        webSearch: { enabled: true },
      },
    }));
    const server = createMockAgentUIServer({ catalog: createMockCatalog(), getCapabilities });
    const { result } = renderHook(
      () => ({
        shell: useShellMode(),
        capabilities: useServerCapabilities(),
      }),
      {
        wrapper: wrapWithServer(server, {
          mode: 'AgentComposer',
          defaultAgentSpec: { model: { name: 'openai-main/gpt-4.1' } },
        }),
      },
    );
    await waitFor(() => expect(result.current.capabilities?.webSearch?.enabled).toBe(true));

    act(() => result.current.shell.openDraft());
    expect(result.current.shell.mode).toMatchObject({
      status: 'active',
      isMutable: true,
      isCreateAgent: false,
      agentSpec: { config: { webSearch: { enabled: true } } },
    });

    act(() => result.current.shell.clearChat());
    expect(result.current.shell.mode).toMatchObject({
      agentSpec: { config: { webSearch: { enabled: true } } },
    });
  });

  it('does not persist capability-forced web-search off as a chat preference', async () => {
    const getCapabilities = vi.fn(async () => ({
      data: {
        sandbox: { enabled: true },
        skill: { enabled: true },
        settings: { enabled: true },
        webSearch: { enabled: false },
      },
    }));
    const server = createMockAgentUIServer({ catalog: createMockCatalog(), getCapabilities });
    const { result } = renderHook(
      () => ({
        shell: useShellMode(),
        capabilities: useServerCapabilities(),
      }),
      {
        wrapper: wrapWithServer(server, {
          mode: 'AgentComposer',
          defaultAgentSpec: { model: { name: 'openai-main/gpt-4.1' } },
        }),
      },
    );
    await waitFor(() => expect(result.current.capabilities?.webSearch?.enabled).toBe(false));

    act(() =>
      result.current.shell.rememberDraftSpec(
        {
          model: { name: 'openai-main/gpt-4.1' },
          config: { webSearch: { enabled: true } },
        },
        'chat',
      ),
    );

    expect(readDraftSpecPreferences('chat')).toEqual({
      model: { name: 'openai-main/gpt-4.1' },
    });
  });

  it('clearChat is a no-op while idle', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibrary' }),
    });
    const key = result.current.runtimeKey;
    act(() => result.current.clearChat());
    expect(result.current.runtimeKey).toBe(key);
    expect(result.current.mode.status).toBe('idle');
  });

  it('openDraft and selectAgent close Settings', async () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
    });

    await waitFor(() => {
      act(() => result.current.setSettingsOpen(true));
      expect(result.current.settingsOpen).toBe(true);
    });

    act(() => result.current.openDraft());
    expect(result.current.settingsOpen).toBe(false);
    expect(result.current.mode).toMatchObject({ status: 'active', isMutable: true });

    act(() => result.current.setSettingsOpen(true));
    act(() => result.current.selectAgent('alpha'));
    expect(result.current.settingsOpen).toBe(false);
    expect(result.current.mode).toEqual({
      status: 'active',
      isMutable: false,
      isCreateAgent: false,
      agentId: 'alpha',
      agentName: 'alpha',
      locked: false,
    });
  });

  it('selectLibraryAgent Edit seeds mutable binding with agentSpec', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
    });
    const spec = {
      model: { name: 'custom/model' },
      skills: [{ id: 's1', name: 'Skill' }],
      mcpServers: [{ id: 'm1', name: 'MCP' }],
    };

    act(() =>
      result.current.selectLibraryAgent({
        isMutable: true,
        agentId: 'writer',
        agentName: 'writer',
        agentSpec: spec,
      }),
    );

    expect(result.current.mode).toEqual({
      status: 'active',
      isMutable: true,
      isCreateAgent: true,
      agentId: 'writer',
      agentName: 'writer',
      agentSpec: spec,
      locked: false,
    });
  });

  it('clearChat on Edit preserves agentName and seeded agentSpec', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
    });
    const spec = {
      model: { name: 'custom/model' },
      skills: [{ id: 's1', name: 'Skill' }],
    };

    act(() =>
      result.current.selectLibraryAgent({
        isMutable: true,
        agentId: 'writer',
        agentName: 'writer',
        agentSpec: spec,
      }),
    );
    const keyBefore = result.current.runtimeKey;

    act(() => result.current.clearChat());

    expect(result.current.mode).toEqual({
      status: 'active',
      isMutable: true,
      isCreateAgent: true,
      agentId: 'writer',
      agentName: 'writer',
      agentSpec: spec,
      locked: false,
    });
    expect(result.current.runtimeKey).not.toBe(keyBefore);
  });

  it('clearChat on a builder keeps the live draft instead of the open snapshot', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
    });
    const opened = {
      model: { name: 'opened/model' },
      instructions: 'Opened instructions.',
    };
    const live = {
      model: { name: 'live/model' },
      instructions: 'Keep these instructions.',
      mcpServers: [{ name: 'exa' }],
      skills: [{ name: 'research' }],
      config: { sandbox: { enabled: true } },
    };

    act(() =>
      result.current.selectLibraryAgent({
        isMutable: true,
        isCreateAgent: true,
        agentSpec: opened,
      }),
    );
    const keyBefore = result.current.runtimeKey;

    act(() => result.current.clearChat(live));

    expect(result.current.runtimeKey).not.toBe(keyBefore);
    expect(result.current.mode).toMatchObject({
      status: 'active',
      isMutable: true,
      isCreateAgent: true,
      agentSpec: live,
    });
  });

  it('listSessionsAgentId follows history filter when library is enabled', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
    });
    expect(result.current.listSessionsAgentId).toBeUndefined();
    expect(result.current.historyAgentFilter).toBeNull();

    act(() =>
      result.current.setHistoryAgentFilter({
        agentId: 'from-sdk',
        agentName: 'From SDK',
        intent: 'history',
      }),
    );
    expect(result.current.historyAgentFilter).toEqual({
      agentId: 'from-sdk',
      agentName: 'From SDK',
      intent: 'history',
    });
    expect(result.current.listSessionsAgentId).toBe('from-sdk');

    act(() => result.current.setHistoryAgentFilter(null));
    expect(result.current.listSessionsAgentId).toBeUndefined();
  });

  it('filters history to an immutable agent selected from the library', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
    });

    act(() =>
      result.current.selectLibraryAgent({
        isMutable: false,
        agentId: 'agent-id',
        agentName: 'Agent Name',
      }),
    );

    expect(result.current.historyAgentFilter).toEqual({
      agentId: 'agent-id',
      agentName: 'Agent Name',
      intent: 'try-agent',
    });
    expect(result.current.listSessionsAgentId).toBe('agent-id');
  });

  it('does not use an agent name as the history agent id', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
    });

    act(() => result.current.selectLibraryAgent({ isMutable: false, agentName: 'Agent Name' }));

    expect(result.current.historyAgentFilter).toBeNull();
    expect(result.current.listSessionsAgentId).toBeUndefined();
  });

  it('SingleAgent locks listSessionsAgentId to the agent name', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'SingleAgent', name: 'locked' }),
    });
    expect(result.current.listSessionsAgentId).toBe('locked');
    act(() =>
      result.current.setHistoryAgentFilter({
        agentId: 'ignored',
        agentName: 'Ignored',
        intent: 'history',
      }),
    );
    expect(result.current.listSessionsAgentId).toBe('locked');
  });

  it('openHistorySession rebinds immutable in place without changing runtimeKey', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
    });
    expect(result.current.mode).toMatchObject({ status: 'active', isMutable: true });
    const keyBefore = result.current.runtimeKey;
    const epochBefore = result.current.pendingSessionEpoch;

    act(() => result.current.openHistorySession({ sessionId: 'sess-1', agentName: 'from-sdk' }));
    expect(result.current.mode).toEqual({
      status: 'active',
      isMutable: false,
      isCreateAgent: false,
      agentId: 'from-sdk',
      agentName: 'from-sdk',
      locked: false,
    });
    expect(result.current.pendingSessionId).toBe('sess-1');
    expect(result.current.runtimeKey).toBe(keyBefore);
    expect(result.current.pendingSessionEpoch).toBe(epochBefore + 1);
  });

  it('re-opening the same history session bumps pendingSessionEpoch', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
    });

    act(() => result.current.openHistorySession({ sessionId: 'sess-1', agentName: 'from-sdk' }));
    const epochBefore = result.current.pendingSessionEpoch;
    const keyBefore = result.current.runtimeKey;

    act(() => result.current.openHistorySession({ sessionId: 'sess-1', agentName: 'from-sdk' }));
    expect(result.current.pendingSessionId).toBe('sess-1');
    expect(result.current.pendingSessionEpoch).toBe(epochBefore + 1);
    expect(result.current.runtimeKey).toBe(keyBefore);
  });

  it('history switches across mutability keep runtimeKey stable', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
    });
    const keyBefore = result.current.runtimeKey;

    act(() => result.current.openHistorySession({ sessionId: 'sess-named', agentName: 'from-sdk' }));
    expect(result.current.runtimeKey).toBe(keyBefore);

    act(() => result.current.openHistorySession({ sessionId: 'sess-draft', isMutable: true }));
    expect(result.current.mode).toMatchObject({ status: 'active', isMutable: true });
    expect(result.current.runtimeKey).toBe(keyBefore);
  });

  it('does not queue history sessions rejected by shell capabilities', () => {
    const library = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibrary' }),
    });
    const libraryEpoch = library.result.current.pendingSessionEpoch;

    act(() => library.result.current.openHistorySession({ sessionId: 'draft', isMutable: true }));
    expect(library.result.current.pendingSessionId).toBeUndefined();
    expect(library.result.current.pendingSessionEpoch).toBe(libraryEpoch);

    const singleAgent = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'SingleAgent', name: 'locked' }),
    });
    const singleAgentEpoch = singleAgent.result.current.pendingSessionEpoch;

    act(() =>
      singleAgent.result.current.openHistorySession({
        sessionId: 'other-session',
        agentName: 'other-agent',
        isMutable: false,
      }),
    );
    expect(singleAgent.result.current.pendingSessionId).toBeUndefined();
    expect(singleAgent.result.current.pendingSessionEpoch).toBe(singleAgentEpoch);
  });

  it('openHistorySession keeps immutable binding when agentName is missing', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
    });

    act(() => result.current.openHistorySession({ sessionId: 'sess-orphan', isMutable: false }));
    expect(result.current.mode).toEqual({
      status: 'active',
      isMutable: false,
      isCreateAgent: false,
      locked: false,
    });
    expect(result.current.pendingSessionId).toBe('sess-orphan');
  });

  it('openHistorySession into mutable clears Edit identity', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({
        mode: 'AgentLibraryWithComposer',
        defaultAgentSpec: { model: { name: 'openai-main/gpt-4.1' } },
      }),
    });

    act(() =>
      result.current.selectLibraryAgent({
        isMutable: true,
        agentId: 'writer',
        agentName: 'writer',
        agentSpec: { model: { name: 'openai-main/gpt-4.1' }, instructions: 'Write.' },
      }),
    );
    expect(result.current.mode).toMatchObject({ agentName: 'writer', isMutable: true });

    act(() => result.current.openHistorySession({ sessionId: 'sess-other', isMutable: true }));
    expect(result.current.mode).toEqual({
      status: 'active',
      isMutable: true,
      isCreateAgent: false,
      agentSpec: { model: { name: 'openai-main/gpt-4.1' } },
      locked: false,
    });
    expect(result.current.pendingSessionId).toBe('sess-other');
  });

  it('invalidateAgentsList bumps agentsListEpoch', () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });
    expect(result.current.agentsListEpoch).toBe(0);
    act(() => result.current.invalidateAgentsList());
    expect(result.current.agentsListEpoch).toBe(1);
  });

  it('invalidateEnvironmentsList bumps environmentsListEpoch', () => {
    const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });
    expect(result.current.environmentsListEpoch).toBe(0);
    act(() => result.current.invalidateEnvironmentsList());
    expect(result.current.environmentsListEpoch).toBe(1);
  });

  it('bindMutableAgent attaches identity without remounting', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),
    });
    const keyBefore = result.current.runtimeKey;
    const spec = {
      model: { name: 'openai-main/gpt-4.1' },
      instructions: 'Saved.',
    };

    act(() =>
      result.current.bindMutableAgent({
        agentId: 'saved',
        agentName: 'saved',
        agentSpec: spec,
      }),
    );

    expect(result.current.mode).toEqual({
      status: 'active',
      isMutable: true,
      isCreateAgent: true,
      agentId: 'saved',
      agentName: 'saved',
      agentSpec: spec,
      locked: false,
    });
    expect(result.current.runtimeKey).toBe(keyBefore);
  });

  it('bindMutableAgent keeps runtimeKey stable even when model changes', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({
        mode: 'AgentLibraryWithComposer',
        defaultAgentSpec: { model: { name: 'openai-main/gpt-4.1' } },
      }),
    });
    const keyBefore = result.current.runtimeKey;

    act(() =>
      result.current.bindMutableAgent({
        agentId: 'saved',
        agentName: 'saved',
        agentSpec: { model: { name: 'other/model' }, instructions: 'Saved.' },
      }),
    );

    expect(result.current.runtimeKey).toBe(keyBefore);
    expect(result.current.mode).toMatchObject({
      agentId: 'saved',
      agentName: 'saved',
      agentSpec: { model: { name: 'other/model' } },
    });
  });

  it('bindMutableAgent is a no-op when not on a mutable chat', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentLibrary' }),
    });
    expect(result.current.mode.status).toBe('idle');

    act(() =>
      result.current.bindMutableAgent({
        agentId: 'x',
        agentName: 'x',
        agentSpec: { model: { name: 'openai-main/gpt-4.1' } },
      }),
    );

    expect(result.current.mode.status).toBe('idle');
  });

  it('uses remembered chat preferences for the next New Chat only', () => {
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({
        mode: 'AgentLibraryWithComposer',
        defaultAgentSpec: { model: { name: 'default/model' } },
      }),
    });

    act(() =>
      result.current.rememberDraftSpec({
        model: { name: 'chosen/model' },
        skills: [{ name: 'Research' }],
        mcpServers: [{ name: 'GitHub' }],
        config: { sandbox: { enabled: true } },
        instructions: 'Do not retain this.',
      }),
    );
    act(() =>
      result.current.rememberDraftSpec(
        {
          model: { name: 'agent/model' },
          skills: [{ name: 'Code' }],
          mcpServers: [{ name: 'Linear' }],
          config: { sandbox: { enabled: true } },
        },
        'agent',
      ),
    );
    act(() => result.current.selectAgent('saved-agent'));
    act(() => result.current.openDraft());

    expect(result.current.mode).toMatchObject({
      status: 'active',
      isMutable: true,
      isCreateAgent: false,
      agentSpec: {
        model: { name: 'chosen/model' },
        skills: [{ name: 'Research' }],
        mcpServers: [{ name: 'GitHub' }],
      },
    });
    if (result.current.mode.status !== 'active') throw new Error('expected active mode');
    expect(result.current.mode.agentSpec).not.toHaveProperty('instructions');
    expect(result.current.mode.agentSpec).not.toHaveProperty('config');

    act(() => result.current.openAgentBuilder());
    expect(result.current.mode).toMatchObject({
      status: 'active',
      isMutable: true,
      isCreateAgent: true,
      agentSpec: {
        model: { name: 'agent/model' },
        skills: [{ name: 'Code' }],
        mcpServers: [{ name: 'Linear' }],
        config: { sandbox: { enabled: true } },
      },
    });
  });

  it('preserves a host-seeded sandbox while capabilities are unavailable', () => {
    const hostSeed = { model: { name: 'chosen/model' }, config: { sandbox: { enabled: true } } };
    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({ mode: 'AgentComposer', defaultAgentSpec: hostSeed }),
    });

    act(() => result.current.rememberDraftSpec(hostSeed, 'agent'));

    expect(readDraftSpecPreferences('agent')).toEqual({
      model: { name: 'chosen/model' },
      config: { sandbox: { enabled: true } },
    });
  });

  it('does not treat sandbox availability as the selected runtime value', async () => {
    const getCapabilities = vi.fn(async () => ({
      data: {
        sandbox: { enabled: true },
        skill: { enabled: true },
      },
    }));
    const server = createMockAgentUIServer({ getCapabilities });
    const { result } = renderHook(
      () => ({
        shell: useShellMode(),
        capabilities: useServerCapabilities(),
      }),
      { wrapper: wrapWithServer(server, { mode: 'AgentComposer' }) },
    );
    await waitFor(() => expect(result.current.capabilities?.sandbox.enabled).toBe(true));

    act(() => result.current.shell.rememberDraftSpec({ model: { name: 'chosen/model' } }, 'agent'));

    expect(readDraftSpecPreferences('agent')).toEqual({
      model: { name: 'chosen/model' },
    });
  });

  it('overrides a host-seeded sandbox when loaded capabilities disable it', async () => {
    const getCapabilities = vi.fn(async () => ({
      data: {
        sandbox: { enabled: false },
        skill: { enabled: false },
      },
    }));
    const server = createMockAgentUIServer({ getCapabilities });
    const { result } = renderHook(
      () => ({
        shell: useShellMode(),
        capabilities: useServerCapabilities(),
      }),
      { wrapper: wrapWithServer(server, { mode: 'AgentComposer' }) },
    );
    await waitFor(() => expect(result.current.capabilities?.sandbox.enabled).toBe(false));
    const hostSeed = { model: { name: 'chosen/model' }, config: { sandbox: { enabled: true } } };

    act(() => result.current.shell.rememberDraftSpec(hostSeed, 'agent'));

    expect(readDraftSpecPreferences('agent')).toEqual({
      model: { name: 'chosen/model' },
      config: { sandbox: { enabled: false } },
    });
  });

  it('hydrates remembered chat preferences on first paint and migrates the legacy key', () => {
    window.localStorage.setItem(
      DRAFT_SPEC_PREFERENCES_STORAGE_KEY,
      JSON.stringify({
        version: 1,
        spec: {
          model: { name: 'remembered/model' },
          config: { sandbox: { enabled: true } },
        },
      }),
    );

    const { result } = renderHook(() => useShellMode(), {
      wrapper: wrap({
        mode: 'AgentComposer',
        defaultAgentSpec: { model: { name: 'default/model' } },
      }),
    });

    expect(result.current.mode).toMatchObject({
      status: 'active',
      isMutable: true,
      isCreateAgent: false,
      agentSpec: { model: { name: 'remembered/model' } },
    });
    if (result.current.mode.status !== 'active') throw new Error('expected active mode');
    expect(result.current.mode.agentSpec).not.toHaveProperty('config');
    expect(readDraftSpecPreferences('chat')).toEqual({ model: { name: 'remembered/model' } });
    expect(readDraftSpecPreferences('agent')).toEqual({
      model: { name: 'remembered/model' },
      config: { sandbox: { enabled: true } },
    });
  });
});