# A minimal web template

A complete template that typechecks, builds, and is listed under Settings → Appearance → Layout on Po 0.0.0-alpha.134. Copy it, set every `@agimon-ai/*` version to what `po --version` prints, rename `my-template` (the template id, from the file name) and `my-po-template` (the package), then change the layout. It draws a rail on the left, the conversation in the middle and the activity dock on the right, using only Po's public packages.

Paths are relative to the package folder. Repeat `my-template.web.ts` under `src/extensions/workspaces/(frontend)/template/` and `src/extensions/workspaces/sessions/(frontend)/template/` (with the import path adjusted) if the template should also be offered there, as Po's own templates do.

`MySettings` keeps Appearance, where the person switches templates. Leave it in, or they can only switch back by editing `web.template` in `config.yaml`.

## `package.json`

```json
{
  "name": "my-po-template",
  "version": "0.0.0",
  "private": true,
  "type": "module",
  "files": ["dist"],
  "exports": {
    "./package.json": "./package.json"
  },
  "scripts": {
    "build": "tsdown",
    "typecheck": "tsc --noEmit"
  },
  "dependencies": {
    "@agimon-ai/po-core": "0.0.0-alpha.134",
    "@agimon-ai/po-web-components": "0.0.0-alpha.134",
    "@agimon-ai/po-web-dashboard": "0.0.0-alpha.134",
    "@tanstack/react-router": "1.170.45",
    "@tanstack/react-store": "0.11.2"
  },
  "devDependencies": {
    "@agimon-ai/po-build": "0.0.0-alpha.134",
    "@types/react": "19.3.0",
    "react": "19.3.1",
    "tsdown": "0.23.1",
    "typescript": "7.0.2"
  },
  "peerDependencies": {
    "react": "^19.0.0"
  }
}
```

## `tsdown.config.ts`

```ts
import { poExtension } from '@agimon-ai/po-build/tsdown';
import { defineConfig } from 'tsdown';

/** Entries come from the folder tree under src/extensions. */
export default defineConfig(poExtension());
```

## `tsconfig.json`

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["ES2023", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "jsx": "react-jsx",
    "strict": true,
    "noEmit": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "allowImportingTsExtensions": true,
    "types": []
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist", "src/**/*.native.*"]
}
```

## `src/extensions/(frontend)/template/my-template.web.ts`

```ts
import { defineWebTemplate } from '@agimon-ai/po-core/web';

import { myTemplate } from './_lib/definition';

export default defineWebTemplate(myTemplate);
```

## `src/extensions/(frontend)/template/_lib/definition.ts`

```ts
import type { WebTemplateFile } from '@agimon-ai/po-core/web';

import { MyDashboard } from '../_components/MyDashboard';
import { MyLayoutPreview } from '../_components/MyLayoutPreview';

export const myTemplate = {
  label: 'My template',
  description: 'A rail on the left, the conversation in the middle, activity on the right.',
  contractVersion: 3,
  app: MyDashboard,
  preview: MyLayoutPreview,
} satisfies WebTemplateFile;
```

## `src/extensions/(frontend)/template/_components/MyLayoutPreview.tsx`

Optional. The sketch on this template's Layout card in Settings > Appearance: static, no props, theme token classes only.

```tsx
export function MyLayoutPreview() {
  return (
    <div aria-hidden className="flex h-full gap-1 rounded border border-po-border bg-po-panel p-1">
      <div className="w-1/5 rounded-sm bg-po-faint" />
      <div className="flex flex-1 flex-col justify-end gap-1 rounded-sm bg-po-bg p-1">
        <div className="h-1.5 w-2/3 rounded-sm bg-po-dim" />
        <div className="h-2 rounded-sm bg-po-border" />
      </div>
      <div className="w-1/5 rounded-sm bg-po-faint" />
    </div>
  );
}
```

## `src/extensions/(frontend)/template/_components/MyDashboard.tsx`

```tsx
import {
  DashboardRendererProvider,
  type DashboardRenderers,
  HOST_SLOTS,
  sessionsStore,
  useDashboardRoute,
  watchDashboardTranscript,
} from '@agimon-ai/po-web-dashboard';
import {
  CommandPalette,
  DialogOverlay,
  PluginSurface,
  RefusedCard,
  SessionActivity,
  SessionTranscriptView,
  ThreadView,
} from '@agimon-ai/po-web-dashboard/views';
import { useStore } from '@tanstack/react-store';

