File size: 12,049 Bytes
fb43301
af1bee9
 
 
fb43301
af1bee9
 
 
 
 
fb43301
 
 
af1bee9
0d811c3
dbd6aed
fb43301
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1de224d
 
af1bee9
 
 
 
 
 
ea59f21
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea59f21
af1bee9
 
 
 
 
ea59f21
153376e
af1bee9
 
 
 
 
 
 
 
 
 
1de224d
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d811c3
dbd6aed
af1bee9
 
 
 
 
 
0d811c3
 
 
 
 
 
 
 
 
 
dbd6aed
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import './shell.css';
import { Menu, Tooltip, useMantineColorScheme } from '@mantine/core';
import {
  IconAlertTriangle, IconBug, IconCheck, IconDeviceDesktop, IconFileReport, IconHandStop, IconHome, IconListCheck, IconLogout, IconMessageCircle, IconMoon,
  IconPlayerPlay, IconPlug, IconRobot, IconServer, IconSettings, IconSun, IconActivity } from '@/components/icons';
import type { ReactNode } from 'react';
import { NavLink as RouterLink, useLocation } from 'react-router-dom';
import type { Schemas } from '../../api/client';
import { useBrand, useHealth, useKill, useRuns } from '../../api/hooks';
import { useAuth } from '../../auth/AuthContext';
import { desktop } from '../../domain/desktop';
import { areaTone } from '../../domain/agents';
import { runTitle } from '../../domain/runName';
import { EnvSwitcher, envKind, useChosenEnv } from './EnvSwitcher';
import { setCursorEffects, useCursorEffects } from './CursorFx';
import { setSimpleMode, useSimpleMode } from './simpleMode';
import { isWaiting, useWaitsOnMe } from '../../domain/waiting';

type RunSummary = Schemas['RunSummary'];
export interface NavItem { to: string; label: string; icon: ReactNode; match?: (p: string) => boolean; admin?: boolean }
const ICON = { size: 16, stroke: 1.7 };

export const MAIN: NavItem[] = [
  { to: '/', label: 'Home', icon: <IconHome {...ICON} />, match: (p) => p === '/' },
  { to: '/runs', label: 'Test runs', icon: <IconPlayerPlay {...ICON} />, match: (p) => p === '/runs' || p.startsWith('/runs/') || p === '/schedules' },
  { to: '/assistant', label: 'Ask', icon: <IconMessageCircle {...ICON} /> },
];
export const LIBRARY: NavItem[] = [
  { to: '/scenarios', label: 'Scenarios', icon: <IconListCheck {...ICON} /> },
  { to: '/tickets', label: 'Defects', icon: <IconBug {...ICON} /> },
  { to: '/reports', label: 'Reports', icon: <IconFileReport {...ICON} /> },
];
export const SETUP: NavItem[] = [
  { to: '/pods', label: 'Test environments', icon: <IconServer {...ICON} /> },
];
export const INTEGRATIONS: NavItem = { to: '/integrations', label: 'Integrations', icon: <IconPlug {...ICON} /> };
/** Oracle AI Agent Studio: the Fusion workflow that drives test cycles (OAuth clients, cycles, callbacks, release watch). */
export const AGENT_STUDIO: NavItem = { to: '/agent-studio', label: 'Agent Studio', icon: <IconRobot {...ICON} /> };
/** How the AI models behave: calls, failures, latency, tokens, evaluations and the LangSmith export. */
export const AI_MONITORING: NavItem = { to: '/ai-monitoring', label: 'AI monitoring', icon: <IconActivity {...ICON} /> };
export const SETTINGS: NavItem = { to: '/admin', label: 'Settings', icon: <IconSettings {...ICON} />,
  match: (p) => ['/admin', '/agents', '/heal', '/scripts', '/learner', '/audit'].some((x) => p === x || p.startsWith(`${x}/`)) };

/** Where "New test run" links go: they open the Start sheet (`/runs/new` redirects there). */
export const NEW_RUN_PATH = '/runs/new';

export const initials = (name?: string) => (name ?? 'Astra').split(/\s+/).slice(0, 2).map((w) => w[0]?.toUpperCase() ?? '').join('') || 'TC';

function NavLink({ item, badge, onNavigate }: { item: NavItem; badge?: number; onNavigate?: () => void }) {
  const loc = useLocation();
  const active = item.match ? item.match(loc.pathname) : loc.pathname === item.to || loc.pathname.startsWith(`${item.to}/`);
  return (
    <RouterLink to={item.to} className="fpt-nav-item" data-active={active} aria-current={active ? 'page' : undefined} onClick={onNavigate}>

      {item.icon}<span className="fpt-nav-label">{item.label}</span>

      {!!badge && <span className="fpt-nav-badge" title={`${badge} waiting for you`}>{badge}<span className="fpt-sr-only">, waiting for you</span></span>}

    </RouterLink>
  );
}

type Group = { key: string; title: string; runs: RunSummary[] };


/** The latest test runs, newest first: a square in the area's colour and the run's readable name. */
function RecentRuns({ items, onNavigate }: { items: RunSummary[]; onNavigate?: () => void }) {
  const loc = useLocation();
  const latest = [...items].sort((a, b) => (a.created_at < b.created_at ? 1 : -1)).slice(0, 4);
  if (!latest.length) return null;
  return (
    <section className="pw-sb-recent" aria-labelledby="pw-sb-recent-h">

      <h6 id="pw-sb-recent-h">Recent test runs</h6>

      <ul>

        {latest.map((r) => {

          const to = `/runs/${r.run_id}`;

          const active = loc.pathname === to || loc.pathname.startsWith(`${to}/`);

          return (

            <li key={r.run_id}>

              <RouterLink to={to} className="pw-sb-recent-item" aria-current={active ? 'page' : undefined} onClick={onNavigate} title={runTitle(r)}>

                <span className="pw-icon-sq" data-tone={areaTone(r.modules[0])} aria-hidden />

                <span className="pw-sb-recent-label">{runTitle(r)}</span>

              </RouterLink>

            </li>

          );

        })}

      </ul>

    </section>
  );
}

/** Needs you (all of them) first, then Running, then Recent to fill up to `max` rows. */
export function groupRuns(items: RunSummary[], max = 12, mine: (r: RunSummary) => boolean = isWaiting): Group[] {
  const needs = items.filter(mine);
  const running = items.filter((r) => !needs.includes(r) && ['queued', 'running'].includes(r.status));
  const recent = items.filter((r) => !needs.includes(r) && !running.includes(r))
    .sort((a, b) => (a.created_at < b.created_at ? 1 : -1));
  let room = Math.max(0, max - needs.length);
  const run2 = running.slice(0, room); room -= run2.length;
  const rec2 = recent.slice(0, room);
  return [{ key: 'needs', title: 'Waiting for you', runs: needs }, { key: 'running', title: 'Running', runs: run2 }, { key: 'recent', title: 'Recent', runs: rec2 }]
    .filter((g) => g.runs.length);
}

const weekCount = (items: RunSummary[]) => items.filter((r) => Date.now() - new Date(r.created_at).getTime() < 7 * 86_400_000).length;

/** The sidebar: brand, the environment switcher (the honesty cue), one level of navigation with two small group labels,

 * the emergency-stop flag, and only the account row at the bottom. */
export function AppSidebar({ onNavigate }: { onNavigate?: () => void }) {
  const { can } = useAuth();
  const health = useHealth();
  const env = useChosenEnv().pod;
  const kill = useKill();
  const runs = useRuns(40, 0);
  const brand = useBrand();
  const mine = useWaitsOnMe();
  const waiting = (runs.data?.items ?? []).filter(mine).length;
  const name = brand.data?.product_name ?? 'Astra';

  return (
    <div className="fpt-sb">

      <div className="fpt-sb-top">

        <div className="fpt-sb-brand" data-testid="brand">

          <img className="astra-logo" src="/astra-logo.png" alt="" height={30} />

          <span className="fpt-sb-brand-name" title={name}><b className="fpt-sb-name astra-wordmark">{name}</b>{brand.data?.org_name ? <small>{brand.data.org_name}</small> : null}</span>

        </div>

        <EnvSwitcher />

        <nav className="fpt-sb-nav" aria-label="Pages">

          <h6>Workspace</h6>

          {MAIN.map((it) => <NavLink key={it.to} item={it} onNavigate={onNavigate} badge={it.to === '/runs' ? waiting : undefined} />)}

          <h6>Library</h6>

          {LIBRARY.map((it) => <NavLink key={it.to} item={it} onNavigate={onNavigate} />)}

          <h6>Setup</h6>

          {SETUP.map((it) => <NavLink key={it.to} item={it} onNavigate={onNavigate} />)}

          {can('admin') && <NavLink item={AGENT_STUDIO} onNavigate={onNavigate} />}

          {can('admin') && <NavLink item={AI_MONITORING} onNavigate={onNavigate} />}

          {can('admin') && <NavLink item={INTEGRATIONS} onNavigate={onNavigate} />}

          {can('admin') && <NavLink item={SETTINGS} onNavigate={onNavigate} />}

        </nav>

        <RecentRuns items={runs.data?.items ?? []} onNavigate={onNavigate} />

      </div>



      <div className="fpt-sb-foot">

        {(runs.data?.items.length ?? 0) > 0 && (

          <div className="pw-sb-usage" data-testid="sb-usage">

            <b>{weekCount(runs.data?.items ?? [])} test {weekCount(runs.data?.items ?? []) === 1 ? 'run' : 'runs'}</b>

            <span>started in the last 7 days{waiting ? `, ${waiting} waiting for you` : ''}</span>

          </div>

        )}

        {kill.data?.engaged && (

          <div className="fpt-kill" data-testid="kill-indicator" role="status"><IconHandStop size={16} aria-hidden />Emergency stop is on</div>

        )}

        {health.data && !health.data.mock_up && envKind(env?.kind) === 'mock' && !!env && (

          <Tooltip label="The practice app is not answering"><div className="fpt-warnrow" aria-label="practice app down"><IconAlertTriangle size={16} aria-hidden />Practice app not answering</div></Tooltip>

        )}

        <AccountMenu />

      </div>

    </div>
  );
}