import { MyConversation } from './MyConversation';
import { MySettings } from './MySettings';

/** How threads, activity and transcripts render when another view asks for them. */
const renderers: DashboardRenderers = {
  thread: (id, threadId, options) => <ThreadView sessionId={id} threadId={threadId} options={options} />,
  activity: (id, open) => <SessionActivity sessionId={id} onOpenConversation={open} />,
  transcript: (id, options) => (
    <SessionTranscriptView sessionId={id} options={options} watch={watchDashboardTranscript} />
  ),
};

/** The whole app. It takes no props: every piece reads Po's stores and the URL itself. */
export function MyDashboard() {
  const route = useDashboardRoute();
  const sessionId = useStore(sessionsStore, (state) => state.activeId);
  return (
    <DashboardRendererProvider value={renderers}>
      {route.kind === 'settings' ? <MySettings /> : <MyConversation />}
      {/* Host dialogs and overlays. Leave none out: approvals and plugin overlays, remote access and pairing among them, render here. */}
      <DialogOverlay />
      <RefusedCard />
      <CommandPalette />
      <PluginSurface slot={HOST_SLOTS.overlay} sessionId={sessionId} />
    </DashboardRendererProvider>
  );
}
```

## `src/extensions/(frontend)/template/_components/MyConversation.tsx`

```tsx
import {
  findTransientTab,
  pluginActivityGroups,
  setDockOpen,
  transientTabsStore,
  uiStore,
  useDashboardRoute,
  useNoSessions,
  usePluginSlotProps,
  useWebPluginRegistry,
  webTabs,
} from '@agimon-ai/po-web-dashboard';
import {
  ActivityDock,
  Composer,
  HomePage,
  PluginPage,
  SelectionBar,
  SessionRailDialogs,
  Timeline,
  TopBar,
  useSessionRail,
  WelcomePanel,
  WorkspacePage,
} from '@agimon-ai/po-web-dashboard/views';
import { useStore } from '@tanstack/react-store';

import { MyAddWorkspace } from './MyAddWorkspace';
import { MyRail } from './MyRail';

/** Rail, main column (header, content, composer, mode controls) and the activity dock. */
export function MyConversation() {
  useWebPluginRegistry();
  const rail = useSessionRail({});
  const dockOpen = useStore(uiStore, (state) => state.dockOpen);
  const { kind, sessionId, tabId, pageId, workspaceId: routeWorkspaceId } = useDashboardRoute();
  const slotProps = usePluginSlotProps(sessionId ?? null);
  const noSessions = useNoSessions();

  // A plugin tab: one the session declares, else one a plugin opened at runtime.
  const storedTab = useStore(transientTabsStore, (state) => findTransientTab(state, sessionId, tabId));
  const transientTab =
    storedTab === undefined
      ? undefined
      : (pluginActivityGroups(sessionId ?? null)
          .map((group) => group.transientTab?.())
          .find((candidate) => candidate?.id === storedTab.id) ?? storedTab);
  const tab =
    (tabId === undefined ? undefined : webTabs(sessionId ?? null).find((entry) => entry.id === tabId)) ?? transientTab;

  // Home, a workspace dashboard or a plugin page replaces the conversation and draws its own header.
  const page =
    pageId !== undefined ? (
      <PluginPage pageId={pageId} sessionId={null} workspaceId={routeWorkspaceId} />
    ) : kind === 'workspace' && routeWorkspaceId !== undefined ? (
      <WorkspacePage workspaceId={routeWorkspaceId} />
    ) : kind === 'home' && !noSessions ? (
      <HomePage />
    ) : null;

  return (
    <div data-testid="cockpit" className="flex h-full min-w-0 overflow-hidden bg-po-bg">
      <aside
        ref={rail.scrollRef}
        data-po-region="rail"
        className="flex w-72 shrink-0 flex-col overflow-y-auto border-r border-po-border-soft bg-po-rail"
      >
        <MyRail rail={rail} />
      </aside>
      <main data-po-region="content" className="flex min-w-0 flex-1 flex-col overflow-hidden">
        {page ? null : <TopBar view={tab?.id ?? 'conversation'} />}
        <div className="mx-auto flex min-h-0 w-full max-w-4xl flex-1 flex-col overflow-hidden px-4">
          {page ?? (tab ? <tab.panel {...slotProps} /> : noSessions ? <WelcomePanel /> : <Timeline />)}
          {page || noSessions || (tab && tab.retainComposer !== true) ? null : (
            <Composer composerContext={tab === transientTab ? transientTab?.composerContext : undefined} />
          )}
          {page || noSessions || tab ? null : <SelectionBar />}
        </div>
      </main>
      {page || !dockOpen ? null : (
        <div data-po-region="activity" className="flex w-96 shrink-0">
          <ActivityDock onClose={() => setDockOpen(false)} onOpenContent={() => undefined} />
        </div>
      )}
      {/* New session, resume, move and other rail dialogs. */}
      <SessionRailDialogs />
      {rail.addWorkspace ? <MyAddWorkspace rail={rail} /> : null}
    </div>
  );
}
```

## `src/extensions/(frontend)/template/_components/MyRail.tsx`

```tsx
import type { WebTemplateRail } from '@agimon-ai/po-core/web';
import { Button } from '@agimon-ai/po-web-components';
import { HOST_SLOTS } from '@agimon-ai/po-web-dashboard';
import { PluginSurface } from '@agimon-ai/po-web-dashboard/views';

/**
 * The session list. `useSessionRail` supplies the data and every action; the template only draws it.
 * Adding a workspace opens when `rail.addWorkspace` is set: draw a dialog that calls `rail.actions.addWorkspace`.
 */
export function MyRail({ rail }: { rail: WebTemplateRail }) {
  const { actions } = rail;
  return (
    <nav aria-label="Sessions" className="flex flex-col gap-4 p-3">
      <div className="flex gap-2">
        <Button variant={rail.homeActive ? 'outline' : 'ghost'} size="sm" onClick={actions.openHome}>
          Home
        </Button>
        <Button variant="ghost" size="sm" onClick={actions.openSettings}>
          Settings
        </Button>
      </div>
      {rail.workspaces.map((workspace) => (
        <section key={workspace.id} className="flex flex-col gap-1">
          {workspace.kind === 'session' ? null : (
            <div className="flex items-center justify-between gap-2 px-2">
              <span className="truncate text-sm font-semibold text-po-dim">{workspace.name}</span>
              {workspace.legacy ? null : (
                <Button variant="ghost" size="sm" onClick={() => actions.createSession(workspace.id)}>
                  New
                </Button>
              )}
            </div>
          )}
          {workspace.sessions.map((session) => (
            <Button
              key={session.id}
              variant={session.active ? 'outline' : 'ghost'}
              className={`justify-start ${session.nested ? 'pl-6' : ''}`}
              onClick={() => actions.openSession(session.id)}
            >
              <span className="min-w-0 flex-1 truncate text-left">{session.name}</span>
              {session.waitingCount ? <span className="text-po-magenta">{session.waitingCount}</span> : null}
            </Button>
          ))}
        </section>
      ))}
      {actions.createGeneralSession ? (
        <Button variant="outline" size="sm" onClick={actions.createGeneralSession}>
          New session
        </Button>
      ) : null}
      <Button variant="ghost" size="sm" onClick={actions.openAddWorkspace}>
        Add workspace
      </Button>
      {rail.pluginContent}
      {/* Status controls such as remote access. The spot name picks how po-remote draws its control. */}
      <div data-rail-status="elegant-action" className="contents">
        <PluginSurface slot={HOST_SLOTS.railStatus} sessionId={null} />
      </div>
    </nav>
  );
}
```

## `src/extensions/(frontend)/template/_components/MyAddWorkspace.tsx`

```tsx
import type { WebTemplateRail } from '@agimon-ai/po-core/web';
import { Button } from '@agimon-ai/po-web-components';
import { useState } from 'react';