/** The account row's menu: your account, light or dark, sign out. `compact`: the avatar alone (the icon rail). */
export function AccountMenu({ compact = false }: { compact?: boolean }) {
  const { user, logout } = useAuth();
  const { colorScheme, setColorScheme } = useMantineColorScheme();
  const whoami = `${user?.username} (${user?.role})`;
  const scheme = [
    { v: 'auto', label: 'Match the system', aria: 'Match the system theme', icon: <IconDeviceDesktop size={15} /> },
    { v: 'light', label: 'Light', aria: 'Switch to light theme', icon: <IconSun size={15} /> },
    { v: 'dark', label: 'Dark', aria: 'Switch to dark theme', icon: <IconMoon size={15} /> },
  ] as const;
  return (
        <Menu position={compact ? 'right-end' : 'top-start'} width={248} withinPortal>

          <Menu.Target>

            <button type="button" className="fpt-me" data-compact={compact || undefined} aria-label={compact ? `Account: ${whoami}` : undefined}>

              <span className="fpt-avatar" aria-hidden>{initials(user?.username)}</span>

              <span className="fpt-me-text" hidden={compact}>

                <b aria-hidden>{user?.username}</b><small aria-hidden>{user?.role}</small>

                <span className="fpt-sr-only" data-testid="whoami">{whoami}</span>

              </span>

            </button>

          </Menu.Target>

          <Menu.Dropdown>

            <Menu.Label>{whoami}</Menu.Label>

            <Menu.Item component={RouterLink} to="/account" data-testid="menu-account">Your account</Menu.Item>

            <Menu.Divider />

            <Menu.Label>Appearance</Menu.Label>

            {scheme.map((s) => (

              <Menu.Item key={s.v} leftSection={s.icon} aria-label={s.aria} onClick={() => setColorScheme(s.v)} rightSection={colorScheme === s.v ? <IconCheck size={14} aria-label="chosen" /> : undefined}>{s.label}</Menu.Item>

            ))}

            <Menu.Divider />

            <CursorMenuItem />

            <SimpleMenuItem />

            {desktop() && <Menu.Item onClick={() => desktop()?.openSettings()}>Desktop settings</Menu.Item>}

            <Menu.Item leftSection={<IconLogout size={15} />} aria-label="Sign out" onClick={() => void logout()}>Sign out</Menu.Item>

          </Menu.Dropdown>

        </Menu>
  );
}

/** The mouse effects (follower ring, magnetic buttons) on or off, for this browser. */
function CursorMenuItem() {
  const on = useCursorEffects();
  return (
    <Menu.Item onClick={() => setCursorEffects(!on)} rightSection={on ? <IconCheck size={14} aria-hidden /> : null} aria-label={`Cursor effects: ${on ? 'on' : 'off'}`}>

      Cursor effects

    </Menu.Item>
  );
}

/** Simple mode on or off, for this browser: the test run page shows only the current step, the rest folded away. */
function SimpleMenuItem() {
  const on = useSimpleMode();
  return (
    <Menu.Item onClick={() => setSimpleMode(!on)} rightSection={on ? <IconCheck size={14} aria-hidden /> : null} aria-label={`Simple mode: ${on ? 'on' : 'off'}`}>

      Simple mode

    </Menu.Item>
  );
}