/** Shown while `rail.addWorkspace` is set. An empty path creates `~/.po/workspace/<name>`. */
export function MyAddWorkspace({ rail }: { rail: WebTemplateRail }) {
  const [name, setName] = useState('');
  const [path, setPath] = useState(rail.addWorkspace?.suggestedPaths[0] ?? '');
  const [error, setError] = useState<string>();
  return (
    <div role="dialog" aria-label="Add workspace" className="fixed inset-0 z-50 grid place-items-center bg-black/55">
      <form
        className="flex w-96 flex-col gap-3 rounded-lg border border-po-border bg-po-panel p-4"
        onSubmit={(event) => {
          event.preventDefault();
          void rail.actions
            .addWorkspace({ name, path: path.trim() === '' ? undefined : path.trim() })
            .then((result) => setError(result?.error));
        }}
      >
        <label className="flex flex-col gap-1 text-sm text-po-dim">
          Name
          <input
            className="rounded border border-po-border bg-po-bg px-2 py-1 text-po-text"
            value={name}
            onChange={(event) => setName(event.target.value)}
            required
          />
        </label>
        <label className="flex flex-col gap-1 text-sm text-po-dim">
          Folder (optional)
          <input
            className="rounded border border-po-border bg-po-bg px-2 py-1 text-po-text"
            value={path}
            onChange={(event) => setPath(event.target.value)}
          />
        </label>
        {error ? (
          <p role="alert" className="text-sm text-po-red">
            {error}
          </p>
        ) : null}
        <div className="flex justify-end gap-2">
          <Button type="button" variant="ghost" onClick={rail.actions.closeAddWorkspace}>
            Cancel
          </Button>
          <Button type="submit">Add</Button>
        </div>
      </form>
    </div>
  );
}
```

## `src/extensions/(frontend)/template/_components/MySettings.tsx`

```tsx
import { Button } from '@agimon-ai/po-web-components';
import {
  DEFAULT_REPOSITORY_SETTINGS_SECTION,
  DEFAULT_SETTINGS_SECTION,
  refreshWebPluginCompositions,
  sessionsStore,
  settingsSection,
  useDashboardRoute,
  useDashboardState,
  useWebPluginRegistry,
} from '@agimon-ai/po-web-dashboard';
import {
  AccountSettings,
  AppearanceSettings,
  ClientDevices,
  ContributedSettings,
  ImageSettings,
  NotificationSettings,
  PresetSettings,
  ProviderSettings,
  RepositoryWorkspace,
  SettingsMenu,
  SettingsPanelHost,
} from '@agimon-ai/po-web-dashboard/views';
import { Link, useNavigate } from '@tanstack/react-router';
import { useStore } from '@tanstack/react-store';
import { useEffect, useState } from 'react';

/**
 * Settings at /settings/<section>. Keep Appearance: it is where the person switches template, so a
 * template without it leaves them stuck in it (they can still edit `web.template` in config.yaml).
 */
export function MySettings() {
  useWebPluginRegistry();
  const { section, workspaceId } = useDashboardRoute();
  const navigate = useNavigate();
  const activeId = useStore(sessionsStore, (state) => state.activeId);
  const [loadError, setLoadError] = useState<string>();
  const [repositoryReady, setRepositoryReady] = useState(false);
  const [templateTarget, setTemplateTarget] = useDashboardState('settings/template-target', 'global');
  const current = settingsSection(section);
  const workspace = current?.workspace ?? (section?.startsWith('repository-') ? 'repository' : 'general');

  // An unknown section may belong to a plugin that has not loaded yet; fall back once plugins are in.
  useEffect(() => {
    if (current) return;
    if (workspace === 'repository' && !repositoryReady) return;
    let cancelled = false;
    void refreshWebPluginCompositions()
      .then(() => {
        if (cancelled || settingsSection(section)) return;
        void navigate({
          to: '/settings/$section',
          params: { section: DEFAULT_SETTINGS_SECTION },
          search: { workspace: workspaceId },
          replace: true,
        });
      })
      .catch((error: unknown) => {
        if (!cancelled) setLoadError(error instanceof Error ? error.message : String(error));
      });
    return () => {
      cancelled = true;
    };
  }, [current, section, navigate, workspace, workspaceId, repositoryReady]);

  return (
    <div data-po-region="settings" className="flex h-full min-h-0 min-w-0 flex-col overflow-hidden bg-po-bg">
      <header className="flex h-14 shrink-0 items-center gap-3 border-b border-po-border px-4">
        <h1 className="flex-1 text-xl font-semibold text-po-hi">Settings</h1>
        <Button asChild variant="ghost" size="sm">
          <Link
            to="/settings/$section"
            params={{ section: DEFAULT_SETTINGS_SECTION }}
            search={{ workspace: workspaceId }}
          >
            General
          </Link>
        </Button>
        <Button asChild variant="ghost" size="sm">
          <Link
            to="/settings/$section"
            params={{ section: DEFAULT_REPOSITORY_SETTINGS_SECTION }}
            search={{ workspace: workspaceId }}
          >
            Workspaces
          </Link>
        </Button>
        <Button asChild variant="outline" size="sm">
          {activeId !== null ? (
            <Link to="/session/$sessionId" params={{ sessionId: activeId }}>
              Back to session
            </Link>
          ) : (
            <Link to="/">Back</Link>
          )}
        </Button>
      </header>
      <main className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
        {workspace === 'repository' ? (
          <RepositoryWorkspace
            key={workspaceId ?? 'remembered-workspace'}
            current={current ?? { id: section ?? '', label: '', detail: '', workspace: 'repository' }}
            initialRepositoryId={workspaceId}
            onRepositoryChange={(nextWorkspaceId) => {
              void navigate({
                to: '/settings/$section',
                params: { section: current?.id ?? section ?? DEFAULT_REPOSITORY_SETTINGS_SECTION },
                search: { workspace: nextWorkspaceId },
                replace: true,
              });
            }}
            onReady={setRepositoryReady}
          />
        ) : (
          <div className="flex min-h-0 flex-1 flex-col lg:flex-row">
            <SettingsMenu active={current?.id} workspace="general" repositoryId={workspaceId} />
            <section className="min-w-0 flex-1 overflow-y-auto px-6 py-8">
              <div className="mx-auto flex w-full max-w-5xl flex-col gap-8">
                {!current && loadError ? <p role="alert">{loadError}</p> : null}
                {current?.id === 'providers' ? <ProviderSettings /> : null}
                {current?.id === 'devices' ? <ClientDevices /> : null}
                {current?.id === 'appearance' ? (
                  <AppearanceSettings templateTarget={templateTarget} onTemplateTargetChange={setTemplateTarget} />
                ) : null}
                {current?.id === 'notifications' ? <NotificationSettings /> : null}
                {current?.id === 'images' ? <ImageSettings /> : null}
                {current?.id === 'presets' ? <PresetSettings /> : null}
                {current?.id === 'account' ? <AccountSettings /> : null}
                {current?.contribution === undefined ? null : (
                  <ContributedSettings section={current.contribution} scope="host" />
                )}
                {current?.panel === undefined ? null : <SettingsPanelHost panel={current.panel} />}
              </div>
            </section>
          </div>
        )}
      </main>
    </div>
  );
}
```
