chore: consolidate new foundation and archive v1 (#1495)
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { loginAs, ADMIN_USER, REQUIRE_SEEDED_AUTH, TEST_USER } from './helpers/auth.js';
|
||||
|
||||
test.describe('Admin page — admin user', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await loginAs(page, ADMIN_USER.email, ADMIN_USER.password);
|
||||
const url = page.url();
|
||||
test.skip(
|
||||
!REQUIRE_SEEDED_AUTH && !url.includes('/chat'),
|
||||
'No seeded admin user — skipping admin tests',
|
||||
);
|
||||
});
|
||||
|
||||
test('admin page loads with the Admin Panel heading', async ({ page }) => {
|
||||
await page.goto('/admin');
|
||||
await expect(page.getByRole('heading', { name: /admin panel/i })).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
});
|
||||
|
||||
test('shows User Management and System Health tabs', async ({ page }) => {
|
||||
await page.goto('/admin');
|
||||
await expect(page.getByRole('button', { name: /user management/i })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: /system health/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('User Management tab is active by default', async ({ page }) => {
|
||||
await page.goto('/admin');
|
||||
// The users tab shows a "+ New User" button
|
||||
await expect(page.getByRole('button', { name: /new user/i })).toBeVisible({ timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('clicking System Health tab switches to health view', async ({ page }) => {
|
||||
await page.goto('/admin');
|
||||
await page.getByRole('button', { name: /system health/i }).click();
|
||||
// Health cards or loading indicator should appear
|
||||
const loadingOrCard = page
|
||||
.getByText(/loading health/i)
|
||||
.or(page.getByText(/database/i))
|
||||
.first();
|
||||
await expect(loadingOrCard).toBeVisible({ timeout: 10_000 });
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Admin page — non-admin user', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await loginAs(page, TEST_USER.email, TEST_USER.password);
|
||||
const url = page.url();
|
||||
test.skip(
|
||||
!REQUIRE_SEEDED_AUTH && !url.includes('/chat'),
|
||||
'No seeded test user — skipping non-admin tests',
|
||||
);
|
||||
});
|
||||
|
||||
test('non-admin visiting /admin never sees the admin panel', async ({ page }) => {
|
||||
await page.goto('/admin');
|
||||
// Wait for the app shell to render (redirect and access-denied views both
|
||||
// keep the sidebar), then assert the panel itself is absent. globalSetup
|
||||
// seeds TEST_USER with role 'member', so this is a real authorization
|
||||
// assertion, not environment-dependent.
|
||||
await expect(page.getByRole('img', { name: /mosaic logo/i })).toBeVisible({ timeout: 10_000 });
|
||||
await expect(page.getByRole('heading', { name: /admin panel/i })).not.toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { REQUIRE_SEEDED_AUTH, TEST_USER } from './helpers/auth.js';
|
||||
|
||||
// ── Login page ────────────────────────────────────────────────────────────────
|
||||
|
||||
test.describe('Login page', () => {
|
||||
test('loads and shows the sign-in heading', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await expect(page).toHaveTitle(/mosaic/i);
|
||||
await expect(page.getByRole('heading', { name: /sign in/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows email and password fields', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await expect(page.getByLabel('Email')).toBeVisible();
|
||||
await expect(page.getByLabel('Password')).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows submit button', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await expect(page.getByRole('button', { name: /sign in/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows link to registration page', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
const signUpLink = page.getByRole('link', { name: /sign up/i });
|
||||
await expect(signUpLink).toBeVisible();
|
||||
await signUpLink.click();
|
||||
await expect(page).toHaveURL(/\/register/);
|
||||
});
|
||||
|
||||
test('shows an error alert for invalid credentials', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await page.getByLabel('Email').fill('[email protected]');
|
||||
await page.getByLabel('Password').fill('wrongpassword');
|
||||
await page.getByRole('button', { name: /sign in/i }).click();
|
||||
// The error banner should appear; it has role="alert"
|
||||
await expect(page.getByRole('alert')).toBeVisible({ timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('email field requires valid format (HTML5 validation)', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
// Fill a non-email value — browser prevents submission
|
||||
await page.getByLabel('Email').fill('notanemail');
|
||||
await page.getByLabel('Password').fill('somepass');
|
||||
await page.getByRole('button', { name: /sign in/i }).click();
|
||||
// Still on the login page
|
||||
await expect(page).toHaveURL(/\/login/);
|
||||
});
|
||||
|
||||
test('redirects to /chat after successful login', async ({ page }) => {
|
||||
// Only meaningful with known-good credentials; against a live environment
|
||||
// this would just probe someone else's user table.
|
||||
test.skip(!REQUIRE_SEEDED_AUTH, 'needs seeded credentials (E2E_REQUIRE_SEEDED_AUTH=1)');
|
||||
await page.goto('/login');
|
||||
await page.getByLabel('Email').fill(TEST_USER.email);
|
||||
await page.getByLabel('Password').fill(TEST_USER.password);
|
||||
await page.getByRole('button', { name: /sign in/i }).click();
|
||||
await expect(page).toHaveURL(/\/chat/, { timeout: 10_000 });
|
||||
});
|
||||
});
|
||||
|
||||
// ── Registration page ─────────────────────────────────────────────────────────
|
||||
|
||||
test.describe('Registration page', () => {
|
||||
test('loads and shows the create account heading', async ({ page }) => {
|
||||
await page.goto('/register');
|
||||
await expect(page.getByRole('heading', { name: /create account/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows name, email and password fields', async ({ page }) => {
|
||||
await page.goto('/register');
|
||||
await expect(page.getByLabel('Name')).toBeVisible();
|
||||
await expect(page.getByLabel('Email')).toBeVisible();
|
||||
await expect(page.getByLabel('Password')).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows submit button', async ({ page }) => {
|
||||
await page.goto('/register');
|
||||
await expect(page.getByRole('button', { name: /create account/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows link to login page', async ({ page }) => {
|
||||
await page.goto('/register');
|
||||
const signInLink = page.getByRole('link', { name: /sign in/i });
|
||||
await expect(signInLink).toBeVisible();
|
||||
await signInLink.click();
|
||||
await expect(page).toHaveURL(/\/login/);
|
||||
});
|
||||
|
||||
test('name field is required — empty form stays on page', async ({ page }) => {
|
||||
await page.goto('/register');
|
||||
// Submit with nothing filled in — browser required validation blocks it
|
||||
await page.getByRole('button', { name: /create account/i }).click();
|
||||
await expect(page).toHaveURL(/\/register/);
|
||||
});
|
||||
|
||||
test('all required fields must be filled (HTML5 validation)', async ({ page }) => {
|
||||
await page.goto('/register');
|
||||
await page.getByLabel('Name').fill('Test User');
|
||||
// Do NOT fill email or password — still on page
|
||||
await page.getByRole('button', { name: /create account/i }).click();
|
||||
await expect(page).toHaveURL(/\/register/);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Root redirect ─────────────────────────────────────────────────────────────
|
||||
|
||||
test.describe('Root route', () => {
|
||||
test('visiting / redirects to /login or /chat', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
// Unauthenticated users should land on /login; authenticated on /chat
|
||||
await expect(page).toHaveURL(/\/(login|chat)/, { timeout: 10_000 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { loginAs, REQUIRE_SEEDED_AUTH, TEST_USER } from './helpers/auth.js';
|
||||
|
||||
test.describe('Chat page', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await loginAs(page, TEST_USER.email, TEST_USER.password);
|
||||
// If login failed (no seeded user in env) we may be on /login — skip
|
||||
const url = page.url();
|
||||
test.skip(
|
||||
!REQUIRE_SEEDED_AUTH && !url.includes('/chat'),
|
||||
'No seeded test user — skipping authenticated tests',
|
||||
);
|
||||
});
|
||||
|
||||
test('chat page loads and shows the conversation area', async ({ page }) => {
|
||||
await page.goto('/chat');
|
||||
await expect(page.getByRole('heading', { level: 1, name: /chat/i })).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
await expect(page.getByRole('log', { name: /conversation/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('message composer input is visible', async ({ page }) => {
|
||||
await page.goto('/chat');
|
||||
await expect(page.getByLabel('Message')).toBeVisible({ timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('command panel lists /new and exposes the run controls', async ({ page }) => {
|
||||
await page.goto('/chat');
|
||||
// Conversations are command-driven: /new starts one via the commands panel.
|
||||
const commandList = page.getByRole('list', { name: /available commands/i });
|
||||
await expect(commandList).toBeVisible({ timeout: 10_000 });
|
||||
await expect(commandList.getByText('/new', { exact: true })).toBeVisible();
|
||||
await expect(page.getByLabel('Command name')).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: /run command/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('sidebar navigation is present on chat page', async ({ page }) => {
|
||||
await page.goto('/chat');
|
||||
// The app-shell sidebar should be visible
|
||||
await expect(page.getByRole('link', { name: /chat/i }).first()).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { FullConfig } from '@playwright/test';
|
||||
import { ADMIN_USER, REQUIRE_SEEDED_AUTH, TEST_USER } from './helpers/auth.js';
|
||||
|
||||
/**
|
||||
* Seed the E2E users through the gateway's real APIs (#1445, P6).
|
||||
*
|
||||
* On a fresh database (CI boots the gateway on the embedded PGlite path):
|
||||
* 1. POST /api/bootstrap/setup creates ADMIN_USER as the first admin.
|
||||
* 2. The admin signs in and creates TEST_USER via the better-auth admin API.
|
||||
*
|
||||
* Against an environment that already has users (needsSetup=false), seeding is
|
||||
* skipped entirely: the specs keep their own skip-when-login-fails guards, so
|
||||
* a live environment stays usable as a test target without mutation. Under
|
||||
* E2E_REQUIRE_SEEDED_AUTH=1 (CI) that state is instead a hard failure and the
|
||||
* guards are disabled — see helpers/auth.ts.
|
||||
*
|
||||
* On a fresh database, any seeding failure throws and fails the whole run: an
|
||||
* E2E gate whose authenticated suites silently skip would pass while proving
|
||||
* nothing.
|
||||
*/
|
||||
export default async function globalSetup(config: FullConfig): Promise<void> {
|
||||
const baseURL = config.projects[0]?.use?.baseURL ?? 'http://localhost:14242';
|
||||
|
||||
const statusRes = await fetch(`${baseURL}/api/bootstrap/status`);
|
||||
if (!statusRes.ok) {
|
||||
throw new Error(`GET /api/bootstrap/status returned ${statusRes.status} — is the gateway up?`);
|
||||
}
|
||||
const status = (await statusRes.json()) as { needsSetup: boolean };
|
||||
if (!status.needsSetup) {
|
||||
if (REQUIRE_SEEDED_AUTH) {
|
||||
// CI boots the gateway on a fresh HOME-isolated database, so an
|
||||
// already-populated one means the isolation regressed — refuse to run
|
||||
// against unknown data rather than skip-and-pass.
|
||||
throw new Error(
|
||||
'E2E_REQUIRE_SEEDED_AUTH=1 but the database already has users — gateway HOME isolation regressed?',
|
||||
);
|
||||
}
|
||||
console.info('[e2e setup] users already exist; skipping seed');
|
||||
return;
|
||||
}
|
||||
|
||||
const setupRes = await fetch(`${baseURL}/api/bootstrap/setup`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: ADMIN_USER.name,
|
||||
email: ADMIN_USER.email,
|
||||
password: ADMIN_USER.password,
|
||||
}),
|
||||
});
|
||||
if (!setupRes.ok) {
|
||||
throw new Error(
|
||||
`POST /api/bootstrap/setup failed (${setupRes.status}): ${await setupRes.text()}`,
|
||||
);
|
||||
}
|
||||
console.info(`[e2e setup] bootstrap admin created: ${ADMIN_USER.email}`);
|
||||
|
||||
// better-auth's CSRF protection rejects requests without an Origin header
|
||||
// (403 MISSING_OR_NULL_ORIGIN), so the server-side fetches here send the
|
||||
// gateway's own origin — the same value a browser tab on the SPA would send.
|
||||
const authHeaders = { 'content-type': 'application/json', origin: baseURL };
|
||||
|
||||
const signInRes = await fetch(`${baseURL}/api/auth/sign-in/email`, {
|
||||
method: 'POST',
|
||||
headers: authHeaders,
|
||||
body: JSON.stringify({ email: ADMIN_USER.email, password: ADMIN_USER.password }),
|
||||
});
|
||||
if (!signInRes.ok) {
|
||||
throw new Error(`admin sign-in failed (${signInRes.status}): ${await signInRes.text()}`);
|
||||
}
|
||||
const cookies = signInRes.headers
|
||||
.getSetCookie()
|
||||
.map((cookie) => cookie.split(';', 1)[0])
|
||||
.join('; ');
|
||||
if (!cookies) {
|
||||
throw new Error('admin sign-in returned no session cookie');
|
||||
}
|
||||
|
||||
const createRes = await fetch(`${baseURL}/api/auth/admin/create-user`, {
|
||||
method: 'POST',
|
||||
headers: { ...authHeaders, cookie: cookies },
|
||||
body: JSON.stringify({
|
||||
name: TEST_USER.name,
|
||||
email: TEST_USER.email,
|
||||
password: TEST_USER.password,
|
||||
role: 'member',
|
||||
}),
|
||||
});
|
||||
if (!createRes.ok) {
|
||||
throw new Error(
|
||||
`POST /api/auth/admin/create-user failed (${createRes.status}): ${await createRes.text()}`,
|
||||
);
|
||||
}
|
||||
console.info(`[e2e setup] test user created: ${TEST_USER.email}`);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { Page } from '@playwright/test';
|
||||
|
||||
export const TEST_USER = {
|
||||
email: process.env['E2E_USER_EMAIL'] ?? '[email protected]',
|
||||
password: process.env['E2E_USER_PASSWORD'] ?? 'password123',
|
||||
name: 'E2E Test User',
|
||||
};
|
||||
|
||||
export const ADMIN_USER = {
|
||||
email: process.env['E2E_ADMIN_EMAIL'] ?? '[email protected]',
|
||||
password: process.env['E2E_ADMIN_PASSWORD'] ?? 'adminpass123',
|
||||
name: 'E2E Admin User',
|
||||
};
|
||||
|
||||
/**
|
||||
* Set when the database was seeded by global-setup (CI sets it in the
|
||||
* publish.yml e2e step). Seeded credentials MUST work, so login failures are
|
||||
* hard failures and the skip-when-login-fails guards are disabled — otherwise
|
||||
* a login regression would skip every authenticated suite and the gate would
|
||||
* pass while proving nothing. Unset (a live environment used as a test
|
||||
* target), the guards stay on and unseeded credentials skip their suites.
|
||||
*/
|
||||
export const REQUIRE_SEEDED_AUTH = process.env['E2E_REQUIRE_SEEDED_AUTH'] === '1';
|
||||
|
||||
/**
|
||||
* Fill the login form and submit, then wait for the post-login redirect to
|
||||
* /chat. Under REQUIRE_SEEDED_AUTH a missed redirect throws (failing the
|
||||
* test). Otherwise the timeout is swallowed: the page stays on /login and the
|
||||
* callers' `test.skip(...)` guards see that. Without this wait, every guard
|
||||
* read page.url() before the redirect happened and skipped its suite even
|
||||
* when login succeeded (#1445).
|
||||
*/
|
||||
export async function loginAs(page: Page, email: string, password: string): Promise<void> {
|
||||
await page.goto('/login');
|
||||
await page.getByLabel('Email').fill(email);
|
||||
await page.getByLabel('Password').fill(password);
|
||||
await page.getByRole('button', { name: /sign in/i }).click();
|
||||
const redirect = page.waitForURL(/\/chat/, { timeout: 10_000 });
|
||||
await (REQUIRE_SEEDED_AUTH ? redirect : redirect.catch(() => {}));
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { loginAs, REQUIRE_SEEDED_AUTH, TEST_USER } from './helpers/auth.js';
|
||||
|
||||
test.describe('Sidebar navigation', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await loginAs(page, TEST_USER.email, TEST_USER.password);
|
||||
const url = page.url();
|
||||
test.skip(
|
||||
!REQUIRE_SEEDED_AUTH && !url.includes('/chat'),
|
||||
'No seeded test user — skipping authenticated tests',
|
||||
);
|
||||
});
|
||||
|
||||
test('sidebar shows the Mosaic brand', async ({ page }) => {
|
||||
await page.goto('/chat');
|
||||
// The brand block is a logo image plus "Mosaic / Mission Control" text,
|
||||
// not a link.
|
||||
await expect(page.getByRole('img', { name: /mosaic logo/i })).toBeVisible();
|
||||
await expect(page.getByText('Mission Control')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Chat nav link navigates to /chat', async ({ page }) => {
|
||||
await page.goto('/settings');
|
||||
await page
|
||||
.getByRole('link', { name: /^chat$/i })
|
||||
.first()
|
||||
.click();
|
||||
await expect(page).toHaveURL(/\/chat/);
|
||||
});
|
||||
|
||||
test('Projects nav link navigates to /projects', async ({ page }) => {
|
||||
await page.goto('/chat');
|
||||
await page
|
||||
.getByRole('link', { name: /projects/i })
|
||||
.first()
|
||||
.click();
|
||||
await expect(page).toHaveURL(/\/projects/);
|
||||
});
|
||||
|
||||
test('Settings nav link navigates to /settings', async ({ page }) => {
|
||||
await page.goto('/chat');
|
||||
await page
|
||||
.getByRole('link', { name: /settings/i })
|
||||
.first()
|
||||
.click();
|
||||
await expect(page).toHaveURL(/\/settings/);
|
||||
});
|
||||
|
||||
test('Tasks nav link navigates to /tasks', async ({ page }) => {
|
||||
await page.goto('/chat');
|
||||
await page.getByRole('link', { name: /tasks/i }).first().click();
|
||||
await expect(page).toHaveURL(/\/tasks/);
|
||||
});
|
||||
|
||||
test('active link is visually highlighted', async ({ page }) => {
|
||||
await page.goto('/chat');
|
||||
// The sidebar marks the active item with `font-medium` (plus an inline
|
||||
// primary-color style); inactive items get the hover class instead.
|
||||
const chatLink = page.getByRole('link', { name: /^chat$/i }).first();
|
||||
const projectsLink = page.getByRole('link', { name: /^projects$/i }).first();
|
||||
await expect(chatLink).toHaveClass(/font-medium/);
|
||||
await expect(projectsLink).not.toHaveClass(/font-medium/);
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Route transitions', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await loginAs(page, TEST_USER.email, TEST_USER.password);
|
||||
const url = page.url();
|
||||
test.skip(
|
||||
!REQUIRE_SEEDED_AUTH && !url.includes('/chat'),
|
||||
'No seeded test user — skipping authenticated tests',
|
||||
);
|
||||
});
|
||||
|
||||
test('navigating chat → projects → settings → chat works without errors', async ({ page }) => {
|
||||
await page.goto('/chat');
|
||||
await expect(page).toHaveURL(/\/chat/);
|
||||
|
||||
// level: 1 — empty-state h2s ("No projects yet") also match the loose
|
||||
// patterns, and a two-element match is a strict-mode violation.
|
||||
await page.goto('/projects');
|
||||
await expect(page.getByRole('heading', { level: 1, name: /projects/i })).toBeVisible();
|
||||
|
||||
await page.goto('/settings');
|
||||
await expect(page.getByRole('heading', { level: 1, name: /settings/i })).toBeVisible();
|
||||
|
||||
await page.goto('/chat');
|
||||
await expect(page).toHaveURL(/\/chat/);
|
||||
});
|
||||
|
||||
test('back-button navigation works between pages', async ({ page }) => {
|
||||
await page.goto('/chat');
|
||||
await page.goto('/projects');
|
||||
await page.goBack();
|
||||
await expect(page).toHaveURL(/\/chat/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { loginAs, REQUIRE_SEEDED_AUTH, TEST_USER } from './helpers/auth.js';
|
||||
|
||||
test.describe('Projects page', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await loginAs(page, TEST_USER.email, TEST_USER.password);
|
||||
const url = page.url();
|
||||
test.skip(
|
||||
!REQUIRE_SEEDED_AUTH && !url.includes('/chat'),
|
||||
'No seeded test user — skipping authenticated tests',
|
||||
);
|
||||
});
|
||||
|
||||
test('projects page loads with heading', async ({ page }) => {
|
||||
await page.goto('/projects');
|
||||
// level: 1 — the "No projects yet" empty-state h2 also matches /projects/i
|
||||
// and a two-element match is a strict-mode violation.
|
||||
await expect(page.getByRole('heading', { level: 1, name: /projects/i })).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
});
|
||||
|
||||
test('shows empty state or project cards when loaded', async ({ page }) => {
|
||||
await page.goto('/projects');
|
||||
// Wait for loading state to clear
|
||||
await expect(page.getByText(/loading projects/i)).not.toBeVisible({ timeout: 10_000 });
|
||||
|
||||
const cardsOrEmpty = page
|
||||
.locator('[class*="grid"]')
|
||||
.or(page.getByText(/no projects yet/i))
|
||||
.first();
|
||||
await expect(cardsOrEmpty).toBeVisible({ timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('sidebar navigation is present', async ({ page }) => {
|
||||
await page.goto('/projects');
|
||||
await expect(page.getByRole('link', { name: /projects/i }).first()).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { loginAs, REQUIRE_SEEDED_AUTH, TEST_USER } from './helpers/auth.js';
|
||||
|
||||
test.describe('Settings page', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await loginAs(page, TEST_USER.email, TEST_USER.password);
|
||||
const url = page.url();
|
||||
test.skip(
|
||||
!REQUIRE_SEEDED_AUTH && !url.includes('/chat'),
|
||||
'No seeded test user — skipping authenticated tests',
|
||||
);
|
||||
});
|
||||
|
||||
test('settings page loads with heading', async ({ page }) => {
|
||||
await page.goto('/settings');
|
||||
await expect(page.getByRole('heading', { name: /^settings$/i })).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
});
|
||||
|
||||
test('shows the four settings tabs', async ({ page }) => {
|
||||
await page.goto('/settings');
|
||||
await expect(page.getByRole('button', { name: /profile/i })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: /appearance/i })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: /notifications/i })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: /providers/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('profile tab is active by default', async ({ page }) => {
|
||||
await page.goto('/settings');
|
||||
await expect(page.getByRole('heading', { name: /^profile$/i })).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
});
|
||||
|
||||
test('clicking Appearance tab switches content', async ({ page }) => {
|
||||
await page.goto('/settings');
|
||||
await page.getByRole('button', { name: /appearance/i }).click();
|
||||
await expect(page.getByRole('heading', { name: /appearance/i })).toBeVisible({
|
||||
timeout: 5_000,
|
||||
});
|
||||
});
|
||||
|
||||
test('clicking Notifications tab switches content', async ({ page }) => {
|
||||
await page.goto('/settings');
|
||||
await page.getByRole('button', { name: /notifications/i }).click();
|
||||
await expect(page.getByRole('heading', { name: /notifications/i })).toBeVisible({
|
||||
timeout: 5_000,
|
||||
});
|
||||
});
|
||||
|
||||
test('clicking Providers tab switches content', async ({ page }) => {
|
||||
await page.goto('/settings');
|
||||
await page.getByRole('button', { name: /providers/i }).click();
|
||||
await expect(page.getByRole('heading', { name: /llm providers/i })).toBeVisible({
|
||||
timeout: 5_000,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Mosaic</title>
|
||||
<meta name="description" content="Mosaic Stack Dashboard" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Fira+Code:wght@400;500&display=swap"
|
||||
/>
|
||||
<script>
|
||||
// set data-theme before first paint so the stored theme never flashes
|
||||
(function () {
|
||||
try {
|
||||
var theme = window.localStorage.getItem('mosaic-theme') || 'dark';
|
||||
document.documentElement.setAttribute('data-theme', theme === 'light' ? 'light' : 'dark');
|
||||
} catch (error) {
|
||||
document.documentElement.setAttribute('data-theme', 'dark');
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"name": "@mosaicstack/web",
|
||||
"version": "0.0.2",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
"dev": "vite",
|
||||
"preview": "vite preview",
|
||||
"lint": "eslint src",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"test:e2e": "playwright test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@mosaicstack/design-tokens": "workspace:^",
|
||||
"@mosaicstack/types": "workspace:^",
|
||||
"better-auth": "^1.5.5",
|
||||
"clsx": "^2.1.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-router-dom": "^7.18.2",
|
||||
"socket.io-client": "^4.8.0",
|
||||
"tailwind-merge": "^3.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.58.2",
|
||||
"@tailwindcss/postcss": "^4.0.0",
|
||||
"@types/node": "^22.0.0",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^6.0.5",
|
||||
"jsdom": "^29.0.0",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "^5.8.0",
|
||||
"vite": "^8.2.1",
|
||||
"vitest": "^3.2.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Playwright E2E configuration for the Mosaic web SPA.
|
||||
*
|
||||
* Assumes the NestJS gateway is already running on http://localhost:14242 and
|
||||
* serving the built SPA bundle (WEB_DIST_DIR pointing at apps/web/dist) — the
|
||||
* same serving path production uses (Phase P5, #1444). Override the target
|
||||
* with PLAYWRIGHT_BASE_URL.
|
||||
*
|
||||
* global-setup seeds the E2E users through the real bootstrap and admin APIs
|
||||
* when the database is empty; against an already-populated environment it
|
||||
* seeds nothing.
|
||||
*
|
||||
* Run with: pnpm --filter @mosaicstack/web test:e2e
|
||||
*/
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
globalSetup: './e2e/global-setup.ts',
|
||||
fullyParallel: true,
|
||||
forbidOnly: !!process.env['CI'],
|
||||
retries: process.env['CI'] ? 2 : 0,
|
||||
workers: process.env['CI'] ? 1 : undefined,
|
||||
// CI needs the verdict in the step log; the html report is a local tool.
|
||||
reporter: process.env['CI'] ? 'list' : 'html',
|
||||
use: {
|
||||
baseURL: process.env['PLAYWRIGHT_BASE_URL'] ?? 'http://localhost:14242',
|
||||
trace: 'on-first-retry',
|
||||
screenshot: 'only-on-failure',
|
||||
},
|
||||
projects: [
|
||||
{
|
||||
name: 'chromium',
|
||||
use: { ...devices['Desktop Chrome'] },
|
||||
},
|
||||
],
|
||||
// Do NOT auto-start a server — tests assume the gateway is already running.
|
||||
// webServer is intentionally omitted so tests can run against a live env.
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
/** @type {import('postcss-load-config').Config} */
|
||||
const config = {
|
||||
plugins: {
|
||||
'@tailwindcss/postcss': {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1,45 @@
|
||||
import React from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { SsoProviderButtons } from './sso-provider-buttons.js';
|
||||
|
||||
describe('SsoProviderButtons', () => {
|
||||
it('renders OIDC sign-in buttons and SAML fallback links', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<SsoProviderButtons
|
||||
providers={[
|
||||
{
|
||||
id: 'workos',
|
||||
name: 'WorkOS',
|
||||
protocols: ['oidc'],
|
||||
configured: true,
|
||||
loginMode: 'oidc',
|
||||
callbackPath: '/api/auth/oauth2/callback/workos',
|
||||
teamSync: { enabled: true, claim: 'organization_id' },
|
||||
samlFallback: { configured: false, loginUrl: null },
|
||||
warnings: [],
|
||||
},
|
||||
{
|
||||
id: 'keycloak',
|
||||
name: 'Keycloak',
|
||||
protocols: ['oidc', 'saml'],
|
||||
configured: true,
|
||||
loginMode: 'saml',
|
||||
callbackPath: null,
|
||||
teamSync: { enabled: true, claim: 'groups' },
|
||||
samlFallback: {
|
||||
configured: true,
|
||||
loginUrl: 'https://sso.example.com/realms/mosaic/protocol/saml',
|
||||
},
|
||||
warnings: [],
|
||||
},
|
||||
]}
|
||||
onOidcSignIn={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain('Continue with WorkOS');
|
||||
expect(html).toContain('Continue with Keycloak (SAML)');
|
||||
expect(html).toContain('https://sso.example.com/realms/mosaic/protocol/saml');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import React from 'react';
|
||||
import type { SsoProviderDiscovery } from '@/lib/sso';
|
||||
|
||||
interface SsoProviderButtonsProps {
|
||||
providers: SsoProviderDiscovery[];
|
||||
loadingProviderId?: string | null;
|
||||
onOidcSignIn: (providerId: SsoProviderDiscovery['id']) => void;
|
||||
}
|
||||
|
||||
export function SsoProviderButtons({
|
||||
providers,
|
||||
loadingProviderId = null,
|
||||
onOidcSignIn,
|
||||
}: SsoProviderButtonsProps): React.ReactElement | null {
|
||||
const visibleProviders = providers.filter((provider) => provider.configured);
|
||||
|
||||
if (visibleProviders.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-6 space-y-3 border-t border-surface-border pt-6">
|
||||
<p className="text-sm font-medium text-text-secondary">Single sign-on</p>
|
||||
<div className="space-y-3">
|
||||
{visibleProviders.map((provider) => {
|
||||
if (provider.loginMode === 'saml' && provider.samlFallback.loginUrl) {
|
||||
return (
|
||||
<a
|
||||
key={provider.id}
|
||||
href={provider.samlFallback.loginUrl}
|
||||
className="flex w-full items-center justify-center rounded-lg border border-surface-border bg-surface-elevated px-4 py-2.5 text-sm font-medium text-text-primary transition-colors hover:border-accent/50 hover:text-accent"
|
||||
>
|
||||
Continue with {provider.name} (SAML)
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
key={provider.id}
|
||||
type="button"
|
||||
disabled={loadingProviderId === provider.id}
|
||||
onClick={() => onOidcSignIn(provider.id)}
|
||||
className="flex w-full items-center justify-center rounded-lg border border-surface-border bg-surface-elevated px-4 py-2.5 text-sm font-medium text-text-primary transition-colors hover:border-accent/50 hover:text-accent disabled:opacity-50"
|
||||
>
|
||||
{loadingProviderId === provider.id
|
||||
? `Redirecting to ${provider.name}...`
|
||||
: `Continue with ${provider.name}`}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { ModelInfo } from '@/lib/types';
|
||||
|
||||
interface ChatInputProps {
|
||||
onSend: (content: string, options?: { modelId?: string }) => void;
|
||||
onStop?: () => void;
|
||||
isStreaming?: boolean;
|
||||
models: ModelInfo[];
|
||||
selectedModelId: string;
|
||||
onModelChange: (modelId: string) => void;
|
||||
onRequestEditLastMessage?: () => string | null;
|
||||
}
|
||||
|
||||
const MAX_HEIGHT = 220;
|
||||
|
||||
export function ChatInput({
|
||||
onSend,
|
||||
onStop,
|
||||
isStreaming = false,
|
||||
models,
|
||||
selectedModelId,
|
||||
onModelChange,
|
||||
onRequestEditLastMessage,
|
||||
}: ChatInputProps): React.ReactElement {
|
||||
const [value, setValue] = useState('');
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const selectedModel = useMemo(
|
||||
() => models.find((model) => model.id === selectedModelId) ?? models[0],
|
||||
[models, selectedModelId],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const textarea = textareaRef.current;
|
||||
if (!textarea) return;
|
||||
textarea.style.height = 'auto';
|
||||
textarea.style.height = `${Math.min(textarea.scrollHeight, MAX_HEIGHT)}px`;
|
||||
}, [value]);
|
||||
|
||||
useEffect(() => {
|
||||
function handleGlobalFocus(event: KeyboardEvent): void {
|
||||
if (
|
||||
(event.metaKey || event.ctrlKey) &&
|
||||
(event.key === '/' || event.key.toLowerCase() === 'k')
|
||||
) {
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (target?.closest('input, textarea, [contenteditable="true"]')) return;
|
||||
event.preventDefault();
|
||||
textareaRef.current?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', handleGlobalFocus);
|
||||
return () => document.removeEventListener('keydown', handleGlobalFocus);
|
||||
}, []);
|
||||
|
||||
function handleSubmit(event: React.FormEvent): void {
|
||||
event.preventDefault();
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed || isStreaming) return;
|
||||
onSend(trimmed, { modelId: selectedModel?.id });
|
||||
setValue('');
|
||||
textareaRef.current?.focus();
|
||||
}
|
||||
|
||||
function handleKeyDown(event: React.KeyboardEvent<HTMLTextAreaElement>): void {
|
||||
if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
|
||||
event.preventDefault();
|
||||
handleSubmit(event);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key === 'ArrowUp' && value.length === 0 && onRequestEditLastMessage) {
|
||||
const lastMessage = onRequestEditLastMessage();
|
||||
if (lastMessage) {
|
||||
event.preventDefault();
|
||||
setValue(lastMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const charCount = value.length;
|
||||
const tokenEstimate = Math.ceil(charCount / 4);
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
className="border-t px-4 py-4 backdrop-blur-xl md:px-6"
|
||||
style={{
|
||||
backgroundColor: 'color-mix(in srgb, var(--color-surface) 88%, transparent)',
|
||||
borderColor: 'var(--color-border)',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="rounded-[28px] border p-3 shadow-[var(--shadow-ms-lg)]"
|
||||
style={{
|
||||
backgroundColor: 'var(--color-surface-2)',
|
||||
borderColor: 'var(--color-border)',
|
||||
}}
|
||||
>
|
||||
<div className="mb-3 flex flex-wrap items-center gap-3">
|
||||
<label className="flex min-w-0 items-center gap-2 text-xs text-[var(--color-muted)]">
|
||||
<span className="uppercase tracking-[0.18em]">Model</span>
|
||||
<select
|
||||
value={selectedModelId}
|
||||
onChange={(event) => onModelChange(event.target.value)}
|
||||
className="rounded-full border px-3 py-1.5 text-sm outline-none"
|
||||
style={{
|
||||
backgroundColor: 'var(--color-surface)',
|
||||
borderColor: 'var(--color-border)',
|
||||
color: 'var(--color-text)',
|
||||
}}
|
||||
>
|
||||
{models.map((model) => (
|
||||
<option key={`${model.provider}:${model.id}`} value={model.id}>
|
||||
{model.name} · {model.provider}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<div className="ml-auto hidden items-center gap-2 text-xs text-[var(--color-muted)] md:flex">
|
||||
<span className="rounded-full border border-[var(--color-border)] px-2 py-1">
|
||||
⌘/ focus
|
||||
</span>
|
||||
<span className="rounded-full border border-[var(--color-border)] px-2 py-1">
|
||||
⌘K focus
|
||||
</span>
|
||||
<span className="rounded-full border border-[var(--color-border)] px-2 py-1">
|
||||
⌘↵ send
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-end gap-3">
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={value}
|
||||
onChange={(event) => setValue(event.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={isStreaming}
|
||||
rows={1}
|
||||
placeholder="Ask Mosaic something..."
|
||||
className="min-h-[3.25rem] flex-1 resize-none bg-transparent px-1 py-2 text-sm outline-none placeholder:text-[var(--color-muted)] disabled:opacity-60"
|
||||
style={{
|
||||
color: 'var(--color-text)',
|
||||
maxHeight: `${MAX_HEIGHT}px`,
|
||||
}}
|
||||
/>
|
||||
|
||||
{isStreaming ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onStop}
|
||||
className="inline-flex h-11 items-center gap-2 rounded-full border px-4 text-sm font-medium transition-colors"
|
||||
style={{
|
||||
backgroundColor: 'var(--color-surface)',
|
||||
borderColor: 'var(--color-border)',
|
||||
color: 'var(--color-text)',
|
||||
}}
|
||||
>
|
||||
<span className="inline-block h-2.5 w-2.5 rounded-sm bg-[var(--color-danger)]" />
|
||||
Stop
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!value.trim()}
|
||||
className="inline-flex h-11 items-center gap-2 rounded-full px-4 text-sm font-semibold text-white transition-all disabled:cursor-not-allowed disabled:opacity-45"
|
||||
style={{ backgroundColor: 'var(--color-ms-blue-500)' }}
|
||||
>
|
||||
<span>Send</span>
|
||||
<span aria-hidden="true">↗</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2 text-xs text-[var(--color-muted)]">
|
||||
<span>{charCount.toLocaleString()} chars</span>
|
||||
<span>·</span>
|
||||
<span>~{tokenEstimate.toLocaleString()} tokens</span>
|
||||
{selectedModel ? (
|
||||
<>
|
||||
<span>·</span>
|
||||
<span>{selectedModel.reasoning ? 'Reasoning on' : 'Fast response'}</span>
|
||||
</>
|
||||
) : null}
|
||||
<span className="ml-auto">Shift+Enter newline · Arrow ↑ edit last</span>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
import { cn } from '@/lib/cn';
|
||||
import type { Conversation } from '@/lib/types';
|
||||
|
||||
interface ConversationListProps {
|
||||
conversations: Conversation[];
|
||||
activeId: string | null;
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSelect: (id: string) => void;
|
||||
onNew: () => void;
|
||||
onRename: (id: string, title: string) => void;
|
||||
onDelete: (id: string) => void;
|
||||
onArchive: (id: string, archived: boolean) => void;
|
||||
}
|
||||
|
||||
interface ContextMenuState {
|
||||
conversationId: string;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
function formatRelativeTime(dateStr: string): string {
|
||||
const date = new Date(dateStr);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
const diffMinutes = Math.floor(diffMs / 60_000);
|
||||
const diffHours = Math.floor(diffMs / 3_600_000);
|
||||
const diffDays = Math.floor(diffMs / 86_400_000);
|
||||
|
||||
if (diffMinutes < 1) return 'Just now';
|
||||
if (diffMinutes < 60) return `${diffMinutes}m ago`;
|
||||
if (diffHours < 24) return `${diffHours}h ago`;
|
||||
if (diffDays === 1) return 'Yesterday';
|
||||
if (diffDays < 7) return `${diffDays}d ago`;
|
||||
return date.toLocaleDateString();
|
||||
}
|
||||
|
||||
export function ConversationList({
|
||||
conversations,
|
||||
activeId,
|
||||
isOpen,
|
||||
onClose,
|
||||
onSelect,
|
||||
onNew,
|
||||
onRename,
|
||||
onDelete,
|
||||
onArchive,
|
||||
}: ConversationListProps): React.ReactElement {
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [renamingId, setRenamingId] = useState<string | null>(null);
|
||||
const [renameValue, setRenameValue] = useState('');
|
||||
const [contextMenu, setContextMenu] = useState<ContextMenuState | null>(null);
|
||||
const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
const renameInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const activeConversations = conversations.filter((conversation) => !conversation.archived);
|
||||
const archivedConversations = conversations.filter((conversation) => conversation.archived);
|
||||
|
||||
const filteredActive = searchQuery
|
||||
? activeConversations.filter((conversation) =>
|
||||
(conversation.title ?? 'Untitled').toLowerCase().includes(searchQuery.toLowerCase()),
|
||||
)
|
||||
: activeConversations;
|
||||
|
||||
const filteredArchived = searchQuery
|
||||
? archivedConversations.filter((conversation) =>
|
||||
(conversation.title ?? 'Untitled').toLowerCase().includes(searchQuery.toLowerCase()),
|
||||
)
|
||||
: archivedConversations;
|
||||
|
||||
const handleContextMenu = useCallback((event: React.MouseEvent, conversationId: string) => {
|
||||
event.preventDefault();
|
||||
setContextMenu({ conversationId, x: event.clientX, y: event.clientY });
|
||||
setDeleteConfirmId(null);
|
||||
}, []);
|
||||
|
||||
const closeContextMenu = useCallback(() => {
|
||||
setContextMenu(null);
|
||||
setDeleteConfirmId(null);
|
||||
}, []);
|
||||
|
||||
const startRename = useCallback(
|
||||
(id: string, currentTitle: string | null) => {
|
||||
setRenamingId(id);
|
||||
setRenameValue(currentTitle ?? '');
|
||||
closeContextMenu();
|
||||
setTimeout(() => renameInputRef.current?.focus(), 0);
|
||||
},
|
||||
[closeContextMenu],
|
||||
);
|
||||
|
||||
const commitRename = useCallback(() => {
|
||||
if (renamingId) {
|
||||
const trimmed = renameValue.trim();
|
||||
onRename(renamingId, trimmed || 'Untitled');
|
||||
}
|
||||
setRenamingId(null);
|
||||
setRenameValue('');
|
||||
}, [onRename, renameValue, renamingId]);
|
||||
|
||||
const cancelRename = useCallback(() => {
|
||||
setRenamingId(null);
|
||||
setRenameValue('');
|
||||
}, []);
|
||||
|
||||
const handleRenameKeyDown = useCallback(
|
||||
(event: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (event.key === 'Enter') commitRename();
|
||||
if (event.key === 'Escape') cancelRename();
|
||||
},
|
||||
[cancelRename, commitRename],
|
||||
);
|
||||
|
||||
const confirmDelete = useCallback(
|
||||
(id: string) => {
|
||||
onDelete(id);
|
||||
setDeleteConfirmId(null);
|
||||
closeContextMenu();
|
||||
},
|
||||
[closeContextMenu, onDelete],
|
||||
);
|
||||
|
||||
const handleArchiveToggle = useCallback(
|
||||
(id: string, archived: boolean) => {
|
||||
onArchive(id, archived);
|
||||
closeContextMenu();
|
||||
},
|
||||
[closeContextMenu, onArchive],
|
||||
);
|
||||
|
||||
const contextConversation = contextMenu
|
||||
? conversations.find((conversation) => conversation.id === contextMenu.conversationId)
|
||||
: null;
|
||||
|
||||
function renderConversationItem(conversation: Conversation): React.ReactElement {
|
||||
const isActive = activeId === conversation.id;
|
||||
const isRenaming = renamingId === conversation.id;
|
||||
|
||||
return (
|
||||
<div key={conversation.id} className="group relative">
|
||||
{isRenaming ? (
|
||||
<div className="px-3 py-2">
|
||||
<input
|
||||
ref={renameInputRef}
|
||||
value={renameValue}
|
||||
onChange={(event) => setRenameValue(event.target.value)}
|
||||
onBlur={commitRename}
|
||||
onKeyDown={handleRenameKeyDown}
|
||||
className="w-full rounded-xl border px-3 py-2 text-sm outline-none"
|
||||
style={{
|
||||
borderColor: 'var(--color-ms-blue-500)',
|
||||
backgroundColor: 'var(--color-surface-2)',
|
||||
color: 'var(--color-text)',
|
||||
}}
|
||||
maxLength={255}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onSelect(conversation.id);
|
||||
if (window.innerWidth < 768) onClose();
|
||||
}}
|
||||
onDoubleClick={() => startRename(conversation.id, conversation.title)}
|
||||
onContextMenu={(event) => handleContextMenu(event, conversation.id)}
|
||||
className={cn(
|
||||
'w-full rounded-2xl px-3 py-2 text-left text-sm transition-colors',
|
||||
isActive ? 'shadow-[var(--shadow-ms-sm)]' : 'hover:bg-white/5',
|
||||
)}
|
||||
style={{
|
||||
backgroundColor: isActive
|
||||
? 'color-mix(in srgb, var(--color-ms-blue-500) 22%, transparent)'
|
||||
: 'transparent',
|
||||
color: isActive ? 'var(--color-text)' : 'var(--color-text-2)',
|
||||
}}
|
||||
>
|
||||
<span className="block truncate font-medium">{conversation.title ?? 'Untitled'}</span>
|
||||
<span className="block text-xs text-[var(--color-muted)]">
|
||||
{formatRelativeTime(conversation.updatedAt)}
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{isOpen ? (
|
||||
<button
|
||||
type="button"
|
||||
className="fixed inset-0 z-20 bg-black/45 md:hidden"
|
||||
onClick={onClose}
|
||||
aria-label="Close conversation sidebar"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{contextMenu ? (
|
||||
<div className="fixed inset-0 z-10" onClick={closeContextMenu} aria-hidden="true" />
|
||||
) : null}
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'fixed inset-y-0 left-0 z-30 flex h-full w-[18.5rem] flex-col border-r px-3 py-3 transition-transform duration-200 md:static md:z-auto',
|
||||
isOpen
|
||||
? 'translate-x-0'
|
||||
: '-translate-x-full md:w-0 md:min-w-0 md:overflow-hidden md:border-r-0 md:px-0 md:py-0',
|
||||
)}
|
||||
style={{
|
||||
backgroundColor: 'var(--color-surface)',
|
||||
borderColor: 'var(--color-border)',
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between px-1 pb-3">
|
||||
<h2 className="text-sm font-medium text-[var(--color-text-2)]">Conversations</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onNew}
|
||||
className="rounded-full px-3 py-1 text-xs transition-colors hover:bg-white/5"
|
||||
style={{ color: 'var(--color-ms-blue-400)' }}
|
||||
>
|
||||
+ New
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="pb-3">
|
||||
<input
|
||||
type="search"
|
||||
value={searchQuery}
|
||||
onChange={(event) => setSearchQuery(event.target.value)}
|
||||
placeholder="Search conversations…"
|
||||
className="w-full rounded-2xl border px-3 py-2 text-xs placeholder:text-[var(--color-muted)] focus:outline-none"
|
||||
style={{
|
||||
backgroundColor: 'var(--color-surface-2)',
|
||||
borderColor: 'var(--color-border)',
|
||||
color: 'var(--color-text)',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto space-y-1">
|
||||
{filteredActive.length === 0 && !searchQuery ? (
|
||||
<p className="px-1 py-2 text-xs text-[var(--color-muted)]">No conversations yet</p>
|
||||
) : null}
|
||||
{filteredActive.length === 0 && searchQuery ? (
|
||||
<p className="px-1 py-2 text-xs text-[var(--color-muted)]">
|
||||
No results for “{searchQuery}”
|
||||
</p>
|
||||
) : null}
|
||||
{filteredActive.map((conversation) => renderConversationItem(conversation))}
|
||||
|
||||
{archivedConversations.length > 0 ? (
|
||||
<div className="pt-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowArchived((prev) => !prev)}
|
||||
className="flex w-full items-center gap-2 px-1 py-1 text-xs text-[var(--color-muted)] transition-colors hover:text-[var(--color-text-2)]"
|
||||
>
|
||||
<span
|
||||
className={cn('inline-block transition-transform', showArchived && 'rotate-90')}
|
||||
>
|
||||
▶
|
||||
</span>
|
||||
Archived ({archivedConversations.length})
|
||||
</button>
|
||||
{showArchived ? (
|
||||
<div className="mt-1 space-y-1 opacity-70">
|
||||
{filteredArchived.map((conversation) => renderConversationItem(conversation))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{contextMenu && contextConversation ? (
|
||||
<div
|
||||
className="fixed z-30 min-w-40 rounded-2xl border py-1 shadow-[var(--shadow-ms-lg)]"
|
||||
style={{
|
||||
top: contextMenu.y,
|
||||
left: contextMenu.x,
|
||||
backgroundColor: 'var(--color-surface)',
|
||||
borderColor: 'var(--color-border)',
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="w-full px-3 py-2 text-left text-sm text-[var(--color-text-2)] transition-colors hover:bg-white/5"
|
||||
onClick={() => startRename(contextConversation.id, contextConversation.title)}
|
||||
>
|
||||
Rename
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="w-full px-3 py-2 text-left text-sm text-[var(--color-text-2)] transition-colors hover:bg-white/5"
|
||||
onClick={() =>
|
||||
handleArchiveToggle(contextConversation.id, !contextConversation.archived)
|
||||
}
|
||||
>
|
||||
{contextConversation.archived ? 'Restore' : 'Archive'}
|
||||
</button>
|
||||
{deleteConfirmId === contextConversation.id ? (
|
||||
<button
|
||||
type="button"
|
||||
className="w-full px-3 py-2 text-left text-sm text-[var(--color-danger)] transition-colors hover:bg-white/5"
|
||||
onClick={() => confirmDelete(contextConversation.id)}
|
||||
>
|
||||
Confirm delete
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="w-full px-3 py-2 text-left text-sm text-[var(--color-danger)] transition-colors hover:bg-white/5"
|
||||
onClick={() => setDeleteConfirmId(contextConversation.id)}
|
||||
>
|
||||
Delete…
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,574 @@
|
||||
import {
|
||||
forwardRef,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { api } from '@/lib/api';
|
||||
import type { Conversation, Project } from '@/lib/types';
|
||||
|
||||
export interface ConversationSummary {
|
||||
id: string;
|
||||
title: string | null;
|
||||
projectId: string | null;
|
||||
updatedAt: string;
|
||||
archived?: boolean;
|
||||
}
|
||||
|
||||
export interface ConversationSidebarRef {
|
||||
refresh: () => void;
|
||||
addConversation: (conversation: ConversationSummary) => void;
|
||||
}
|
||||
|
||||
interface ConversationSidebarProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
currentConversationId: string | null;
|
||||
onSelectConversation: (conversationId: string | null) => void;
|
||||
onNewConversation: (projectId?: string | null) => void;
|
||||
}
|
||||
|
||||
interface GroupedConversations {
|
||||
key: string;
|
||||
label: string;
|
||||
projectId: string | null;
|
||||
conversations: ConversationSummary[];
|
||||
}
|
||||
|
||||
function toSummary(conversation: Conversation): ConversationSummary {
|
||||
return {
|
||||
id: conversation.id,
|
||||
title: conversation.title,
|
||||
projectId: conversation.projectId,
|
||||
updatedAt: conversation.updatedAt,
|
||||
archived: conversation.archived,
|
||||
};
|
||||
}
|
||||
|
||||
function formatRelativeTime(dateStr: string): string {
|
||||
const date = new Date(dateStr);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
const diffMinutes = Math.floor(diffMs / 60_000);
|
||||
const diffHours = Math.floor(diffMs / 3_600_000);
|
||||
const diffDays = Math.floor(diffMs / 86_400_000);
|
||||
|
||||
if (diffMinutes < 1) return 'Just now';
|
||||
if (diffMinutes < 60) return `${diffMinutes}m ago`;
|
||||
if (diffHours < 24) return `${diffHours}h ago`;
|
||||
if (diffDays === 1) return 'Yesterday';
|
||||
if (diffDays < 7) return `${diffDays}d ago`;
|
||||
|
||||
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
|
||||
}
|
||||
|
||||
export const ConversationSidebar = forwardRef<ConversationSidebarRef, ConversationSidebarProps>(
|
||||
function ConversationSidebar(
|
||||
{ isOpen, onClose, currentConversationId, onSelectConversation, onNewConversation },
|
||||
ref,
|
||||
): React.ReactElement {
|
||||
const [conversations, setConversations] = useState<ConversationSummary[]>([]);
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [renamingId, setRenamingId] = useState<string | null>(null);
|
||||
const [renameValue, setRenameValue] = useState('');
|
||||
const [pendingDeleteId, setPendingDeleteId] = useState<string | null>(null);
|
||||
const [hoveredId, setHoveredId] = useState<string | null>(null);
|
||||
const renameInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const loadSidebarData = useCallback(async (): Promise<void> => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
const [loadedConversations, loadedProjects] = await Promise.all([
|
||||
api<Conversation[]>('/api/conversations'),
|
||||
api<Project[]>('/api/projects').catch(() => [] as Project[]),
|
||||
]);
|
||||
|
||||
setConversations(
|
||||
loadedConversations
|
||||
.filter((conversation) => !conversation.archived)
|
||||
.map(toSummary)
|
||||
.sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt)),
|
||||
);
|
||||
setProjects(loadedProjects);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load conversations');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void loadSidebarData();
|
||||
}, [loadSidebarData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!renamingId) return;
|
||||
const timer = window.setTimeout(() => renameInputRef.current?.focus(), 0);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [renamingId]);
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
refresh: () => {
|
||||
void loadSidebarData();
|
||||
},
|
||||
addConversation: (conversation) => {
|
||||
setConversations((prev) => {
|
||||
const next = [conversation, ...prev.filter((item) => item.id !== conversation.id)];
|
||||
return next.sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));
|
||||
});
|
||||
},
|
||||
}),
|
||||
[loadSidebarData],
|
||||
);
|
||||
|
||||
const filteredConversations = useMemo(() => {
|
||||
const query = searchQuery.trim().toLowerCase();
|
||||
if (!query) return conversations;
|
||||
|
||||
return conversations.filter((conversation) =>
|
||||
(conversation.title ?? 'Untitled conversation').toLowerCase().includes(query),
|
||||
);
|
||||
}, [conversations, searchQuery]);
|
||||
|
||||
const groupedConversations = useMemo<GroupedConversations[]>(() => {
|
||||
if (projects.length === 0) {
|
||||
return [
|
||||
{
|
||||
key: 'all',
|
||||
label: 'All conversations',
|
||||
projectId: null,
|
||||
conversations: filteredConversations,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const byProject = new Map<string | null, ConversationSummary[]>();
|
||||
for (const conversation of filteredConversations) {
|
||||
const key = conversation.projectId ?? null;
|
||||
const items = byProject.get(key) ?? [];
|
||||
items.push(conversation);
|
||||
byProject.set(key, items);
|
||||
}
|
||||
|
||||
const groups: GroupedConversations[] = [];
|
||||
|
||||
for (const project of projects) {
|
||||
const projectConversations = byProject.get(project.id);
|
||||
if (!projectConversations?.length) continue;
|
||||
|
||||
groups.push({
|
||||
key: project.id,
|
||||
label: project.name,
|
||||
projectId: project.id,
|
||||
conversations: projectConversations,
|
||||
});
|
||||
}
|
||||
|
||||
const ungrouped = byProject.get(null);
|
||||
if (ungrouped?.length) {
|
||||
groups.push({
|
||||
key: 'general',
|
||||
label: 'General',
|
||||
projectId: null,
|
||||
conversations: ungrouped,
|
||||
});
|
||||
}
|
||||
|
||||
if (groups.length === 0) {
|
||||
groups.push({
|
||||
key: 'all',
|
||||
label: 'All conversations',
|
||||
projectId: null,
|
||||
conversations: filteredConversations,
|
||||
});
|
||||
}
|
||||
|
||||
return groups;
|
||||
}, [filteredConversations, projects]);
|
||||
|
||||
const startRename = useCallback((conversation: ConversationSummary): void => {
|
||||
setPendingDeleteId(null);
|
||||
setRenamingId(conversation.id);
|
||||
setRenameValue(conversation.title ?? '');
|
||||
}, []);
|
||||
|
||||
const cancelRename = useCallback((): void => {
|
||||
setRenamingId(null);
|
||||
setRenameValue('');
|
||||
}, []);
|
||||
|
||||
const commitRename = useCallback(async (): Promise<void> => {
|
||||
if (!renamingId) return;
|
||||
|
||||
const title = renameValue.trim() || 'Untitled conversation';
|
||||
|
||||
try {
|
||||
const updated = await api<Conversation>(`/api/conversations/${renamingId}`, {
|
||||
method: 'PATCH',
|
||||
body: { title },
|
||||
});
|
||||
|
||||
const summary = toSummary(updated);
|
||||
setConversations((prev) =>
|
||||
prev
|
||||
.map((conversation) => (conversation.id === renamingId ? summary : conversation))
|
||||
.sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt)),
|
||||
);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to rename conversation');
|
||||
} finally {
|
||||
setRenamingId(null);
|
||||
setRenameValue('');
|
||||
}
|
||||
}, [renameValue, renamingId]);
|
||||
|
||||
const deleteConversation = useCallback(
|
||||
async (conversationId: string): Promise<void> => {
|
||||
try {
|
||||
await api<void>(`/api/conversations/${conversationId}`, { method: 'DELETE' });
|
||||
setConversations((prev) =>
|
||||
prev.filter((conversation) => conversation.id !== conversationId),
|
||||
);
|
||||
if (currentConversationId === conversationId) {
|
||||
onSelectConversation(null);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to delete conversation');
|
||||
} finally {
|
||||
setPendingDeleteId(null);
|
||||
}
|
||||
},
|
||||
[currentConversationId, onSelectConversation],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{isOpen ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Close conversation sidebar"
|
||||
className="fixed inset-0 z-30 bg-black/50 md:hidden"
|
||||
onClick={onClose}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<aside
|
||||
aria-label="Conversation sidebar"
|
||||
className="fixed left-0 top-0 z-40 flex h-full flex-col border-r md:relative md:z-0"
|
||||
style={{
|
||||
width: 'var(--sidebar-w)',
|
||||
background: 'var(--bg)',
|
||||
borderColor: 'var(--border)',
|
||||
transform: isOpen ? 'translateX(0)' : 'translateX(calc(-1 * var(--sidebar-w)))',
|
||||
transition: 'transform 220ms var(--ease)',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="flex items-center justify-between border-b px-4 py-3"
|
||||
style={{ borderColor: 'var(--border)' }}
|
||||
>
|
||||
<div>
|
||||
<p className="text-sm font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Conversations
|
||||
</p>
|
||||
<p className="text-xs" style={{ color: 'var(--muted)' }}>
|
||||
Search, rename, and manage threads
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="rounded-md p-2 md:hidden"
|
||||
style={{ color: 'var(--text-2)' }}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor">
|
||||
<path strokeWidth="2" strokeLinecap="round" d="M6 6l12 12M18 6 6 18" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 border-b p-3" style={{ borderColor: 'var(--border)' }}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onNewConversation(null)}
|
||||
className="flex w-full items-center justify-center gap-2 rounded-lg border px-3 py-2 text-sm font-medium transition-colors"
|
||||
style={{
|
||||
borderColor: 'var(--primary)',
|
||||
background: 'color-mix(in srgb, var(--primary) 12%, transparent)',
|
||||
color: 'var(--text)',
|
||||
}}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor">
|
||||
<path strokeWidth="2" strokeLinecap="round" d="M12 5v14M5 12h14" />
|
||||
</svg>
|
||||
New conversation
|
||||
</button>
|
||||
|
||||
<div className="relative">
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
style={{ color: 'var(--muted)' }}
|
||||
>
|
||||
<circle cx="11" cy="11" r="7" strokeWidth="2" />
|
||||
<path d="m20 20-3.5-3.5" strokeWidth="2" strokeLinecap="round" />
|
||||
</svg>
|
||||
<input
|
||||
type="search"
|
||||
value={searchQuery}
|
||||
onChange={(event) => setSearchQuery(event.target.value)}
|
||||
placeholder="Search conversations"
|
||||
className="w-full rounded-lg border px-9 py-2 text-sm outline-none"
|
||||
style={{
|
||||
background: 'var(--surface)',
|
||||
borderColor: 'var(--border)',
|
||||
color: 'var(--text)',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-3">
|
||||
{isLoading ? (
|
||||
<div className="py-8 text-center text-sm" style={{ color: 'var(--muted)' }}>
|
||||
Loading conversations...
|
||||
</div>
|
||||
) : error ? (
|
||||
<div
|
||||
className="space-y-3 rounded-xl border p-4 text-sm"
|
||||
style={{
|
||||
background: 'color-mix(in srgb, var(--danger) 10%, var(--surface))',
|
||||
borderColor: 'color-mix(in srgb, var(--danger) 35%, var(--border))',
|
||||
color: 'var(--text)',
|
||||
}}
|
||||
>
|
||||
<p>{error}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void loadSidebarData()}
|
||||
className="rounded-md px-3 py-1.5 text-xs font-medium"
|
||||
style={{ background: 'var(--danger)', color: 'white' }}
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
) : filteredConversations.length === 0 ? (
|
||||
<div className="py-10 text-center">
|
||||
<p className="text-sm" style={{ color: 'var(--text-2)' }}>
|
||||
{searchQuery ? 'No matching conversations' : 'No conversations yet'}
|
||||
</p>
|
||||
<p className="mt-1 text-xs" style={{ color: 'var(--muted)' }}>
|
||||
{searchQuery ? 'Try another title search.' : 'Start a new conversation to begin.'}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{groupedConversations.map((group) => (
|
||||
<section key={group.key} className="space-y-2">
|
||||
{projects.length > 0 ? (
|
||||
<div className="flex items-center justify-between px-1">
|
||||
<h3
|
||||
className="text-[11px] font-semibold uppercase tracking-[0.16em]"
|
||||
style={{ color: 'var(--muted)' }}
|
||||
>
|
||||
{group.label}
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onNewConversation(group.projectId)}
|
||||
className="rounded-md px-2 py-1 text-[11px] font-medium"
|
||||
style={{ color: 'var(--ms-blue-500)' }}
|
||||
>
|
||||
New
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="space-y-1">
|
||||
{group.conversations.map((conversation) => {
|
||||
const isActive = currentConversationId === conversation.id;
|
||||
const isRenaming = renamingId === conversation.id;
|
||||
const showActions =
|
||||
hoveredId === conversation.id ||
|
||||
isRenaming ||
|
||||
pendingDeleteId === conversation.id;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={conversation.id}
|
||||
onMouseEnter={() => setHoveredId(conversation.id)}
|
||||
onMouseLeave={() =>
|
||||
setHoveredId((current) =>
|
||||
current === conversation.id ? null : current,
|
||||
)
|
||||
}
|
||||
className="rounded-xl border p-2 transition-colors"
|
||||
style={{
|
||||
borderColor: isActive
|
||||
? 'color-mix(in srgb, var(--primary) 60%, var(--border))'
|
||||
: 'transparent',
|
||||
background: isActive ? 'var(--surface-2)' : 'transparent',
|
||||
}}
|
||||
>
|
||||
{isRenaming ? (
|
||||
<input
|
||||
ref={renameInputRef}
|
||||
value={renameValue}
|
||||
onChange={(event) => setRenameValue(event.target.value)}
|
||||
onBlur={() => void commitRename()}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
void commitRename();
|
||||
}
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
cancelRename();
|
||||
}
|
||||
}}
|
||||
maxLength={255}
|
||||
className="w-full rounded-md border px-2 py-1.5 text-sm outline-none"
|
||||
style={{
|
||||
background: 'var(--surface)',
|
||||
borderColor: 'var(--ms-blue-500)',
|
||||
color: 'var(--text)',
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSelectConversation(conversation.id)}
|
||||
className="block w-full text-left"
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p
|
||||
className="truncate text-sm font-medium"
|
||||
style={{
|
||||
color: isActive ? 'var(--text)' : 'var(--text-2)',
|
||||
}}
|
||||
>
|
||||
{conversation.title ?? 'Untitled conversation'}
|
||||
</p>
|
||||
<p className="mt-1 text-xs" style={{ color: 'var(--muted)' }}>
|
||||
{formatRelativeTime(conversation.updatedAt)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{showActions ? (
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
startRename(conversation);
|
||||
}}
|
||||
className="rounded-md p-1.5 transition-colors"
|
||||
style={{ color: 'var(--text-2)' }}
|
||||
aria-label={`Rename ${conversation.title ?? 'conversation'}`}
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
className="h-3.5 w-3.5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M4 20h4l10.5-10.5a1.4 1.4 0 0 0 0-2L16.5 5.5a1.4 1.4 0 0 0-2 0L4 16v4Z"
|
||||
strokeWidth="1.8"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
setPendingDeleteId((current) =>
|
||||
current === conversation.id ? null : conversation.id,
|
||||
);
|
||||
setRenamingId(null);
|
||||
}}
|
||||
className="rounded-md p-1.5 transition-colors"
|
||||
style={{ color: 'var(--danger)' }}
|
||||
aria-label={`Delete ${conversation.title ?? 'conversation'}`}
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
className="h-3.5 w-3.5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M4 7h16M10 11v6M14 11v6M6 7l1 12h10l1-12M9 7V4h6v3"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{pendingDeleteId === conversation.id ? (
|
||||
<div
|
||||
className="mt-2 flex items-center justify-between rounded-lg border px-2 py-2"
|
||||
style={{
|
||||
borderColor:
|
||||
'color-mix(in srgb, var(--danger) 45%, var(--border))',
|
||||
background:
|
||||
'color-mix(in srgb, var(--danger) 10%, var(--surface))',
|
||||
}}
|
||||
>
|
||||
<p className="text-xs" style={{ color: 'var(--text-2)' }}>
|
||||
Delete this conversation?
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPendingDeleteId(null)}
|
||||
className="rounded-md px-2 py-1 text-xs"
|
||||
style={{ color: 'var(--text-2)' }}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void deleteConversation(conversation.id)}
|
||||
className="rounded-md px-2 py-1 text-xs font-medium"
|
||||
style={{ background: 'var(--danger)', color: 'white' }}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,269 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import { cn } from '@/lib/cn';
|
||||
import type { Message } from '@/lib/types';
|
||||
|
||||
interface MessageBubbleProps {
|
||||
message: Message;
|
||||
}
|
||||
|
||||
export function MessageBubble({ message }: MessageBubbleProps): React.ReactElement {
|
||||
const isUser = message.role === 'user';
|
||||
const isSystem = message.role === 'system';
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [thinkingExpanded, setThinkingExpanded] = useState(false);
|
||||
const { response, thinking } = useMemo(
|
||||
() => parseThinking(message.content, message.thinking),
|
||||
[message.content, message.thinking],
|
||||
);
|
||||
|
||||
const handleCopy = useCallback(async (): Promise<void> => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(response);
|
||||
setCopied(true);
|
||||
window.setTimeout(() => setCopied(false), 1800);
|
||||
} catch (error) {
|
||||
console.error('[MessageBubble] Failed to copy message:', error);
|
||||
}
|
||||
}, [response]);
|
||||
|
||||
if (isSystem) {
|
||||
return (
|
||||
<div className="flex justify-center">
|
||||
<div
|
||||
className="max-w-[42rem] rounded-full border px-3 py-1.5 text-xs backdrop-blur-sm"
|
||||
style={{
|
||||
borderColor: 'var(--color-border)',
|
||||
backgroundColor: 'color-mix(in srgb, var(--color-surface) 70%, transparent)',
|
||||
color: 'var(--color-muted)',
|
||||
}}
|
||||
>
|
||||
<span>{response}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('group flex', isUser ? 'justify-end' : 'justify-start')}>
|
||||
<div
|
||||
className={cn(
|
||||
'flex max-w-[min(78ch,85%)] flex-col gap-2',
|
||||
isUser ? 'items-end' : 'items-start',
|
||||
)}
|
||||
>
|
||||
<div className={cn('flex items-center gap-2 text-[11px]', isUser && 'flex-row-reverse')}>
|
||||
<span className="font-medium text-[var(--color-text-2)]">
|
||||
{isUser ? 'You' : 'Assistant'}
|
||||
</span>
|
||||
{!isUser && message.model ? (
|
||||
<span
|
||||
className="rounded-full border px-2 py-0.5 font-medium text-[var(--color-text-2)]"
|
||||
style={{
|
||||
backgroundColor: 'color-mix(in srgb, var(--color-surface-2) 82%, transparent)',
|
||||
borderColor: 'var(--color-border)',
|
||||
}}
|
||||
title={message.provider ? `Provider: ${message.provider}` : undefined}
|
||||
>
|
||||
{message.model}
|
||||
</span>
|
||||
) : null}
|
||||
{!isUser && typeof message.totalTokens === 'number' && message.totalTokens > 0 ? (
|
||||
<span
|
||||
className="rounded-full border px-2 py-0.5 text-[var(--color-muted)]"
|
||||
style={{ borderColor: 'var(--color-border)' }}
|
||||
>
|
||||
{formatTokenCount(message.totalTokens)}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="text-[var(--color-muted)]">{formatTimestamp(message.createdAt)}</span>
|
||||
</div>
|
||||
|
||||
{thinking && !isUser ? (
|
||||
<div
|
||||
className="w-full overflow-hidden rounded-2xl border"
|
||||
style={{
|
||||
backgroundColor: 'color-mix(in srgb, var(--color-surface-2) 88%, transparent)',
|
||||
borderColor: 'var(--color-border)',
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setThinkingExpanded((prev) => !prev)}
|
||||
className="flex w-full items-center gap-2 px-3 py-2 text-left text-xs font-medium text-[var(--color-text-2)] transition-colors hover:bg-black/5"
|
||||
aria-expanded={thinkingExpanded}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'inline-block text-[10px] transition-transform',
|
||||
thinkingExpanded && 'rotate-90',
|
||||
)}
|
||||
>
|
||||
▶
|
||||
</span>
|
||||
<span>Chain of thought</span>
|
||||
<span className="ml-auto text-[var(--color-muted)]">
|
||||
{thinkingExpanded ? 'Hide' : 'Show'}
|
||||
</span>
|
||||
</button>
|
||||
{thinkingExpanded ? (
|
||||
<pre
|
||||
className="overflow-x-auto border-t px-3 py-3 font-mono text-xs leading-6 whitespace-pre-wrap"
|
||||
style={{
|
||||
borderColor: 'var(--color-border)',
|
||||
backgroundColor: 'var(--color-bg-deep)',
|
||||
color: 'var(--color-text-2)',
|
||||
}}
|
||||
>
|
||||
{thinking}
|
||||
</pre>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'relative w-full rounded-3xl px-4 py-3 text-sm shadow-[var(--shadow-ms-sm)]',
|
||||
!isUser && 'border',
|
||||
)}
|
||||
style={{
|
||||
backgroundColor: isUser ? 'var(--color-ms-blue-500)' : 'var(--color-surface)',
|
||||
color: isUser ? '#fff' : 'var(--color-text)',
|
||||
borderColor: isUser ? 'transparent' : 'var(--color-border)',
|
||||
}}
|
||||
>
|
||||
<div className="max-w-none">
|
||||
<ReactMarkdown
|
||||
components={{
|
||||
p: ({ children }) => <p className="mb-3 leading-7 last:mb-0">{children}</p>,
|
||||
ul: ({ children }) => <ul className="mb-3 list-disc pl-5 last:mb-0">{children}</ul>,
|
||||
ol: ({ children }) => (
|
||||
<ol className="mb-3 list-decimal pl-5 last:mb-0">{children}</ol>
|
||||
),
|
||||
li: ({ children }) => <li className="mb-1">{children}</li>,
|
||||
a: ({ href, children }) => (
|
||||
<a
|
||||
href={href}
|
||||
className="font-medium underline underline-offset-4"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
pre: ({ children }) => <div className="mb-3 last:mb-0">{children}</div>,
|
||||
code: ({ className, children, ...props }) => {
|
||||
const language = className?.replace('language-', '');
|
||||
const content = String(children).replace(/\n$/, '');
|
||||
const isInline = !className;
|
||||
|
||||
if (isInline) {
|
||||
return (
|
||||
<code
|
||||
className="rounded-md px-1.5 py-0.5 font-mono text-[0.9em]"
|
||||
style={{
|
||||
backgroundColor:
|
||||
'color-mix(in srgb, var(--color-bg-deep) 76%, transparent)',
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</code>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="overflow-hidden rounded-2xl border"
|
||||
style={{
|
||||
backgroundColor: 'var(--color-bg-deep)',
|
||||
borderColor: 'var(--color-border)',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="border-b px-3 py-2 font-mono text-[11px] uppercase tracking-[0.18em] text-[var(--color-muted)]"
|
||||
style={{ borderColor: 'var(--color-border)' }}
|
||||
>
|
||||
{language || 'code'}
|
||||
</div>
|
||||
<pre className="overflow-x-auto p-3">
|
||||
<code
|
||||
className={cn('font-mono text-[13px] leading-6', className)}
|
||||
{...props}
|
||||
>
|
||||
{content}
|
||||
</code>
|
||||
</pre>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
blockquote: ({ children }) => (
|
||||
<blockquote
|
||||
className="mb-3 border-l-2 pl-4 italic last:mb-0"
|
||||
style={{ borderColor: 'var(--color-ms-blue-500)' }}
|
||||
>
|
||||
{children}
|
||||
</blockquote>
|
||||
),
|
||||
}}
|
||||
>
|
||||
{response}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleCopy()}
|
||||
className="absolute -right-2 -top-2 rounded-full border p-2 opacity-0 shadow-[var(--shadow-ms-md)] transition-all group-hover:opacity-100 focus:opacity-100"
|
||||
style={{
|
||||
backgroundColor: 'var(--color-surface)',
|
||||
borderColor: 'var(--color-border)',
|
||||
color: copied ? 'var(--color-success)' : 'var(--color-text-2)',
|
||||
}}
|
||||
aria-label={copied ? 'Copied' : 'Copy message'}
|
||||
title={copied ? 'Copied' : 'Copy message'}
|
||||
>
|
||||
{copied ? '✓' : '⧉'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function parseThinking(
|
||||
content: string,
|
||||
thinking?: string,
|
||||
): { response: string; thinking: string | null } {
|
||||
if (thinking) {
|
||||
return { response: content, thinking };
|
||||
}
|
||||
|
||||
const regex = /<(?:thinking|think)>([\s\S]*?)<\/(?:thinking|think)>/gi;
|
||||
const matches = [...content.matchAll(regex)];
|
||||
if (matches.length === 0) {
|
||||
return { response: content, thinking: null };
|
||||
}
|
||||
|
||||
return {
|
||||
response: content.replace(regex, '').trim(),
|
||||
thinking:
|
||||
matches
|
||||
.map((match) => match[1]?.trim() ?? '')
|
||||
.filter(Boolean)
|
||||
.join('\n\n') || null,
|
||||
};
|
||||
}
|
||||
|
||||
function formatTimestamp(createdAt: string): string {
|
||||
return new Date(createdAt).toLocaleTimeString([], {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
function formatTokenCount(totalTokens: number): string {
|
||||
if (totalTokens >= 1_000_000) return `${(totalTokens / 1_000_000).toFixed(1)}M tokens`;
|
||||
if (totalTokens >= 1_000) return `${(totalTokens / 1_000).toFixed(1)}k tokens`;
|
||||
return `${totalTokens} tokens`;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
interface StreamingMessageProps {
|
||||
text: string;
|
||||
modelName?: string | null;
|
||||
thinking?: string;
|
||||
}
|
||||
|
||||
const WAITING_QUIPS = [
|
||||
'The AI is warming up... give it a moment.',
|
||||
'Brewing some thoughts...',
|
||||
'Summoning intelligence from the void...',
|
||||
'Consulting the silicon oracle...',
|
||||
'Teaching electrons to think...',
|
||||
];
|
||||
|
||||
const TIMEOUT_QUIPS = [
|
||||
'The model wandered off. Let’s try to find it again.',
|
||||
'Response is taking the scenic route.',
|
||||
'That answer is clearly overthinking things.',
|
||||
'Still working. Either brilliance or a detour.',
|
||||
];
|
||||
|
||||
export function StreamingMessage({
|
||||
text,
|
||||
modelName,
|
||||
thinking,
|
||||
}: StreamingMessageProps): React.ReactElement {
|
||||
const [elapsedMs, setElapsedMs] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
setElapsedMs(0);
|
||||
const startedAt = Date.now();
|
||||
const timer = window.setInterval(() => {
|
||||
setElapsedMs(Date.now() - startedAt);
|
||||
}, 1000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [text, modelName, thinking]);
|
||||
|
||||
const quip = useMemo(() => {
|
||||
if (elapsedMs >= 18_000) {
|
||||
return TIMEOUT_QUIPS[Math.floor((elapsedMs / 1000) % TIMEOUT_QUIPS.length)];
|
||||
}
|
||||
if (elapsedMs >= 4_000) {
|
||||
return WAITING_QUIPS[Math.floor((elapsedMs / 1000) % WAITING_QUIPS.length)];
|
||||
}
|
||||
return null;
|
||||
}, [elapsedMs]);
|
||||
|
||||
return (
|
||||
<div className="flex justify-start">
|
||||
<div
|
||||
className="max-w-[min(78ch,85%)] rounded-3xl border px-4 py-3 text-sm shadow-[var(--shadow-ms-sm)]"
|
||||
style={{
|
||||
backgroundColor: 'var(--color-surface)',
|
||||
borderColor: 'var(--color-border)',
|
||||
color: 'var(--color-text)',
|
||||
}}
|
||||
>
|
||||
<div className="mb-2 flex items-center gap-2 text-[11px]">
|
||||
<span className="font-medium text-[var(--color-text-2)]">Assistant</span>
|
||||
{modelName ? (
|
||||
<span className="rounded-full border border-[var(--color-border)] px-2 py-0.5 text-[var(--color-text-2)]">
|
||||
{modelName}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="text-[var(--color-muted)]">{text ? 'Responding…' : 'Thinking…'}</span>
|
||||
</div>
|
||||
{text ? (
|
||||
<div className="whitespace-pre-wrap break-words">{text}</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2 text-[var(--color-muted)]">
|
||||
<span className="inline-block h-2 w-2 animate-pulse rounded-full bg-[var(--color-ms-blue-500)]" />
|
||||
<span className="inline-block h-2 w-2 animate-pulse rounded-full bg-[var(--color-ms-blue-500)] [animation-delay:0.2s]" />
|
||||
<span className="inline-block h-2 w-2 animate-pulse rounded-full bg-[var(--color-ms-blue-500)] [animation-delay:0.4s]" />
|
||||
</div>
|
||||
)}
|
||||
{thinking ? (
|
||||
<div
|
||||
className="mt-3 rounded-2xl border px-3 py-2 font-mono text-xs whitespace-pre-wrap"
|
||||
style={{
|
||||
backgroundColor: 'var(--color-bg-deep)',
|
||||
borderColor: 'var(--color-border)',
|
||||
color: 'var(--color-text-2)',
|
||||
}}
|
||||
>
|
||||
{thinking}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="mt-2 flex items-center gap-2 text-xs text-[var(--color-muted)]">
|
||||
<span className="inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-[var(--color-ms-blue-500)]" />
|
||||
<span>{quip ?? (text ? 'Responding…' : 'Thinking…')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import type { ReactElement } from 'react';
|
||||
import { formatAge, type FreshnessLabel } from '@/lib/freshness/model';
|
||||
|
||||
/**
|
||||
* Rendering rules for non-current freshness states (RI-5-001).
|
||||
*
|
||||
* - `unavailable` renders an explicit failure panel — never an empty
|
||||
* healthy collection.
|
||||
* - `stale` may render last-known data, but only under a visible label
|
||||
* carrying source identity, snapshot version, and age.
|
||||
* - `partial` renders the verified parts plus an explicit list of what is
|
||||
* missing.
|
||||
*/
|
||||
|
||||
interface RetryableNoticeProps {
|
||||
readonly onRetry?: () => void;
|
||||
readonly retryLabel?: string;
|
||||
}
|
||||
|
||||
function RetryButton({ onRetry, retryLabel }: RetryableNoticeProps): ReactElement | null {
|
||||
if (!onRetry) return null;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRetry}
|
||||
className="mt-2 rounded-lg border border-surface-border px-3 py-1.5 text-xs transition-colors hover:border-gray-500"
|
||||
>
|
||||
{retryLabel ?? 'Retry'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export interface UnavailableDataNoticeProps extends RetryableNoticeProps {
|
||||
/** What is unavailable, e.g. "Tasks". */
|
||||
readonly title: string;
|
||||
/** Optional underlying failure detail (network message, invalidation reason). */
|
||||
readonly detail?: string | null;
|
||||
}
|
||||
|
||||
/** Explicit `unavailable` state. Never renders as an empty healthy collection. */
|
||||
export function UnavailableDataNotice({
|
||||
title,
|
||||
detail,
|
||||
onRetry,
|
||||
retryLabel,
|
||||
}: UnavailableDataNoticeProps): ReactElement {
|
||||
return (
|
||||
<div role="alert" className="rounded-lg border border-error/40 px-4 py-3 text-sm">
|
||||
<p className="font-medium text-text-primary">{title} are unavailable</p>
|
||||
<p className="mt-1 text-text-muted">
|
||||
This is not an empty result — the data could not be verified from the gateway.
|
||||
{detail ? ` ${detail}` : ''}
|
||||
</p>
|
||||
<RetryButton onRetry={onRetry} retryLabel={retryLabel} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export interface StaleDataNoticeProps extends RetryableNoticeProps {
|
||||
/** Provenance of the last-known snapshot being displayed. */
|
||||
readonly label: FreshnessLabel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Situational-awareness banner for `stale` data: last-known data may render,
|
||||
* but visibly labeled with source identity, snapshot version, and age.
|
||||
*/
|
||||
export function StaleDataNotice({
|
||||
label,
|
||||
onRetry,
|
||||
retryLabel,
|
||||
}: StaleDataNoticeProps): ReactElement {
|
||||
return (
|
||||
<div role="status" className="rounded-lg border border-warning/40 px-4 py-3 text-sm">
|
||||
<p className="font-medium text-warning">Showing last-known data — it may be out of date</p>
|
||||
<p className="mt-1 text-xs text-text-muted">
|
||||
Source {label.source} · snapshot v{label.version} · fetched{' '}
|
||||
{formatAge(label.fetchedAt, Date.now())}. Verdicts derived from this data are unknown and
|
||||
changes are disabled until it is revalidated.
|
||||
</p>
|
||||
<RetryButton onRetry={onRetry} retryLabel={retryLabel ?? 'Revalidate'} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export interface PartialDataNoticeProps extends RetryableNoticeProps {
|
||||
/** Display names of the sections whose collections are unavailable. */
|
||||
readonly missing: readonly string[];
|
||||
}
|
||||
|
||||
/** `partial` surface banner: verified parts render, missing parts are explicit. */
|
||||
export function PartialDataNotice({
|
||||
missing,
|
||||
onRetry,
|
||||
retryLabel,
|
||||
}: PartialDataNoticeProps): ReactElement {
|
||||
return (
|
||||
<div role="status" className="rounded-lg border border-warning/40 px-4 py-3 text-sm">
|
||||
<p className="font-medium text-warning">Some data could not be loaded</p>
|
||||
<p className="mt-1 text-xs text-text-muted">
|
||||
{missing.join(', ')} {missing.length === 1 ? 'is' : 'are'} unavailable — sections below show
|
||||
an explicit unavailable state instead of an empty list. Derived verdicts remain unknown
|
||||
until every collection is revalidated.
|
||||
</p>
|
||||
<RetryButton onRetry={onRetry} retryLabel={retryLabel ?? 'Revalidate'} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { SidebarProvider, useSidebar } from './sidebar-context';
|
||||
import { Sidebar } from './sidebar';
|
||||
import { Topbar } from './topbar';
|
||||
|
||||
interface AppShellProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
function AppShellFrame({ children }: AppShellProps): React.ReactElement {
|
||||
const { collapsed, isMobile } = useSidebar();
|
||||
|
||||
return (
|
||||
<div className="app-shell" data-sidebar-hidden={!isMobile && collapsed ? 'true' : undefined}>
|
||||
<Topbar />
|
||||
<Sidebar />
|
||||
<div className="app-main">
|
||||
<main className="h-full overflow-y-auto p-6">{children}</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AppShell({ children }: AppShellProps): React.ReactElement {
|
||||
return (
|
||||
<SidebarProvider>
|
||||
<AppShellFrame>{children}</AppShellFrame>
|
||||
</SidebarProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
|
||||
|
||||
interface SidebarContextValue {
|
||||
collapsed: boolean;
|
||||
toggleCollapsed: () => void;
|
||||
mobileOpen: boolean;
|
||||
setMobileOpen: (open: boolean) => void;
|
||||
isMobile: boolean;
|
||||
}
|
||||
|
||||
const MOBILE_MAX_WIDTH = 767;
|
||||
const SidebarContext = createContext<SidebarContextValue | undefined>(undefined);
|
||||
|
||||
export function SidebarProvider({ children }: { children: ReactNode }): React.JSX.Element {
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
const [mobileOpen, setMobileOpen] = useState(false);
|
||||
const [isMobile, setIsMobile] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const mediaQuery = window.matchMedia(`(max-width: ${String(MOBILE_MAX_WIDTH)}px)`);
|
||||
|
||||
const syncState = (matches: boolean): void => {
|
||||
setIsMobile(matches);
|
||||
if (!matches) {
|
||||
setMobileOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
syncState(mediaQuery.matches);
|
||||
|
||||
const handleChange = (event: MediaQueryListEvent): void => {
|
||||
syncState(event.matches);
|
||||
};
|
||||
|
||||
mediaQuery.addEventListener('change', handleChange);
|
||||
|
||||
return () => {
|
||||
mediaQuery.removeEventListener('change', handleChange);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider
|
||||
value={{
|
||||
collapsed,
|
||||
toggleCollapsed: () => setCollapsed((value) => !value),
|
||||
mobileOpen,
|
||||
setMobileOpen,
|
||||
isMobile,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</SidebarContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useSidebar(): SidebarContextValue {
|
||||
const context = useContext(SidebarContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error('useSidebar must be used within SidebarProvider');
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { Link, useLocation } from 'react-router-dom';
|
||||
import { cn } from '@/lib/cn';
|
||||
import { MosaicLogo } from '@/components/ui/mosaic-logo';
|
||||
import { useSidebar } from './sidebar-context';
|
||||
|
||||
interface NavItem {
|
||||
label: string;
|
||||
href: string;
|
||||
icon: React.JSX.Element;
|
||||
}
|
||||
|
||||
function IconChat(): React.JSX.Element {
|
||||
return (
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
>
|
||||
<path d="M3 4.5A2.5 2.5 0 0 1 5.5 2h5A2.5 2.5 0 0 1 13 4.5v3A2.5 2.5 0 0 1 10.5 10H8l-3.5 3v-3H5.5A2.5 2.5 0 0 1 3 7.5z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function IconTasks(): React.JSX.Element {
|
||||
return (
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
>
|
||||
<path d="M6 3h7M6 8h7M6 13h7" />
|
||||
<path d="M2.5 3.5 3.5 4.5 5 2.5M2.5 8.5 3.5 9.5 5 7.5M2.5 13.5 3.5 14.5 5 12.5" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function IconProjects(): React.JSX.Element {
|
||||
return (
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
>
|
||||
<path d="M2 4.5A1.5 1.5 0 0 1 3.5 3h3l1.5 1.5h4A1.5 1.5 0 0 1 13.5 6v5.5A1.5 1.5 0 0 1 12 13H3.5A1.5 1.5 0 0 1 2 11.5z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function IconSettings(): React.JSX.Element {
|
||||
return (
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
>
|
||||
<circle cx="8" cy="8" r="2.25" />
|
||||
<path d="M8 1.5v2M8 12.5v2M1.5 8h2M12.5 8h2M3.05 3.05l1.4 1.4M11.55 11.55l1.4 1.4M3.05 12.95l1.4-1.4M11.55 4.45l1.4-1.4" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function IconAdmin(): React.JSX.Element {
|
||||
return (
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
>
|
||||
<path d="M8 1.75 13 3.5v3.58c0 3.12-1.88 5.94-5 7.17-3.12-1.23-5-4.05-5-7.17V3.5z" />
|
||||
<path d="M6.25 7.75 7.5 9l2.5-2.5" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
const navItems: NavItem[] = [
|
||||
{ label: 'Chat', href: '/chat', icon: <IconChat /> },
|
||||
{ label: 'Tasks', href: '/tasks', icon: <IconTasks /> },
|
||||
{ label: 'Projects', href: '/projects', icon: <IconProjects /> },
|
||||
{ label: 'Settings', href: '/settings', icon: <IconSettings /> },
|
||||
{ label: 'Admin', href: '/admin', icon: <IconAdmin /> },
|
||||
];
|
||||
|
||||
export function Sidebar(): React.ReactElement {
|
||||
const { pathname } = useLocation();
|
||||
const { mobileOpen, setMobileOpen } = useSidebar();
|
||||
|
||||
return (
|
||||
<>
|
||||
<aside
|
||||
className="app-sidebar"
|
||||
data-mobile-open={mobileOpen ? 'true' : undefined}
|
||||
style={{
|
||||
width: 'var(--sidebar-w)',
|
||||
background: 'var(--surface)',
|
||||
borderRightColor: 'var(--border)',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="flex h-16 items-center gap-3 border-b px-5"
|
||||
style={{ borderColor: 'var(--border)' }}
|
||||
>
|
||||
<MosaicLogo size={32} />
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<span className="text-sm font-semibold uppercase tracking-[0.12em] text-[var(--text)]">
|
||||
Mosaic
|
||||
</span>
|
||||
<span className="text-xs text-[var(--muted)]">Mission Control</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 px-3 py-4">
|
||||
<div className="mb-3 px-2 text-[11px] font-medium uppercase tracking-[0.18em] text-[var(--muted)]">
|
||||
Workspace
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
{navItems.map((item) => {
|
||||
const isActive = pathname === item.href || pathname.startsWith(`${item.href}/`);
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
to={item.href}
|
||||
onClick={() => setMobileOpen(false)}
|
||||
className={cn(
|
||||
'group flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm transition-all duration-150',
|
||||
isActive ? 'font-medium' : 'hover:bg-white/4',
|
||||
)}
|
||||
style={
|
||||
isActive
|
||||
? {
|
||||
background: 'color-mix(in srgb, var(--primary) 18%, transparent)',
|
||||
color: 'var(--primary)',
|
||||
}
|
||||
: { color: 'var(--text-2)' }
|
||||
}
|
||||
>
|
||||
<span className="shrink-0" aria-hidden="true">
|
||||
{item.icon}
|
||||
</span>
|
||||
<span>{item.label}</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div className="border-t px-5 py-4" style={{ borderColor: 'var(--border)' }}>
|
||||
<p className="text-xs text-[var(--muted)]">Mosaic Stack v0.0.4</p>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{mobileOpen ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Close sidebar"
|
||||
className="fixed inset-0 z-40 bg-black/40 md:hidden"
|
||||
onClick={() => setMobileOpen(false)}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useTheme } from '@/providers/theme-provider';
|
||||
|
||||
interface ThemeToggleProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ThemeToggle({ className = '' }: ThemeToggleProps): React.JSX.Element {
|
||||
const { theme, toggleTheme } = useTheme();
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleTheme}
|
||||
className={`btn-ghost rounded-md p-2 ${className}`}
|
||||
title={`Switch to ${theme === 'dark' ? 'light' : 'dark'} mode`}
|
||||
aria-label={`Switch to ${theme === 'dark' ? 'light' : 'dark'} mode`}
|
||||
>
|
||||
{theme === 'dark' ? (
|
||||
<svg
|
||||
className="h-5 w-5"
|
||||
style={{ color: 'var(--warn)' }}
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
>
|
||||
<circle cx="12" cy="12" r="4" />
|
||||
<path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg
|
||||
className="h-5 w-5"
|
||||
style={{ color: 'var(--text-2)' }}
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
>
|
||||
<path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { signOut, useSession } from '@/lib/auth-client';
|
||||
import { ThemeToggle } from './theme-toggle';
|
||||
import { useSidebar } from './sidebar-context';
|
||||
|
||||
function MenuIcon(): React.JSX.Element {
|
||||
return (
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
>
|
||||
<path d="M2 4h12M2 8h12M2 12h12" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function Topbar(): React.ReactElement {
|
||||
const { data: session } = useSession();
|
||||
const navigate = useNavigate();
|
||||
const { isMobile, mobileOpen, setMobileOpen, toggleCollapsed } = useSidebar();
|
||||
|
||||
async function handleSignOut(): Promise<void> {
|
||||
await signOut();
|
||||
navigate('/login', { replace: true });
|
||||
}
|
||||
|
||||
function handleSidebarToggle(): void {
|
||||
if (isMobile) {
|
||||
setMobileOpen(!mobileOpen);
|
||||
return;
|
||||
}
|
||||
|
||||
toggleCollapsed();
|
||||
}
|
||||
|
||||
return (
|
||||
<header
|
||||
className="app-header justify-between border-b px-4 md:px-6"
|
||||
style={{
|
||||
height: 'var(--topbar-h)',
|
||||
background: 'color-mix(in srgb, var(--surface) 88%, transparent)',
|
||||
borderBottomColor: 'var(--border)',
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSidebarToggle}
|
||||
className="btn-ghost rounded-lg border p-2"
|
||||
style={{ borderColor: 'var(--border)', color: 'var(--text-2)' }}
|
||||
aria-label="Toggle sidebar"
|
||||
>
|
||||
<MenuIcon />
|
||||
</button>
|
||||
<div className="hidden sm:block">
|
||||
<div className="text-sm font-medium text-[var(--text)]">Workspace</div>
|
||||
<div className="text-xs text-[var(--muted)]">Unified agent operations</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<ThemeToggle />
|
||||
{session?.user ? (
|
||||
<>
|
||||
<span className="hidden text-sm text-[var(--text-2)] sm:block">
|
||||
{session.user.name ?? session.user.email}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSignOut}
|
||||
className="rounded-md px-3 py-1.5 text-sm transition-colors"
|
||||
style={{ color: 'var(--muted)' }}
|
||||
>
|
||||
Sign out
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-sm text-[var(--muted)]">Not signed in</span>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { cn } from '@/lib/cn';
|
||||
import type { Mission, MissionStatus } from '@/lib/types';
|
||||
|
||||
interface MissionTimelineProps {
|
||||
missions: Mission[];
|
||||
}
|
||||
|
||||
const statusOrder: MissionStatus[] = ['planning', 'active', 'paused', 'completed', 'failed'];
|
||||
|
||||
const statusStyles: Record<MissionStatus, { dot: string; label: string; badge: string }> = {
|
||||
planning: {
|
||||
dot: 'bg-gray-400',
|
||||
label: 'text-gray-400',
|
||||
badge: 'bg-gray-600/20 text-gray-300',
|
||||
},
|
||||
active: {
|
||||
dot: 'bg-blue-400',
|
||||
label: 'text-blue-400',
|
||||
badge: 'bg-blue-600/20 text-blue-400',
|
||||
},
|
||||
paused: {
|
||||
dot: 'bg-warning',
|
||||
label: 'text-warning',
|
||||
badge: 'bg-warning/20 text-warning',
|
||||
},
|
||||
completed: {
|
||||
dot: 'bg-success',
|
||||
label: 'text-success',
|
||||
badge: 'bg-success/20 text-success',
|
||||
},
|
||||
failed: {
|
||||
dot: 'bg-error',
|
||||
label: 'text-error',
|
||||
badge: 'bg-error/20 text-error',
|
||||
},
|
||||
};
|
||||
|
||||
function sortMissions(missions: Mission[]): Mission[] {
|
||||
return [...missions].sort((a, b) => {
|
||||
const aIdx = statusOrder.indexOf(a.status);
|
||||
const bIdx = statusOrder.indexOf(b.status);
|
||||
if (aIdx !== bIdx) return aIdx - bIdx;
|
||||
return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
|
||||
});
|
||||
}
|
||||
|
||||
export function MissionTimeline({ missions }: MissionTimelineProps): React.ReactElement {
|
||||
if (missions.length === 0) {
|
||||
return (
|
||||
<div className="py-6 text-center">
|
||||
<p className="text-sm text-text-muted">No missions for this project</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const sorted = sortMissions(missions);
|
||||
|
||||
return (
|
||||
<ol className="relative space-y-0">
|
||||
{sorted.map((mission, idx) => {
|
||||
const styles = statusStyles[mission.status] ?? statusStyles.planning;
|
||||
const isLast = idx === sorted.length - 1;
|
||||
return (
|
||||
<li key={mission.id} className="relative flex gap-4 pb-6 last:pb-0">
|
||||
{/* Vertical line */}
|
||||
{!isLast && <div className="absolute left-2.5 top-5 h-full w-px bg-surface-border" />}
|
||||
{/* Status dot */}
|
||||
<div
|
||||
className={cn('mt-1 h-5 w-5 shrink-0 rounded-full border-2 border-bg', styles.dot)}
|
||||
/>
|
||||
<div className="flex-1 rounded-lg border border-surface-border bg-surface-card p-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<span className="text-sm font-medium text-text-primary">{mission.name}</span>
|
||||
<span className={cn('shrink-0 rounded-full px-2 py-0.5 text-xs', styles.badge)}>
|
||||
{mission.status}
|
||||
</span>
|
||||
</div>
|
||||
{mission.description && (
|
||||
<p className="mt-1 text-xs text-text-muted">{mission.description}</p>
|
||||
)}
|
||||
<p className="mt-2 text-xs text-text-muted">
|
||||
Created {new Date(mission.createdAt).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
interface PrdViewerProps {
|
||||
content: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight markdown-to-HTML renderer for PRD content.
|
||||
* Supports headings, bold, italic, inline code, code blocks, and lists.
|
||||
* No external dependency — keeps bundle size minimal.
|
||||
*/
|
||||
function renderMarkdown(md: string): string {
|
||||
let html = md
|
||||
// Escape HTML entities first to prevent XSS
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
|
||||
// Code blocks (must run before inline code)
|
||||
html = html.replace(/```[\w]*\n?([\s\S]*?)```/g, (_match, code: string) => {
|
||||
return `<pre class="overflow-x-auto rounded-lg bg-surface-elevated p-4 my-4"><code class="text-xs text-text-secondary whitespace-pre">${code.trim()}</code></pre>`;
|
||||
});
|
||||
|
||||
// Headings
|
||||
html = html.replace(
|
||||
/^#### (.+)$/gm,
|
||||
'<h4 class="text-sm font-semibold text-text-primary mt-4 mb-1">$1</h4>',
|
||||
);
|
||||
html = html.replace(
|
||||
/^### (.+)$/gm,
|
||||
'<h3 class="text-base font-semibold text-text-primary mt-6 mb-2">$1</h3>',
|
||||
);
|
||||
html = html.replace(
|
||||
/^## (.+)$/gm,
|
||||
'<h2 class="text-lg font-semibold text-text-primary mt-8 mb-3">$1</h2>',
|
||||
);
|
||||
html = html.replace(
|
||||
/^# (.+)$/gm,
|
||||
'<h1 class="text-xl font-bold text-text-primary mt-8 mb-4">$1</h1>',
|
||||
);
|
||||
|
||||
// Horizontal rule
|
||||
html = html.replace(/^---$/gm, '<hr class="my-6 border-surface-border" />');
|
||||
|
||||
// Unordered list items
|
||||
html = html.replace(
|
||||
/^[-*] (.+)$/gm,
|
||||
'<li class="ml-4 text-sm text-text-secondary list-disc">$1</li>',
|
||||
);
|
||||
|
||||
// Ordered list items
|
||||
html = html.replace(
|
||||
/^\d+\. (.+)$/gm,
|
||||
'<li class="ml-4 text-sm text-text-secondary list-decimal">$1</li>',
|
||||
);
|
||||
|
||||
// Bold + italic
|
||||
html = html.replace(/\*\*\*(.+?)\*\*\*/g, '<strong><em>$1</em></strong>');
|
||||
// Bold
|
||||
html = html.replace(
|
||||
/\*\*(.+?)\*\*/g,
|
||||
'<strong class="font-semibold text-text-primary">$1</strong>',
|
||||
);
|
||||
// Italic
|
||||
html = html.replace(/\*(.+?)\*/g, '<em class="italic text-text-secondary">$1</em>');
|
||||
|
||||
// Inline code
|
||||
html = html.replace(
|
||||
/`([^`]+)`/g,
|
||||
'<code class="rounded bg-surface-elevated px-1 py-0.5 text-xs text-text-secondary">$1</code>',
|
||||
);
|
||||
|
||||
// Paragraphs — wrap lines that aren't already wrapped in a block element
|
||||
const lines = html.split('\n');
|
||||
const result: string[] = [];
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed === '') {
|
||||
result.push('');
|
||||
} else if (
|
||||
trimmed.startsWith('<h') ||
|
||||
trimmed.startsWith('<pre') ||
|
||||
trimmed.startsWith('<li') ||
|
||||
trimmed.startsWith('<hr')
|
||||
) {
|
||||
result.push(trimmed);
|
||||
} else {
|
||||
result.push(`<p class="text-sm text-text-secondary leading-relaxed my-2">${trimmed}</p>`);
|
||||
}
|
||||
}
|
||||
|
||||
return result.join('\n');
|
||||
}
|
||||
|
||||
export function PrdViewer({ content }: PrdViewerProps): React.ReactElement {
|
||||
const html = renderMarkdown(content);
|
||||
|
||||
return <div className="prose prose-sm max-w-none" dangerouslySetInnerHTML={{ __html: html }} />;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { cn } from '@/lib/cn';
|
||||
import type { Project } from '@/lib/types';
|
||||
|
||||
interface ProjectCardProps {
|
||||
project: Project;
|
||||
onClick: (project: Project) => void;
|
||||
}
|
||||
|
||||
const statusColors: Record<string, string> = {
|
||||
active: 'bg-success/20 text-success',
|
||||
paused: 'bg-warning/20 text-warning',
|
||||
completed: 'bg-blue-600/20 text-blue-400',
|
||||
archived: 'bg-gray-600/20 text-gray-400',
|
||||
};
|
||||
|
||||
export function ProjectCard({ project, onClick }: ProjectCardProps): React.ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onClick(project)}
|
||||
className="w-full rounded-lg border border-surface-border bg-surface-card p-4 text-left transition-colors hover:border-gray-500"
|
||||
>
|
||||
<div className="flex items-start justify-between">
|
||||
<h3 className="text-sm font-medium text-text-primary">{project.name}</h3>
|
||||
<span
|
||||
className={cn(
|
||||
'rounded-full px-2 py-0.5 text-xs',
|
||||
statusColors[project.status] ?? 'bg-gray-600/20 text-gray-400',
|
||||
)}
|
||||
>
|
||||
{project.status}
|
||||
</span>
|
||||
</div>
|
||||
{project.description && (
|
||||
<p className="mt-2 line-clamp-2 text-xs text-text-muted">{project.description}</p>
|
||||
)}
|
||||
<p className="mt-3 text-xs text-text-muted">
|
||||
Created {new Date(project.createdAt).toLocaleDateString()}
|
||||
</p>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import React from 'react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { SsoProviderSection } from './sso-provider-section.js';
|
||||
|
||||
describe('SsoProviderSection', () => {
|
||||
it('renders configured providers with callback, sync, and fallback details', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<SsoProviderSection
|
||||
loading={false}
|
||||
providers={[
|
||||
{
|
||||
id: 'workos',
|
||||
name: 'WorkOS',
|
||||
protocols: ['oidc'],
|
||||
configured: true,
|
||||
loginMode: 'oidc',
|
||||
callbackPath: '/api/auth/oauth2/callback/workos',
|
||||
teamSync: { enabled: true, claim: 'organization_id' },
|
||||
samlFallback: { configured: false, loginUrl: null },
|
||||
warnings: [],
|
||||
},
|
||||
{
|
||||
id: 'keycloak',
|
||||
name: 'Keycloak',
|
||||
protocols: ['oidc', 'saml'],
|
||||
configured: true,
|
||||
loginMode: 'saml',
|
||||
callbackPath: null,
|
||||
teamSync: { enabled: true, claim: 'groups' },
|
||||
samlFallback: {
|
||||
configured: true,
|
||||
loginUrl: 'https://sso.example.com/realms/mosaic/protocol/saml',
|
||||
},
|
||||
warnings: [],
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain('WorkOS');
|
||||
expect(html).toContain('/api/auth/oauth2/callback/workos');
|
||||
expect(html).toContain('Team sync claim: organization_id');
|
||||
expect(html).toContain('SAML fallback: https://sso.example.com/realms/mosaic/protocol/saml');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import React from 'react';
|
||||
import type { SsoProviderDiscovery } from '@/lib/sso';
|
||||
|
||||
interface SsoProviderSectionProps {
|
||||
providers: SsoProviderDiscovery[];
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
export function SsoProviderSection({
|
||||
providers,
|
||||
loading,
|
||||
}: SsoProviderSectionProps): React.ReactElement {
|
||||
if (loading) {
|
||||
return <p className="text-sm text-text-muted">Loading SSO providers...</p>;
|
||||
}
|
||||
|
||||
const configuredProviders = providers.filter((provider) => provider.configured);
|
||||
|
||||
if (providers.length === 0 || configuredProviders.length === 0) {
|
||||
return (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-4">
|
||||
<p className="text-sm text-text-muted">
|
||||
No SSO providers configured. Set WorkOS or Keycloak environment variables to enable SSO.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{configuredProviders.map((provider) => (
|
||||
<div
|
||||
key={provider.id}
|
||||
className="rounded-lg border border-surface-border bg-surface-card p-4"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-text-primary">{provider.name}</h3>
|
||||
<p className="text-xs text-text-muted">
|
||||
{provider.protocols.join(' + ').toUpperCase()}
|
||||
{provider.loginMode ? ` • primary ${provider.loginMode.toUpperCase()}` : ''}
|
||||
</p>
|
||||
</div>
|
||||
<span className="rounded-full border border-accent/30 bg-accent/10 px-2 py-1 text-xs font-medium text-accent">
|
||||
Enabled
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 space-y-2 text-xs text-text-muted">
|
||||
{provider.callbackPath && <p>Callback: {provider.callbackPath}</p>}
|
||||
{provider.teamSync.enabled && provider.teamSync.claim && (
|
||||
<p>Team sync claim: {provider.teamSync.claim}</p>
|
||||
)}
|
||||
{provider.samlFallback.configured && provider.samlFallback.loginUrl && (
|
||||
<p>SAML fallback: {provider.samlFallback.loginUrl}</p>
|
||||
)}
|
||||
{provider.warnings.map((warning) => (
|
||||
<p key={warning} className="text-warning">
|
||||
{warning}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { Task, TaskStatus } from '@/lib/types';
|
||||
import { TaskCard } from './task-card';
|
||||
|
||||
interface KanbanBoardProps {
|
||||
tasks: Task[];
|
||||
onTaskClick: (task: Task) => void;
|
||||
}
|
||||
|
||||
const columns: { id: TaskStatus; label: string }[] = [
|
||||
{ id: 'not-started', label: 'Not Started' },
|
||||
{ id: 'in-progress', label: 'In Progress' },
|
||||
{ id: 'blocked', label: 'Blocked' },
|
||||
{ id: 'done', label: 'Done' },
|
||||
];
|
||||
|
||||
export function KanbanBoard({ tasks, onTaskClick }: KanbanBoardProps): React.ReactElement {
|
||||
return (
|
||||
<div className="flex gap-4 overflow-x-auto pb-4">
|
||||
{columns.map((col) => {
|
||||
const columnTasks = tasks.filter((t) => t.status === col.id);
|
||||
return (
|
||||
<div
|
||||
key={col.id}
|
||||
className="flex w-72 shrink-0 flex-col rounded-lg border border-surface-border bg-surface-elevated"
|
||||
>
|
||||
<div className="flex items-center justify-between border-b border-surface-border px-3 py-2">
|
||||
<h3 className="text-sm font-medium text-text-secondary">{col.label}</h3>
|
||||
<span className="rounded-full bg-surface-card px-2 py-0.5 text-xs text-text-muted">
|
||||
{columnTasks.length}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex-1 space-y-2 p-2">
|
||||
{columnTasks.length === 0 && (
|
||||
<p className="py-4 text-center text-xs text-text-muted">No tasks</p>
|
||||
)}
|
||||
{columnTasks.map((task) => (
|
||||
<TaskCard key={task.id} task={task} onClick={onTaskClick} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { cn } from '@/lib/cn';
|
||||
import type { Task } from '@/lib/types';
|
||||
|
||||
interface TaskCardProps {
|
||||
task: Task;
|
||||
onClick: (task: Task) => void;
|
||||
}
|
||||
|
||||
const priorityColors: Record<string, string> = {
|
||||
critical: 'text-error',
|
||||
high: 'text-warning',
|
||||
medium: 'text-blue-400',
|
||||
low: 'text-text-muted',
|
||||
};
|
||||
|
||||
const statusBadgeColors: Record<string, string> = {
|
||||
'not-started': 'bg-gray-600/20 text-gray-300',
|
||||
'in-progress': 'bg-blue-600/20 text-blue-400',
|
||||
blocked: 'bg-error/20 text-error',
|
||||
done: 'bg-success/20 text-success',
|
||||
cancelled: 'bg-gray-600/20 text-gray-500',
|
||||
};
|
||||
|
||||
export function TaskCard({ task, onClick }: TaskCardProps): React.ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onClick(task)}
|
||||
className="w-full rounded-lg border border-surface-border bg-surface-card p-3 text-left transition-colors hover:border-gray-500"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<span className="text-sm font-medium text-text-primary">{task.title}</span>
|
||||
<span className={cn('text-xs', priorityColors[task.priority])}>{task.priority}</span>
|
||||
</div>
|
||||
{task.description && (
|
||||
<p className="mt-1 line-clamp-2 text-xs text-text-muted">{task.description}</p>
|
||||
)}
|
||||
<div className="mt-2 flex items-center gap-2">
|
||||
<span
|
||||
className={cn(
|
||||
'rounded-full px-2 py-0.5 text-xs',
|
||||
statusBadgeColors[task.status] ?? 'bg-gray-600/20 text-gray-400',
|
||||
)}
|
||||
>
|
||||
{task.status}
|
||||
</span>
|
||||
{task.dueDate && (
|
||||
<span className="text-xs text-text-muted">
|
||||
{new Date(task.dueDate).toLocaleDateString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { cn } from '@/lib/cn';
|
||||
import type { Task } from '@/lib/types';
|
||||
|
||||
interface TaskDetailModalProps {
|
||||
task: Task;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const priorityColors: Record<string, string> = {
|
||||
critical: 'text-error',
|
||||
high: 'text-warning',
|
||||
medium: 'text-blue-400',
|
||||
low: 'text-text-muted',
|
||||
};
|
||||
|
||||
const statusBadgeColors: Record<string, string> = {
|
||||
'not-started': 'bg-gray-600/20 text-gray-300',
|
||||
'in-progress': 'bg-blue-600/20 text-blue-400',
|
||||
blocked: 'bg-error/20 text-error',
|
||||
done: 'bg-success/20 text-success',
|
||||
cancelled: 'bg-gray-600/20 text-gray-500',
|
||||
};
|
||||
|
||||
function DetailRow({
|
||||
label,
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
children: ReactNode;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<div className="flex gap-2 py-2 text-sm">
|
||||
<span className="w-24 shrink-0 text-text-muted">{label}</span>
|
||||
<span className="text-text-primary">{children}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TaskDetailModal({ task, onClose }: TaskDetailModalProps): React.ReactElement {
|
||||
const dialogRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
function handleKeyDown(e: KeyboardEvent): void {
|
||||
if (e.key === 'Escape') onClose();
|
||||
}
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||
}, [onClose]);
|
||||
|
||||
// Trap focus on mount
|
||||
useEffect(() => {
|
||||
dialogRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
const prLinks = extractPrLinks(task.metadata);
|
||||
|
||||
return (
|
||||
/* backdrop */
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) onClose();
|
||||
}}
|
||||
role="presentation"
|
||||
>
|
||||
<div
|
||||
ref={dialogRef}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="task-detail-title"
|
||||
tabIndex={-1}
|
||||
className="flex max-h-[90vh] w-full max-w-lg flex-col overflow-hidden rounded-xl border border-surface-border bg-surface-card outline-none"
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex items-start justify-between gap-3 border-b border-surface-border p-4">
|
||||
<h2 id="task-detail-title" className="text-base font-semibold text-text-primary">
|
||||
{task.title}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="Close task details"
|
||||
className="shrink-0 rounded p-1 text-text-muted hover:text-text-primary"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
{/* Badges */}
|
||||
<div className="mb-4 flex flex-wrap gap-2">
|
||||
<span
|
||||
className={cn(
|
||||
'rounded-full px-2 py-0.5 text-xs',
|
||||
statusBadgeColors[task.status] ?? 'bg-gray-600/20 text-gray-400',
|
||||
)}
|
||||
>
|
||||
{task.status}
|
||||
</span>
|
||||
<span className={cn('text-xs', priorityColors[task.priority])}>
|
||||
{task.priority} priority
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
{task.description && (
|
||||
<div className="mb-4 rounded-lg bg-surface-elevated p-3">
|
||||
<p className="text-sm text-text-secondary">{task.description}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Details */}
|
||||
<div className="divide-y divide-surface-border rounded-lg border border-surface-border px-3">
|
||||
{task.assignee ? <DetailRow label="Assignee">{task.assignee}</DetailRow> : null}
|
||||
{task.dueDate ? (
|
||||
<DetailRow label="Due date">
|
||||
{new Date(task.dueDate).toLocaleDateString(undefined, {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
})}
|
||||
</DetailRow>
|
||||
) : null}
|
||||
<DetailRow label="Created">
|
||||
{new Date(task.createdAt).toLocaleDateString(undefined, {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
})}
|
||||
</DetailRow>
|
||||
<DetailRow label="Updated">
|
||||
{new Date(task.updatedAt).toLocaleDateString(undefined, {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
})}
|
||||
</DetailRow>
|
||||
</div>
|
||||
|
||||
{/* Tags */}
|
||||
{task.tags != null && task.tags.length > 0 ? (
|
||||
<div className="mt-4">
|
||||
<p className="mb-2 text-xs text-text-muted">Tags</p>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{task.tags.map((tag) => (
|
||||
<span
|
||||
key={tag}
|
||||
className="rounded-full bg-surface-elevated px-2 py-0.5 text-xs text-text-secondary"
|
||||
>
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* PR Links */}
|
||||
{prLinks.length > 0 ? (
|
||||
<div className="mt-4">
|
||||
<p className="mb-2 text-xs text-text-muted">Pull Requests</p>
|
||||
<ul className="space-y-1">
|
||||
{prLinks.map((link) => (
|
||||
<li key={link.url}>
|
||||
<a
|
||||
href={link.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs text-blue-400 underline hover:text-blue-300"
|
||||
>
|
||||
{link.label ?? link.url}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Notes from metadata */}
|
||||
<NotesSection notes={getNotesString(task.metadata)} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface PrLink {
|
||||
url: string;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
function extractPrLinks(metadata: Record<string, unknown> | null): PrLink[] {
|
||||
if (!metadata) return [];
|
||||
|
||||
const raw = metadata['pr_links'] ?? metadata['prLinks'];
|
||||
if (!Array.isArray(raw)) return [];
|
||||
|
||||
return raw
|
||||
.filter((item): item is PrLink => {
|
||||
if (typeof item === 'string') return true;
|
||||
if (typeof item === 'object' && item !== null && 'url' in item) return true;
|
||||
return false;
|
||||
})
|
||||
.map((item): PrLink => {
|
||||
if (typeof item === 'string') return { url: item };
|
||||
return item as PrLink;
|
||||
});
|
||||
}
|
||||
|
||||
function getNotesString(metadata: Record<string, unknown> | null): string | null {
|
||||
if (!metadata) return null;
|
||||
const notes = metadata['notes'];
|
||||
if (typeof notes === 'string' && notes.trim().length > 0) return notes;
|
||||
return null;
|
||||
}
|
||||
|
||||
function NotesSection({ notes }: { notes: string | null }): React.ReactElement | null {
|
||||
if (!notes) return null;
|
||||
return (
|
||||
<div className="mt-4">
|
||||
<p className="mb-2 text-xs text-text-muted">Notes</p>
|
||||
<div className="rounded-lg bg-surface-elevated p-3">
|
||||
<p className="whitespace-pre-wrap text-xs text-text-secondary">{notes}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { cn } from '@/lib/cn';
|
||||
import type { Task } from '@/lib/types';
|
||||
|
||||
interface TaskListViewProps {
|
||||
tasks: Task[];
|
||||
onTaskClick: (task: Task) => void;
|
||||
}
|
||||
|
||||
const priorityColors: Record<string, string> = {
|
||||
critical: 'text-error',
|
||||
high: 'text-warning',
|
||||
medium: 'text-blue-400',
|
||||
low: 'text-text-muted',
|
||||
};
|
||||
|
||||
const statusColors: Record<string, string> = {
|
||||
'not-started': 'text-gray-400',
|
||||
'in-progress': 'text-blue-400',
|
||||
blocked: 'text-error',
|
||||
done: 'text-success',
|
||||
cancelled: 'text-gray-500',
|
||||
};
|
||||
|
||||
export function TaskListView({ tasks, onTaskClick }: TaskListViewProps): React.ReactElement {
|
||||
if (tasks.length === 0) {
|
||||
return <p className="py-8 text-center text-sm text-text-muted">No tasks found</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="overflow-hidden rounded-lg border border-surface-border">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr className="border-b border-surface-border bg-surface-elevated text-left text-xs text-text-muted">
|
||||
<th className="px-4 py-2 font-medium">Title</th>
|
||||
<th className="px-4 py-2 font-medium">Status</th>
|
||||
<th className="px-4 py-2 font-medium">Priority</th>
|
||||
<th className="hidden px-4 py-2 font-medium md:table-cell">Due</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{tasks.map((task) => (
|
||||
<tr
|
||||
key={task.id}
|
||||
onClick={() => onTaskClick(task)}
|
||||
className="cursor-pointer border-b border-surface-border transition-colors last:border-b-0 hover:bg-surface-elevated"
|
||||
>
|
||||
<td className="px-4 py-3 text-sm text-text-primary">{task.title}</td>
|
||||
<td className="px-4 py-3">
|
||||
<span className={cn('text-xs', statusColors[task.status])}>{task.status}</span>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<span className={cn('text-xs', priorityColors[task.priority])}>
|
||||
{task.priority}
|
||||
</span>
|
||||
</td>
|
||||
<td className="hidden px-4 py-3 text-xs text-text-muted md:table-cell">
|
||||
{task.dueDate ? new Date(task.dueDate).toLocaleDateString() : '—'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { cn } from '@/lib/cn';
|
||||
import type { Task, TaskStatus } from '@/lib/types';
|
||||
|
||||
interface TaskStatusSummaryProps {
|
||||
tasks: Task[];
|
||||
activeFilter: TaskStatus | 'all';
|
||||
onFilterChange: (filter: TaskStatus | 'all') => void;
|
||||
}
|
||||
|
||||
const statusConfig: {
|
||||
id: TaskStatus | 'all';
|
||||
label: string;
|
||||
color: string;
|
||||
activeColor: string;
|
||||
}[] = [
|
||||
{
|
||||
id: 'all',
|
||||
label: 'All',
|
||||
color: 'text-text-muted',
|
||||
activeColor: 'bg-surface-elevated text-text-primary',
|
||||
},
|
||||
{
|
||||
id: 'not-started',
|
||||
label: 'Not Started',
|
||||
color: 'text-gray-400',
|
||||
activeColor: 'bg-gray-600/20 text-gray-300',
|
||||
},
|
||||
{
|
||||
id: 'in-progress',
|
||||
label: 'In Progress',
|
||||
color: 'text-blue-400',
|
||||
activeColor: 'bg-blue-600/20 text-blue-400',
|
||||
},
|
||||
{
|
||||
id: 'blocked',
|
||||
label: 'Blocked',
|
||||
color: 'text-error',
|
||||
activeColor: 'bg-error/20 text-error',
|
||||
},
|
||||
{
|
||||
id: 'done',
|
||||
label: 'Done',
|
||||
color: 'text-success',
|
||||
activeColor: 'bg-success/20 text-success',
|
||||
},
|
||||
];
|
||||
|
||||
export function TaskStatusSummary({
|
||||
tasks,
|
||||
activeFilter,
|
||||
onFilterChange,
|
||||
}: TaskStatusSummaryProps): React.ReactElement {
|
||||
const counts: Record<TaskStatus | 'all', number> = {
|
||||
all: tasks.length,
|
||||
'not-started': 0,
|
||||
'in-progress': 0,
|
||||
blocked: 0,
|
||||
done: 0,
|
||||
cancelled: 0,
|
||||
};
|
||||
|
||||
for (const task of tasks) {
|
||||
counts[task.status] = (counts[task.status] ?? 0) + 1;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{statusConfig.map((config) => {
|
||||
const count = counts[config.id];
|
||||
const isActive = activeFilter === config.id;
|
||||
return (
|
||||
<button
|
||||
key={config.id}
|
||||
type="button"
|
||||
onClick={() => onFilterChange(config.id)}
|
||||
className={cn(
|
||||
'flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs transition-colors',
|
||||
isActive
|
||||
? cn('border-transparent', config.activeColor)
|
||||
: 'border-surface-border text-text-muted hover:border-gray-500',
|
||||
)}
|
||||
>
|
||||
<span>{config.label}</span>
|
||||
<span
|
||||
className={cn(
|
||||
'rounded-full px-1.5 py-0.5 text-xs font-medium',
|
||||
isActive ? 'bg-black/20' : 'bg-surface-elevated',
|
||||
)}
|
||||
>
|
||||
{count}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { CSSProperties } from 'react';
|
||||
|
||||
export interface MosaicLogoProps {
|
||||
size?: number;
|
||||
spinning?: boolean;
|
||||
spinDuration?: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function MosaicLogo({
|
||||
size = 36,
|
||||
spinning = false,
|
||||
spinDuration = 20,
|
||||
className = '',
|
||||
}: MosaicLogoProps): React.JSX.Element {
|
||||
const scale = size / 36;
|
||||
const squareSize = Math.round(14 * scale);
|
||||
const circleSize = Math.round(11 * scale);
|
||||
const borderRadius = Math.round(3 * scale);
|
||||
|
||||
const animationValue = spinning
|
||||
? `mosaicLogoSpin ${String(spinDuration)}s linear infinite`
|
||||
: undefined;
|
||||
|
||||
const containerStyle: CSSProperties = {
|
||||
width: size,
|
||||
height: size,
|
||||
position: 'relative',
|
||||
flexShrink: 0,
|
||||
animation: animationValue,
|
||||
transformOrigin: 'center',
|
||||
};
|
||||
|
||||
const baseSquareStyle: CSSProperties = {
|
||||
position: 'absolute',
|
||||
width: squareSize,
|
||||
height: squareSize,
|
||||
borderRadius,
|
||||
};
|
||||
|
||||
const circleStyle: CSSProperties = {
|
||||
position: 'absolute',
|
||||
top: '50%',
|
||||
left: '50%',
|
||||
transform: 'translate(-50%, -50%)',
|
||||
width: circleSize,
|
||||
height: circleSize,
|
||||
borderRadius: '50%',
|
||||
background: 'var(--ms-pink-500)',
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{spinning ? (
|
||||
<style>{`
|
||||
@keyframes mosaicLogoSpin {
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
`}</style>
|
||||
) : null}
|
||||
<div style={containerStyle} className={className} role="img" aria-label="Mosaic logo">
|
||||
<div style={{ ...baseSquareStyle, top: 0, left: 0, background: 'var(--ms-blue-500)' }} />
|
||||
<div style={{ ...baseSquareStyle, top: 0, right: 0, background: 'var(--ms-purple-500)' }} />
|
||||
<div
|
||||
style={{
|
||||
...baseSquareStyle,
|
||||
bottom: 0,
|
||||
right: 0,
|
||||
background: 'var(--ms-teal-500)',
|
||||
}}
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
...baseSquareStyle,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
background: 'var(--ms-amber-500)',
|
||||
}}
|
||||
/>
|
||||
<div style={circleStyle} />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default MosaicLogo;
|
||||
@@ -0,0 +1,286 @@
|
||||
@import 'tailwindcss';
|
||||
|
||||
/* =============================================================================
|
||||
MOSAIC DESIGN SYSTEM — Reference token system from dashboard design
|
||||
============================================================================= */
|
||||
|
||||
/* -----------------------------------------------------------------------------
|
||||
Primitive Tokens (Dark-first — dark is the default theme)
|
||||
----------------------------------------------------------------------------- */
|
||||
:root {
|
||||
/* Mosaic design tokens — dark palette (default) */
|
||||
--ms-bg-950: #080b12;
|
||||
--ms-bg-900: #0f141d;
|
||||
--ms-bg-850: #151b26;
|
||||
--ms-surface-800: #1b2331;
|
||||
--ms-surface-750: #232d3f;
|
||||
--ms-border-700: #2f3b52;
|
||||
--ms-text-100: #eef3ff;
|
||||
--ms-text-300: #c5d0e6;
|
||||
--ms-text-500: #8f9db7;
|
||||
--ms-blue-500: #2f80ff;
|
||||
--ms-blue-400: #56a0ff;
|
||||
--ms-red-500: #e5484d;
|
||||
--ms-red-400: #f06a6f;
|
||||
--ms-purple-500: #8b5cf6;
|
||||
--ms-purple-400: #a78bfa;
|
||||
--ms-teal-500: #14b8a6;
|
||||
--ms-teal-400: #2dd4bf;
|
||||
--ms-amber-500: #f59e0b;
|
||||
--ms-amber-400: #fbbf24;
|
||||
--ms-pink-500: #ec4899;
|
||||
--ms-emerald-500: #10b981;
|
||||
--ms-orange-500: #f97316;
|
||||
--ms-cyan-500: #06b6d4;
|
||||
--ms-indigo-500: #6366f1;
|
||||
|
||||
/* Semantic aliases — dark theme is default */
|
||||
--bg: var(--ms-bg-900);
|
||||
--bg-deep: var(--ms-bg-950);
|
||||
--bg-mid: var(--ms-bg-850);
|
||||
--surface: var(--ms-surface-800);
|
||||
--surface-2: var(--ms-surface-750);
|
||||
--border: var(--ms-border-700);
|
||||
--text: var(--ms-text-100);
|
||||
--text-2: var(--ms-text-300);
|
||||
--muted: var(--ms-text-500);
|
||||
--primary: var(--ms-blue-500);
|
||||
--primary-l: var(--ms-blue-400);
|
||||
--danger: var(--ms-red-500);
|
||||
--success: var(--ms-teal-500);
|
||||
--warn: var(--ms-amber-500);
|
||||
--purple: var(--ms-purple-500);
|
||||
|
||||
/* Typography */
|
||||
--font: var(--font-outfit, 'Outfit'), system-ui, sans-serif;
|
||||
--mono: var(--font-fira-code, 'Fira Code'), 'Cascadia Code', monospace;
|
||||
|
||||
/* Radius scale */
|
||||
--r: 8px;
|
||||
--r-sm: 5px;
|
||||
--r-lg: 12px;
|
||||
--r-xl: 16px;
|
||||
|
||||
/* Layout dimensions */
|
||||
--sidebar-w: 260px;
|
||||
--topbar-h: 56px;
|
||||
--terminal-h: 220px;
|
||||
|
||||
/* Easing */
|
||||
--ease: cubic-bezier(0.16, 1, 0.3, 1);
|
||||
|
||||
/* Legacy shadow tokens (retained for component compat) */
|
||||
--shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.3);
|
||||
--shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.4), 0 2px 4px -2px rgb(0 0 0 / 0.3);
|
||||
--shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.5), 0 4px 6px -4px rgb(0 0 0 / 0.4);
|
||||
}
|
||||
|
||||
[data-theme='light'] {
|
||||
--ms-bg-950: #f8faff;
|
||||
--ms-bg-900: #f0f4fc;
|
||||
--ms-bg-850: #e8edf8;
|
||||
--ms-surface-800: #dde4f2;
|
||||
--ms-surface-750: #d0d9ec;
|
||||
--ms-border-700: #b8c4de;
|
||||
--ms-text-100: #0f141d;
|
||||
--ms-text-300: #2f3b52;
|
||||
--ms-text-500: #5a6a87;
|
||||
--bg: var(--ms-bg-900);
|
||||
--bg-deep: var(--ms-bg-950);
|
||||
--bg-mid: var(--ms-bg-850);
|
||||
--surface: var(--ms-surface-800);
|
||||
--surface-2: var(--ms-surface-750);
|
||||
--border: var(--ms-border-700);
|
||||
--text: var(--ms-text-100);
|
||||
--text-2: var(--ms-text-300);
|
||||
--muted: var(--ms-text-500);
|
||||
--shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05), 0 1px 3px 0 rgb(0 0 0 / 0.05);
|
||||
--shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.08), 0 2px 4px -2px rgb(0 0 0 / 0.06);
|
||||
--shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.08);
|
||||
}
|
||||
|
||||
@theme {
|
||||
--font-sans: var(--font);
|
||||
--font-mono: var(--mono);
|
||||
--color-surface-bg: var(--bg);
|
||||
--color-surface-card: var(--surface);
|
||||
--color-surface-elevated: var(--surface-2);
|
||||
--color-surface-border: var(--border);
|
||||
--color-text-primary: var(--text);
|
||||
--color-text-secondary: var(--text-2);
|
||||
--color-text-muted: var(--muted);
|
||||
--color-accent: var(--primary);
|
||||
--color-success: var(--success);
|
||||
--color-warning: var(--warn);
|
||||
--color-error: var(--danger);
|
||||
--color-info: var(--primary-l);
|
||||
--spacing-sidebar: var(--sidebar-w);
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html {
|
||||
font-size: 15px;
|
||||
font-feature-settings: 'cv02', 'cv03', 'cv04', 'cv11';
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: var(--font);
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
button {
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
background: none;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
ul {
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
body::before {
|
||||
content: '';
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
z-index: 9999;
|
||||
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='1'/%3E%3C/svg%3E");
|
||||
opacity: 0.025;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--ms-blue-400);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
:focus:not(:focus-visible) {
|
||||
outline: none;
|
||||
}
|
||||
}
|
||||
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: var(--border);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--muted);
|
||||
}
|
||||
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--border) transparent;
|
||||
}
|
||||
|
||||
.app-shell {
|
||||
display: grid;
|
||||
grid-template-columns: var(--sidebar-w) 1fr;
|
||||
grid-template-rows: var(--topbar-h) 1fr;
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.app-header {
|
||||
grid-column: 1 / -1;
|
||||
grid-row: 1;
|
||||
background: var(--bg-deep);
|
||||
border-bottom: 1px solid var(--border);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 20px;
|
||||
gap: 12px;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
.app-sidebar {
|
||||
grid-column: 1;
|
||||
grid-row: 2;
|
||||
background: var(--bg-deep);
|
||||
border-right: 1px solid var(--border);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.app-main {
|
||||
grid-column: 2;
|
||||
grid-row: 2;
|
||||
background: var(--bg);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.app-shell {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.app-sidebar {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
top: var(--topbar-h);
|
||||
bottom: 0;
|
||||
width: 240px;
|
||||
z-index: 150;
|
||||
transform: translateX(-100%);
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
.app-sidebar[data-mobile-open='true'] {
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
.app-main,
|
||||
.app-header {
|
||||
grid-column: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 768px) and (max-width: 1023px) {
|
||||
.app-shell[data-sidebar-hidden='true'] {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.app-shell[data-sidebar-hidden='true'] .app-sidebar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.app-shell[data-sidebar-hidden='true'] .app-main,
|
||||
.app-shell[data-sidebar-hidden='true'] .app-header {
|
||||
grid-column: 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { api } from './api';
|
||||
|
||||
describe('api', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('fetches the supplied relative path with credentials and a JSON body', async () => {
|
||||
const fetchMock = vi.fn<typeof fetch>();
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ ok: true }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(
|
||||
api<{ ok: boolean }>('/api/projects', {
|
||||
method: 'POST',
|
||||
body: { name: 'Mosaic' },
|
||||
}),
|
||||
).resolves.toEqual({ ok: true });
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/projects',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ name: 'Mosaic' }),
|
||||
headers: expect.objectContaining({
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('throws the gateway JSON error with its statusCode', async () => {
|
||||
const fetchMock = vi.fn<typeof fetch>();
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ statusCode: 403, message: 'Forbidden' }), {
|
||||
status: 403,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(api('/api/admin/users')).rejects.toMatchObject({
|
||||
name: 'Error',
|
||||
message: 'Forbidden',
|
||||
statusCode: 403,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
export interface ApiRequestInit extends Omit<RequestInit, 'body'> {
|
||||
body?: unknown;
|
||||
}
|
||||
|
||||
export interface ApiError {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch wrapper for the Mosaic gateway API.
|
||||
* Sends credentials (cookies) and JSON body automatically.
|
||||
*/
|
||||
export async function api<T>(path: string, init?: ApiRequestInit): Promise<T> {
|
||||
const { body, headers: customHeaders, ...rest } = init ?? {};
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
Accept: 'application/json',
|
||||
...(customHeaders as Record<string, string>),
|
||||
};
|
||||
|
||||
if (body !== undefined) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
|
||||
const res = await fetch(path, {
|
||||
credentials: 'include',
|
||||
...rest,
|
||||
headers,
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorBody = (await res.json().catch(() => ({
|
||||
statusCode: res.status,
|
||||
message: res.statusText,
|
||||
}))) as ApiError;
|
||||
throw Object.assign(new Error(errorBody.message), {
|
||||
statusCode: errorBody.statusCode,
|
||||
});
|
||||
}
|
||||
|
||||
if (res.status === 204) return undefined as T;
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
describe('auth client origin contract', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it('uses the same-origin BetterAuth mount at /api/auth', async () => {
|
||||
const fetchMock = vi.fn<typeof fetch>();
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ session: null, user: null }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const { authClient } = await import('./auth-client');
|
||||
await authClient.getSession();
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
const firstCall = fetchMock.mock.calls.at(0);
|
||||
expect(firstCall).toBeDefined();
|
||||
const requestURL = new URL(String(firstCall?.[0]), window.location.origin);
|
||||
expect(requestURL.origin).toBe(window.location.origin);
|
||||
expect(requestURL.pathname).toBe('/api/auth/get-session');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import { createAuthClient } from 'better-auth/react';
|
||||
import { adminClient, genericOAuthClient } from 'better-auth/client/plugins';
|
||||
|
||||
// The gateway and BetterAuth client both use /api/auth. Omitting baseURL keeps
|
||||
// every browser request on the current origin in development and production.
|
||||
export const authClient = createAuthClient({
|
||||
plugins: [adminClient(), genericOAuthClient()],
|
||||
});
|
||||
|
||||
export const { useSession, signIn, signUp, signOut } = authClient;
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { resolveAuthCallbackURL } from './auth-redirect';
|
||||
|
||||
const CURRENT_ORIGIN = 'https://mosaic.example';
|
||||
|
||||
describe('resolveAuthCallbackURL', () => {
|
||||
it('preserves a canonical same-origin path with search and hash', () => {
|
||||
expect(resolveAuthCallbackURL('/projects?view=active#current', CURRENT_ORIGIN)).toBe(
|
||||
'/projects?view=active#current',
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
null,
|
||||
'chat',
|
||||
'//evil.example',
|
||||
'/..//evil.com',
|
||||
'/..//evil.com/x',
|
||||
'/./..//evil.com',
|
||||
'/../..//evil.com',
|
||||
'/foo/..//evil.com',
|
||||
'/\\evil.example',
|
||||
'/\n//evil.example',
|
||||
'/\r//evil.example',
|
||||
'/\t//evil.example',
|
||||
'https://evil.example/phish',
|
||||
])('falls back to chat for an unsafe callback target %#', (candidate) => {
|
||||
expect(resolveAuthCallbackURL(candidate, CURRENT_ORIGIN)).toBe('/chat');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
const DEFAULT_AUTH_CALLBACK_URL = '/chat';
|
||||
|
||||
/**
|
||||
* Return a canonical same-origin path for post-auth navigation.
|
||||
*
|
||||
* Parsing before comparing origins rejects protocol-relative URLs, backslash
|
||||
* variants, and control characters that the WHATWG parser normalizes away.
|
||||
*/
|
||||
export function resolveAuthCallbackURL(candidate: string | null, currentOrigin: string): string {
|
||||
if (!candidate?.startsWith('/')) return DEFAULT_AUTH_CALLBACK_URL;
|
||||
|
||||
try {
|
||||
const expectedOrigin = new URL(currentOrigin).origin;
|
||||
const resolved = new URL(candidate, expectedOrigin);
|
||||
if (resolved.origin !== expectedOrigin || resolved.pathname.startsWith('//')) {
|
||||
return DEFAULT_AUTH_CALLBACK_URL;
|
||||
}
|
||||
|
||||
return `${resolved.pathname}${resolved.search}${resolved.hash}`;
|
||||
} catch {
|
||||
return DEFAULT_AUTH_CALLBACK_URL;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
// Centralizes the type-only import of the shared `/chat` Socket.IO contract from
|
||||
// the public `@mosaicstack/types` package. `import type` is erased at compile
|
||||
// time, so this introduces no runtime dependency — it only reuses the exact
|
||||
// payload shapes instead of redeclaring them.
|
||||
import type { Socket } from 'socket.io-client';
|
||||
import type {
|
||||
AbortPayload,
|
||||
AgentEndPayload,
|
||||
AgentStartPayload,
|
||||
AgentTextPayload,
|
||||
AgentThinkingPayload,
|
||||
ChatMessagePayload,
|
||||
ChatSendCapabilityPayload,
|
||||
ChatSendProtocol,
|
||||
ClientToServerEvents,
|
||||
CommandDef,
|
||||
CommandManifest,
|
||||
CommandManifestPayload,
|
||||
ErrorPayload,
|
||||
HarnessSelection,
|
||||
HarnessTurnAckPayload,
|
||||
HarnessTurnSendPayload,
|
||||
MessageAckPayload,
|
||||
RoutingDecisionInfo,
|
||||
ServerToClientEvents,
|
||||
SessionInfoPayload,
|
||||
SessionUsagePayload,
|
||||
SetThinkingPayload,
|
||||
SkillCommandDef,
|
||||
SlashCommandApprovalResultPayload,
|
||||
SlashCommandPayload,
|
||||
SlashCommandResultPayload,
|
||||
SystemReloadPayload,
|
||||
ToolEndPayload,
|
||||
ToolStartPayload,
|
||||
} from '@mosaicstack/types';
|
||||
|
||||
export type {
|
||||
AbortPayload,
|
||||
AgentEndPayload,
|
||||
AgentStartPayload,
|
||||
AgentTextPayload,
|
||||
AgentThinkingPayload,
|
||||
ChatMessagePayload,
|
||||
ChatSendCapabilityPayload,
|
||||
ChatSendProtocol,
|
||||
ClientToServerEvents,
|
||||
CommandDef,
|
||||
CommandManifest,
|
||||
CommandManifestPayload,
|
||||
ErrorPayload,
|
||||
HarnessSelection,
|
||||
HarnessTurnAckPayload,
|
||||
HarnessTurnSendPayload,
|
||||
MessageAckPayload,
|
||||
RoutingDecisionInfo,
|
||||
ServerToClientEvents,
|
||||
SessionInfoPayload,
|
||||
SessionUsagePayload,
|
||||
SetThinkingPayload,
|
||||
SkillCommandDef,
|
||||
SlashCommandApprovalResultPayload,
|
||||
SlashCommandPayload,
|
||||
SlashCommandResultPayload,
|
||||
SystemReloadPayload,
|
||||
ToolEndPayload,
|
||||
ToolStartPayload,
|
||||
};
|
||||
|
||||
/** The `/chat` namespace socket, narrowed to the exact typed event contract. */
|
||||
export type ChatSocket = Socket<ServerToClientEvents, ClientToServerEvents>;
|
||||
@@ -0,0 +1,7 @@
|
||||
import { clsx, type ClassValue } from 'clsx';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
|
||||
/** Merge and deduplicate Tailwind class names. */
|
||||
export function cn(...inputs: ClassValue[]): string {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { Task } from '@/lib/types';
|
||||
import {
|
||||
acceptSnapshot,
|
||||
assertMutable,
|
||||
canMutate,
|
||||
combineFreshness,
|
||||
computeDigest,
|
||||
computeFreshness,
|
||||
DEFAULT_FRESHNESS_POLICY,
|
||||
formatAge,
|
||||
type FreshSnapshot,
|
||||
invalidationReasonLabels,
|
||||
StaleMutationError,
|
||||
UNKNOWN_VERDICT,
|
||||
verdictValue,
|
||||
} from './model';
|
||||
import { validateProjectCollection, validateTaskCollection } from './validators';
|
||||
|
||||
const NOW = 1_800_000_000_000;
|
||||
|
||||
const policy = { ...DEFAULT_FRESHNESS_POLICY, staleAfterMs: 60_000 };
|
||||
|
||||
const taskPayload: Task[] = [
|
||||
{
|
||||
id: 'task-1',
|
||||
title: 'T1',
|
||||
description: null,
|
||||
status: 'not-started',
|
||||
priority: 'high',
|
||||
projectId: 'project-1',
|
||||
missionId: null,
|
||||
assignee: null,
|
||||
tags: null,
|
||||
dueDate: null,
|
||||
metadata: null,
|
||||
createdAt: '2026-08-01T00:00:00.000Z',
|
||||
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||
},
|
||||
];
|
||||
|
||||
function acceptedTaskSnapshot(
|
||||
overrides: Partial<FreshSnapshot<typeof taskPayload>> = {},
|
||||
): FreshSnapshot<typeof taskPayload> {
|
||||
const result = acceptSnapshot({
|
||||
value: taskPayload,
|
||||
validate: validateTaskCollection,
|
||||
previous: null,
|
||||
policy,
|
||||
source: 'gateway:/api/tasks',
|
||||
now: NOW,
|
||||
});
|
||||
if (result.outcome !== 'accepted') {
|
||||
throw new Error(`fixture setup failed: ${result.reason}`);
|
||||
}
|
||||
return { ...result.snapshot, ...overrides };
|
||||
}
|
||||
|
||||
describe('computeFreshness', () => {
|
||||
it('treats a missing snapshot as unavailable, never as an empty healthy collection', () => {
|
||||
expect(computeFreshness({ snapshot: null, policy, now: NOW })).toBe('unavailable');
|
||||
});
|
||||
|
||||
it('returns current for a fresh verified snapshot regardless of data emptiness', () => {
|
||||
const empty = acceptSnapshot({
|
||||
value: [],
|
||||
validate: validateTaskCollection,
|
||||
previous: null,
|
||||
policy,
|
||||
source: 'gateway:/api/tasks',
|
||||
now: NOW,
|
||||
});
|
||||
if (empty.outcome !== 'accepted') throw new Error('expected acceptance');
|
||||
expect(computeFreshness({ snapshot: empty.snapshot, policy, now: NOW })).toBe('current');
|
||||
});
|
||||
|
||||
it('degrades to stale once the snapshot ages past staleAfterMs', () => {
|
||||
const snapshot = acceptedTaskSnapshot();
|
||||
expect(computeFreshness({ snapshot, policy, now: NOW + 60_001 })).toBe('stale');
|
||||
expect(computeFreshness({ snapshot, policy, now: NOW + 59_999 })).toBe('current');
|
||||
});
|
||||
|
||||
it('degrades to stale when the latest revalidation failed', () => {
|
||||
const snapshot = acceptedTaskSnapshot();
|
||||
expect(computeFreshness({ snapshot, policy, now: NOW, degraded: true })).toBe('stale');
|
||||
});
|
||||
});
|
||||
|
||||
describe('mutation guard', () => {
|
||||
it('permits mutations only on current data', () => {
|
||||
expect(canMutate('current')).toBe(true);
|
||||
for (const state of ['stale', 'partial', 'unknown', 'unavailable'] as const) {
|
||||
expect(canMutate(state)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses mutations on non-current data via assertMutable', () => {
|
||||
expect(() => assertMutable('current')).not.toThrow();
|
||||
for (const state of ['stale', 'partial', 'unknown', 'unavailable'] as const) {
|
||||
let thrown: unknown;
|
||||
try {
|
||||
assertMutable(state);
|
||||
} catch (caught) {
|
||||
thrown = caught;
|
||||
}
|
||||
expect(thrown).toBeInstanceOf(StaleMutationError);
|
||||
expect(thrown).toBeInstanceOf(Error);
|
||||
if (thrown instanceof StaleMutationError) {
|
||||
expect(thrown.name).toBe('StaleMutationError');
|
||||
expect(thrown.freshness).toBe(state);
|
||||
expect(thrown.message).toContain(state);
|
||||
expect(thrown.message).toContain('revalidat');
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('acceptSnapshot', () => {
|
||||
it('accepts a valid payload with provenance', () => {
|
||||
const result = acceptSnapshot({
|
||||
value: taskPayload,
|
||||
validate: validateTaskCollection,
|
||||
previous: null,
|
||||
policy,
|
||||
source: 'gateway:/api/tasks',
|
||||
now: NOW,
|
||||
});
|
||||
expect(result.outcome).toBe('accepted');
|
||||
if (result.outcome !== 'accepted') return;
|
||||
expect(result.snapshot.source).toBe('gateway:/api/tasks');
|
||||
expect(result.snapshot.version).toBe(1);
|
||||
expect(result.snapshot.fetchedAt).toBe(NOW);
|
||||
expect(result.snapshot.data).toEqual(taskPayload);
|
||||
});
|
||||
|
||||
it('invalidates a schema-mismatched payload instead of rendering it', () => {
|
||||
const result = acceptSnapshot({
|
||||
value: { not: 'an array' },
|
||||
validate: validateTaskCollection,
|
||||
previous: acceptedTaskSnapshot(),
|
||||
policy,
|
||||
source: 'gateway:/api/tasks',
|
||||
now: NOW,
|
||||
});
|
||||
expect(result).toEqual({ outcome: 'invalidated', reason: 'schema-mismatch' });
|
||||
expect(invalidationReasonLabels['schema-mismatch']).toContain('schema');
|
||||
});
|
||||
|
||||
it('invalidates cross-workspace payloads', () => {
|
||||
const userOne = acceptSnapshot({
|
||||
value: [
|
||||
{
|
||||
id: 'p1',
|
||||
name: 'P1',
|
||||
description: null,
|
||||
status: 'active',
|
||||
userId: 'user-1',
|
||||
metadata: null,
|
||||
createdAt: '2026-08-01T00:00:00.000Z',
|
||||
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||
},
|
||||
],
|
||||
validate: validateProjectCollection,
|
||||
previous: null,
|
||||
policy,
|
||||
source: 'gateway:/api/projects',
|
||||
now: NOW,
|
||||
});
|
||||
if (userOne.outcome !== 'accepted') throw new Error('expected acceptance');
|
||||
|
||||
const switched = acceptSnapshot({
|
||||
value: [
|
||||
{
|
||||
id: 'p9',
|
||||
name: 'P9',
|
||||
description: null,
|
||||
status: 'active',
|
||||
userId: 'user-2',
|
||||
metadata: null,
|
||||
createdAt: '2026-08-01T00:00:00.000Z',
|
||||
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||
},
|
||||
],
|
||||
validate: validateProjectCollection,
|
||||
previous: userOne.snapshot,
|
||||
policy,
|
||||
source: 'gateway:/api/projects',
|
||||
now: NOW,
|
||||
});
|
||||
expect(switched).toEqual({ outcome: 'invalidated', reason: 'cross-workspace' });
|
||||
});
|
||||
|
||||
it('keeps the previous workspace for collections with no intrinsic identity', () => {
|
||||
const userOne = acceptSnapshot({
|
||||
value: [
|
||||
{
|
||||
id: 'p1',
|
||||
name: 'P1',
|
||||
description: null,
|
||||
status: 'active',
|
||||
userId: 'user-1',
|
||||
metadata: null,
|
||||
createdAt: '2026-08-01T00:00:00.000Z',
|
||||
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||
},
|
||||
],
|
||||
validate: validateProjectCollection,
|
||||
previous: null,
|
||||
policy,
|
||||
source: 'gateway:/api/projects',
|
||||
now: NOW,
|
||||
});
|
||||
if (userOne.outcome !== 'accepted') throw new Error('expected acceptance');
|
||||
|
||||
// Empty list after the user deleted every project: no identity to check,
|
||||
// so the verified scope is retained and the empty state stays healthy.
|
||||
const emptied = acceptSnapshot({
|
||||
value: [],
|
||||
validate: validateProjectCollection,
|
||||
previous: userOne.snapshot,
|
||||
policy,
|
||||
source: 'gateway:/api/projects',
|
||||
now: NOW,
|
||||
});
|
||||
expect(emptied.outcome).toBe('accepted');
|
||||
if (emptied.outcome === 'accepted') {
|
||||
expect(emptied.snapshot.data).toEqual([]);
|
||||
expect(emptied.snapshot.workspace).toBe('user-1');
|
||||
}
|
||||
});
|
||||
|
||||
it('invalidates version regressions', () => {
|
||||
const previous = acceptedTaskSnapshot({ version: 7 });
|
||||
const regressed = acceptSnapshot({
|
||||
value: taskPayload,
|
||||
validate: validateTaskCollection,
|
||||
previous,
|
||||
policy,
|
||||
source: 'gateway:/api/tasks',
|
||||
now: NOW,
|
||||
incomingVersion: 3,
|
||||
});
|
||||
expect(regressed).toEqual({ outcome: 'invalidated', reason: 'version-regression' });
|
||||
|
||||
const newerSchema = acceptedTaskSnapshot({ schemaVersion: 4 });
|
||||
const downgradedClient = acceptSnapshot({
|
||||
value: taskPayload,
|
||||
validate: validateTaskCollection,
|
||||
previous: newerSchema,
|
||||
policy: { ...policy, schemaVersion: 2 },
|
||||
source: 'gateway:/api/tasks',
|
||||
now: NOW,
|
||||
});
|
||||
expect(downgradedClient).toEqual({ outcome: 'invalidated', reason: 'version-regression' });
|
||||
});
|
||||
|
||||
it('increments the version monotonically across accepted snapshots', () => {
|
||||
const first = acceptedTaskSnapshot();
|
||||
const second = acceptSnapshot({
|
||||
value: taskPayload,
|
||||
validate: validateTaskCollection,
|
||||
previous: first,
|
||||
policy,
|
||||
source: 'gateway:/api/tasks',
|
||||
now: NOW,
|
||||
});
|
||||
expect(second.outcome).toBe('accepted');
|
||||
if (second.outcome === 'accepted') {
|
||||
expect(second.snapshot.version).toBe(first.version + 1);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('combineFreshness', () => {
|
||||
it('gates the surface on the primary collection', () => {
|
||||
expect(combineFreshness('unavailable', ['current'])).toBe('unavailable');
|
||||
expect(combineFreshness('unknown', ['current'])).toBe('unknown');
|
||||
expect(combineFreshness('current', [])).toBe('current');
|
||||
});
|
||||
|
||||
it('degrades to partial when a secondary is unavailable', () => {
|
||||
expect(combineFreshness('current', ['current', 'unavailable'])).toBe('partial');
|
||||
});
|
||||
|
||||
it('degrades to unknown while a secondary is still loading', () => {
|
||||
expect(combineFreshness('current', ['unknown'])).toBe('unknown');
|
||||
});
|
||||
|
||||
it('degrades to stale when any collection is stale', () => {
|
||||
expect(combineFreshness('current', ['stale'])).toBe('stale');
|
||||
expect(combineFreshness('stale', ['current'])).toBe('stale');
|
||||
});
|
||||
|
||||
it('propagates partial secondaries', () => {
|
||||
expect(combineFreshness('current', ['partial'])).toBe('partial');
|
||||
});
|
||||
});
|
||||
|
||||
describe('computeDigest', () => {
|
||||
it('is stable across key order and changes with data', () => {
|
||||
const a = computeDigest({ x: 1, y: [1, 2] });
|
||||
const b = computeDigest({ y: [1, 2], x: 1 });
|
||||
expect(a).toBe(b);
|
||||
expect(computeDigest({ x: 1, y: [1, 3] })).not.toBe(a);
|
||||
});
|
||||
});
|
||||
|
||||
describe('verdictValue', () => {
|
||||
it('returns the value only for verified inputs', () => {
|
||||
expect(verdictValue(true, '5')).toBe('5');
|
||||
expect(verdictValue(false, '5')).toBe(UNKNOWN_VERDICT);
|
||||
expect(verdictValue(false, '5')).not.toBe('5');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatAge', () => {
|
||||
it('labels age in human terms', () => {
|
||||
expect(formatAge(NOW, NOW)).toBe('just now');
|
||||
expect(formatAge(NOW, NOW + 15_000)).toBe('under a minute ago');
|
||||
expect(formatAge(NOW, NOW + 120_000)).toBe('2m ago');
|
||||
expect(formatAge(NOW, NOW + 3 * 3_600_000)).toBe('3h ago');
|
||||
expect(formatAge(NOW, NOW + 2 * 86_400_000)).toBe('2d ago');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,261 @@
|
||||
/**
|
||||
* Typed freshness model for gateway-fetched collections (RI-5-001).
|
||||
*
|
||||
* A failed or stale fetch must never be indistinguishable from an empty
|
||||
* healthy collection. Every fetched surface carries an explicit freshness
|
||||
* state, a verified snapshot identity (source, workspace, version, age), and
|
||||
* a mutation guard that refuses state-changing operations unless the data is
|
||||
* verified current.
|
||||
*/
|
||||
|
||||
/** Freshness states for fetched data. Never inferred from emptiness. */
|
||||
export type FreshnessState = 'current' | 'stale' | 'partial' | 'unknown' | 'unavailable';
|
||||
|
||||
/**
|
||||
* Reasons a snapshot is invalidated. An invalidated snapshot is treated as
|
||||
* unavailable and is never rendered as current.
|
||||
*/
|
||||
export type InvalidationReason =
|
||||
| 'cache-corruption'
|
||||
| 'cross-workspace'
|
||||
| 'schema-mismatch'
|
||||
| 'version-regression';
|
||||
|
||||
/** Human-readable labels for invalidation reasons (UI + error messages). */
|
||||
export const invalidationReasonLabels: Record<InvalidationReason, string> = {
|
||||
'cache-corruption': 'cached snapshot failed integrity checks',
|
||||
'cross-workspace': 'data belongs to a different workspace',
|
||||
'schema-mismatch': 'response did not match the expected schema',
|
||||
'version-regression': 'snapshot version regressed below the accepted version',
|
||||
};
|
||||
|
||||
/** A verified snapshot of fetched data with full provenance. */
|
||||
export interface FreshSnapshot<T> {
|
||||
readonly data: T;
|
||||
/** Source identity of the fetch, e.g. `gateway:/api/tasks`. */
|
||||
readonly source: string;
|
||||
/** Workspace scope the data belongs to. */
|
||||
readonly workspace: string;
|
||||
/** Monotonic snapshot sequence number for this surface. */
|
||||
readonly version: number;
|
||||
/** Schema version of the validator that accepted this snapshot. */
|
||||
readonly schemaVersion: number;
|
||||
/** Epoch ms at which the data was verified. */
|
||||
readonly fetchedAt: number;
|
||||
/** Integrity digest of `data`, used to detect cache corruption. */
|
||||
readonly digest: string;
|
||||
}
|
||||
|
||||
/** Provenance label rendered next to last-known data. */
|
||||
export interface FreshnessLabel {
|
||||
readonly source: string;
|
||||
readonly version: number;
|
||||
readonly fetchedAt: number;
|
||||
}
|
||||
|
||||
/** Policy governing freshness for a surface. */
|
||||
export interface FreshnessPolicy {
|
||||
/** Active workspace scope. Snapshots from other scopes are invalidated. */
|
||||
readonly workspace: string;
|
||||
/** Schema version of the current validator. */
|
||||
readonly schemaVersion: number;
|
||||
/** Age after which a verified snapshot degrades from current to stale. */
|
||||
readonly staleAfterMs: number;
|
||||
}
|
||||
|
||||
export const DEFAULT_FRESHNESS_POLICY: FreshnessPolicy = {
|
||||
workspace: 'default',
|
||||
schemaVersion: 1,
|
||||
staleAfterMs: 60_000,
|
||||
};
|
||||
|
||||
/** Payload returned by a successful schema validation. */
|
||||
export interface FreshPayload<T> {
|
||||
readonly data: T;
|
||||
/**
|
||||
* Workspace identity extracted from the payload itself when the collection
|
||||
* carries one (e.g. a uniform `userId` on projects). `null` when the
|
||||
* collection has no intrinsic workspace identity.
|
||||
*/
|
||||
readonly workspace: string | null;
|
||||
}
|
||||
|
||||
/** Error thrown when a mutation is attempted on non-current data. */
|
||||
export class StaleMutationError extends Error {
|
||||
readonly freshness: FreshnessState;
|
||||
|
||||
constructor(freshness: FreshnessState) {
|
||||
super(`Refused mutation on ${freshness} data: revalidation is required before mutating.`);
|
||||
this.name = 'StaleMutationError';
|
||||
this.freshness = freshness;
|
||||
}
|
||||
}
|
||||
|
||||
/** Stable JSON digest used for snapshot integrity checks. */
|
||||
export function computeDigest(value: unknown): string {
|
||||
// FNV-1a 32-bit over the stable JSON serialization. This is an integrity
|
||||
// check against corruption, not a cryptographic guarantee.
|
||||
let hash = 0x811c9dc5;
|
||||
for (const byte of stableStringify(value)) {
|
||||
hash ^= byte.charCodeAt(0);
|
||||
hash = Math.imul(hash, 0x01000193) >>> 0;
|
||||
}
|
||||
return hash.toString(16).padStart(8, '0');
|
||||
}
|
||||
|
||||
function stableStringify(value: unknown): string {
|
||||
return serialize(value);
|
||||
}
|
||||
|
||||
function serialize(value: unknown): string {
|
||||
if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';
|
||||
if (Array.isArray(value)) return `[${value.map(serialize).join(',')}]`;
|
||||
const entries = Object.entries(value as Record<string, unknown>)
|
||||
.filter(([, item]) => item !== undefined)
|
||||
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
||||
.map(([key, item]) => `${JSON.stringify(key)}:${serialize(item)}`);
|
||||
return `{${entries.join(',')}}`;
|
||||
}
|
||||
|
||||
export type AcceptSnapshotResult<T> =
|
||||
| { readonly outcome: 'accepted'; readonly snapshot: FreshSnapshot<T> }
|
||||
| { readonly outcome: 'invalidated'; readonly reason: InvalidationReason };
|
||||
|
||||
export interface AcceptSnapshotOptions<T> {
|
||||
/** Raw fetched value (untrusted JSON). */
|
||||
readonly value: unknown;
|
||||
/** Schema validator; returns `null` when the value does not match. */
|
||||
readonly validate: (value: unknown) => FreshPayload<T> | null;
|
||||
/** Previously accepted snapshot for this surface, if any. */
|
||||
readonly previous: FreshSnapshot<T> | null;
|
||||
readonly policy: FreshnessPolicy;
|
||||
readonly source: string;
|
||||
/**
|
||||
* Version carried by the incoming payload when the transport exposes one.
|
||||
* Must not regress below the accepted snapshot's version.
|
||||
*/
|
||||
readonly incomingVersion?: number;
|
||||
readonly now: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate and accept a fetched value as a snapshot, or invalidate it.
|
||||
*
|
||||
* Invalidation rules (each treated as unavailable, never rendered current):
|
||||
* - schema mismatch: the payload fails validation
|
||||
* - cross-workspace: the payload's workspace differs from the verified one
|
||||
* - version regression: payload/schema version is below the accepted one
|
||||
*/
|
||||
export function acceptSnapshot<T>(options: AcceptSnapshotOptions<T>): AcceptSnapshotResult<T> {
|
||||
const payload = options.validate(options.value);
|
||||
if (payload === null) {
|
||||
return { outcome: 'invalidated', reason: 'schema-mismatch' };
|
||||
}
|
||||
|
||||
// Workspace identity: the payload's own scope wins; a collection with no
|
||||
// intrinsic identity (e.g. an empty list after every project was deleted)
|
||||
// keeps the previously verified scope rather than resetting to the policy
|
||||
// default, so a legitimately empty response is not mistaken for a scope
|
||||
// change.
|
||||
const workspace = payload.workspace ?? options.previous?.workspace ?? options.policy.workspace;
|
||||
if (options.previous !== null && options.previous.workspace !== workspace) {
|
||||
return { outcome: 'invalidated', reason: 'cross-workspace' };
|
||||
}
|
||||
if (options.previous !== null && options.policy.schemaVersion < options.previous.schemaVersion) {
|
||||
return { outcome: 'invalidated', reason: 'version-regression' };
|
||||
}
|
||||
if (
|
||||
options.incomingVersion !== undefined &&
|
||||
options.previous !== null &&
|
||||
options.incomingVersion < options.previous.version
|
||||
) {
|
||||
return { outcome: 'invalidated', reason: 'version-regression' };
|
||||
}
|
||||
|
||||
const snapshot: FreshSnapshot<T> = {
|
||||
data: payload.data,
|
||||
source: options.source,
|
||||
workspace,
|
||||
version: options.incomingVersion ?? (options.previous?.version ?? 0) + 1,
|
||||
schemaVersion: options.policy.schemaVersion,
|
||||
fetchedAt: options.now,
|
||||
digest: computeDigest(payload.data),
|
||||
};
|
||||
return { outcome: 'accepted', snapshot };
|
||||
}
|
||||
|
||||
export interface ComputeFreshnessOptions {
|
||||
readonly snapshot: FreshSnapshot<unknown> | null;
|
||||
readonly policy: FreshnessPolicy;
|
||||
readonly now: number;
|
||||
/**
|
||||
* True when the snapshot cannot be trusted as current regardless of age:
|
||||
* the latest revalidation failed, or the snapshot was restored from cache
|
||||
* and has not been verified by a fetch in this session.
|
||||
*/
|
||||
readonly degraded?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the freshness state of a snapshot. A missing snapshot is
|
||||
* `unavailable` (never "empty and healthy"); a degraded or aged snapshot is
|
||||
* `stale` (situational awareness only).
|
||||
*/
|
||||
export function computeFreshness(options: ComputeFreshnessOptions): FreshnessState {
|
||||
const { snapshot, policy, now, degraded = false } = options;
|
||||
if (snapshot === null) return 'unavailable';
|
||||
if (degraded) return 'stale';
|
||||
if (now - snapshot.fetchedAt > policy.staleAfterMs) return 'stale';
|
||||
return 'current';
|
||||
}
|
||||
|
||||
/** Only verified-current data may back a state-changing action. */
|
||||
export function canMutate(state: FreshnessState): boolean {
|
||||
return state === 'current';
|
||||
}
|
||||
|
||||
/** Defense in depth: reject the mutation call itself on non-current data. */
|
||||
export function assertMutable(state: FreshnessState): void {
|
||||
if (!canMutate(state)) {
|
||||
throw new StaleMutationError(state);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Combine freshness across a multi-collection surface (primary + secondaries).
|
||||
* The primary collection gates the surface: unknown while it loads,
|
||||
* unavailable when it fails. Missing secondaries degrade the surface to
|
||||
* `partial`; aged collections degrade it to `stale`.
|
||||
*/
|
||||
export function combineFreshness(
|
||||
primary: FreshnessState,
|
||||
secondaries: readonly FreshnessState[],
|
||||
): FreshnessState {
|
||||
if (primary === 'unavailable') return 'unavailable';
|
||||
if (primary === 'unknown') return 'unknown';
|
||||
if (secondaries.includes('unavailable')) return 'partial';
|
||||
if (secondaries.includes('unknown')) return 'unknown';
|
||||
if (secondaries.includes('stale') || primary === 'stale') return 'stale';
|
||||
if (secondaries.includes('partial')) return 'partial';
|
||||
return 'current';
|
||||
}
|
||||
|
||||
/** Render-safe age label for snapshot provenance. */
|
||||
export function formatAge(fetchedAt: number, now: number): string {
|
||||
const ageMs = Math.max(0, now - fetchedAt);
|
||||
if (ageMs < 10_000) return 'just now';
|
||||
const minutes = Math.floor(ageMs / 60_000);
|
||||
if (minutes < 1) return 'under a minute ago';
|
||||
if (minutes < 60) return `${minutes}m ago`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
if (hours < 24) return `${hours}h ago`;
|
||||
const days = Math.floor(hours / 24);
|
||||
return `${days}d ago`;
|
||||
}
|
||||
|
||||
/** Derived verdict placeholder for non-current inputs — never a green value. */
|
||||
export const UNKNOWN_VERDICT = '?';
|
||||
|
||||
export function verdictValue(verified: boolean, value: string): string {
|
||||
return verified ? value : UNKNOWN_VERDICT;
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { acceptSnapshot, DEFAULT_FRESHNESS_POLICY } from './model';
|
||||
import { clearSnapshotCache, readSnapshotCache, writeSnapshotCache } from './snapshot-cache';
|
||||
import { validateProjectCollection, validateTaskCollection } from './validators';
|
||||
import { projectFixtures, taskFixtures } from '@/spa/pages/page-fixtures';
|
||||
import type { Project, Task } from '@/lib/types';
|
||||
|
||||
const KEY = 'test:tasks';
|
||||
const NOW = 1_800_000_000_000;
|
||||
const policy = { ...DEFAULT_FRESHNESS_POLICY, staleAfterMs: 60_000 };
|
||||
|
||||
function storedTaskSnapshot() {
|
||||
const result = acceptSnapshot({
|
||||
value: taskFixtures,
|
||||
validate: validateTaskCollection,
|
||||
previous: null,
|
||||
policy,
|
||||
source: 'gateway:/api/tasks',
|
||||
now: NOW,
|
||||
});
|
||||
if (result.outcome !== 'accepted') throw new Error('fixture setup failed');
|
||||
return result.snapshot;
|
||||
}
|
||||
|
||||
function storedProjectSnapshot() {
|
||||
const result = acceptSnapshot({
|
||||
value: projectFixtures,
|
||||
validate: validateProjectCollection,
|
||||
previous: null,
|
||||
policy,
|
||||
source: 'gateway:/api/projects',
|
||||
now: NOW,
|
||||
});
|
||||
if (result.outcome !== 'accepted') throw new Error('fixture setup failed');
|
||||
return result.snapshot;
|
||||
}
|
||||
|
||||
function readTasks() {
|
||||
return readSnapshotCache({
|
||||
key: KEY,
|
||||
workspace: policy.workspace,
|
||||
policy,
|
||||
validate: validateTaskCollection,
|
||||
});
|
||||
}
|
||||
|
||||
/** Write an arbitrary value directly at the raw cache slot. */
|
||||
function writeRaw(key: string, value: unknown): void {
|
||||
sessionStorage.setItem(`mosaic:freshness:v1:${key}`, JSON.stringify(value));
|
||||
}
|
||||
|
||||
/** Parse and re-write the stored entry (for tampering with internals). */
|
||||
function tamperStored<T>(key: string, mutate: (stored: T) => void): void {
|
||||
const parsed = JSON.parse(sessionStorage.getItem(`mosaic:freshness:v1:${key}`) ?? '{}') as T;
|
||||
mutate(parsed);
|
||||
writeRaw(key, parsed);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
describe('readSnapshotCache', () => {
|
||||
it('misses when nothing is stored', () => {
|
||||
expect(readTasks()).toEqual({ outcome: 'miss' });
|
||||
});
|
||||
|
||||
it('hits for a well-formed entry and preserves provenance', () => {
|
||||
const snapshot = storedTaskSnapshot();
|
||||
writeSnapshotCache(KEY, snapshot);
|
||||
|
||||
const result = readTasks();
|
||||
expect(result.outcome).toBe('hit');
|
||||
if (result.outcome === 'hit') {
|
||||
expect(result.snapshot.data).toEqual(taskFixtures);
|
||||
expect(result.snapshot.source).toBe('gateway:/api/tasks');
|
||||
expect(result.snapshot.version).toBe(snapshot.version);
|
||||
expect(result.snapshot.fetchedAt).toBe(snapshot.fetchedAt);
|
||||
expect(result.snapshot.workspace).toBe(snapshot.workspace);
|
||||
}
|
||||
});
|
||||
|
||||
it('invalidates unparsable entries as cache corruption', () => {
|
||||
sessionStorage.setItem(`mosaic:freshness:v1:${KEY}`, '{not json');
|
||||
expect(readTasks()).toEqual({ outcome: 'invalidated', reason: 'cache-corruption' });
|
||||
});
|
||||
|
||||
it('invalidates structurally wrong entries as cache corruption', () => {
|
||||
const malformed: unknown[] = [
|
||||
'nested but not a snapshot',
|
||||
{ data: taskFixtures }, // missing provenance fields
|
||||
{
|
||||
data: taskFixtures,
|
||||
source: 1,
|
||||
workspace: 'w',
|
||||
version: 1,
|
||||
schemaVersion: 1,
|
||||
fetchedAt: 1,
|
||||
digest: 'x',
|
||||
},
|
||||
null,
|
||||
17,
|
||||
];
|
||||
for (const entry of malformed) {
|
||||
writeRaw(KEY, entry);
|
||||
expect(readTasks()).toEqual({ outcome: 'invalidated', reason: 'cache-corruption' });
|
||||
}
|
||||
});
|
||||
|
||||
it('invalidates digest mismatches as cache corruption (tampered data)', () => {
|
||||
writeSnapshotCache(KEY, storedTaskSnapshot());
|
||||
tamperStored<{ data: Task[] }>(KEY, (stored) => {
|
||||
stored.data = [...stored.data, { ...stored.data[0]!, id: 'injected-task' }];
|
||||
});
|
||||
expect(readTasks()).toEqual({ outcome: 'invalidated', reason: 'cache-corruption' });
|
||||
});
|
||||
|
||||
it('invalidates entries scoped to another workspace', () => {
|
||||
const snapshot = storedTaskSnapshot();
|
||||
writeSnapshotCache(KEY, { ...snapshot, workspace: 'someone-else' });
|
||||
expect(readTasks()).toEqual({ outcome: 'invalidated', reason: 'cross-workspace' });
|
||||
});
|
||||
|
||||
it('invalidates entries written by a newer schema as a version regression', () => {
|
||||
const snapshot = storedTaskSnapshot();
|
||||
writeSnapshotCache(KEY, { ...snapshot, schemaVersion: policy.schemaVersion + 1 });
|
||||
expect(readTasks()).toEqual({ outcome: 'invalidated', reason: 'version-regression' });
|
||||
});
|
||||
|
||||
it('invalidates entries whose data no longer validates (schema mismatch)', () => {
|
||||
writeSnapshotCache(KEY, storedTaskSnapshot());
|
||||
tamperStored<{ data: unknown }>(KEY, (stored) => {
|
||||
stored.data = { malformed: true };
|
||||
});
|
||||
expect(readTasks()).toEqual({ outcome: 'invalidated', reason: 'schema-mismatch' });
|
||||
});
|
||||
|
||||
it('never reports a corrupted raw entry as a hit (negative control)', () => {
|
||||
for (const raw of ['{oops', 'null', '"string"', '[]', '12']) {
|
||||
sessionStorage.setItem(`mosaic:freshness:v1:${KEY}`, raw);
|
||||
const result = readTasks();
|
||||
expect(result.outcome).not.toBe('hit');
|
||||
expect(result.outcome).toBe('invalidated');
|
||||
}
|
||||
});
|
||||
|
||||
it('scopes project collections by their workspace identity', () => {
|
||||
const snapshot = storedProjectSnapshot();
|
||||
writeSnapshotCache('test:projects', snapshot);
|
||||
|
||||
const sameScope = readSnapshotCache({
|
||||
key: 'test:projects',
|
||||
workspace: 'user-1',
|
||||
policy,
|
||||
validate: validateProjectCollection,
|
||||
});
|
||||
expect(sameScope.outcome).toBe('hit');
|
||||
|
||||
const foreignScope = readSnapshotCache({
|
||||
key: 'test:projects',
|
||||
workspace: 'user-2',
|
||||
policy,
|
||||
validate: validateProjectCollection,
|
||||
});
|
||||
expect(foreignScope).toEqual({ outcome: 'invalidated', reason: 'cross-workspace' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeSnapshotCache round-trip', () => {
|
||||
it('round-trips an accepted project snapshot', () => {
|
||||
const snapshot = storedProjectSnapshot();
|
||||
writeSnapshotCache('test:projects', snapshot);
|
||||
const result = readSnapshotCache({
|
||||
key: 'test:projects',
|
||||
workspace: snapshot.workspace,
|
||||
policy,
|
||||
validate: validateProjectCollection,
|
||||
});
|
||||
expect(result.outcome).toBe('hit');
|
||||
if (result.outcome === 'hit') {
|
||||
expect(result.snapshot.data).toEqual(projectFixtures as Project[]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('clearSnapshotCache', () => {
|
||||
it('drops the entry so the next read misses', () => {
|
||||
writeSnapshotCache(KEY, storedTaskSnapshot());
|
||||
expect(readTasks().outcome).toBe('hit');
|
||||
clearSnapshotCache(KEY);
|
||||
expect(readTasks()).toEqual({ outcome: 'miss' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
import {
|
||||
computeDigest,
|
||||
type FreshPayload,
|
||||
type FreshSnapshot,
|
||||
type FreshnessPolicy,
|
||||
type InvalidationReason,
|
||||
} from './model';
|
||||
|
||||
/**
|
||||
* Session-scoped last-known snapshot cache (RI-5-001).
|
||||
*
|
||||
* Restored snapshots are situational awareness only: they surface as `stale`
|
||||
* until a fetch re-verifies them. A cache entry that is corrupted, belongs to
|
||||
* another workspace, was written by a newer schema, or no longer validates is
|
||||
* invalidated (treated as unavailable, never rendered as current).
|
||||
*/
|
||||
|
||||
const CACHE_PREFIX = 'mosaic:freshness:v1';
|
||||
|
||||
interface StoredSnapshot {
|
||||
data: unknown;
|
||||
source: string;
|
||||
workspace: string;
|
||||
version: number;
|
||||
schemaVersion: number;
|
||||
fetchedAt: number;
|
||||
digest: string;
|
||||
}
|
||||
|
||||
export type SnapshotCacheRead<T> =
|
||||
| { readonly outcome: 'hit'; readonly snapshot: FreshSnapshot<T> }
|
||||
| { readonly outcome: 'miss' }
|
||||
| { readonly outcome: 'invalidated'; readonly reason: InvalidationReason };
|
||||
|
||||
export interface ReadSnapshotCacheOptions<T> {
|
||||
readonly key: string;
|
||||
readonly workspace: string;
|
||||
readonly policy: FreshnessPolicy;
|
||||
readonly validate: (value: unknown) => FreshPayload<T> | null;
|
||||
}
|
||||
|
||||
function cacheKey(key: string): string {
|
||||
return `${CACHE_PREFIX}:${key}`;
|
||||
}
|
||||
|
||||
function isStoredSnapshot(value: unknown): value is StoredSnapshot {
|
||||
if (typeof value !== 'object' || value === null) return false;
|
||||
const candidate = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof candidate['data'] === 'object' &&
|
||||
candidate['data'] !== null &&
|
||||
typeof candidate['source'] === 'string' &&
|
||||
typeof candidate['workspace'] === 'string' &&
|
||||
typeof candidate['version'] === 'number' &&
|
||||
typeof candidate['schemaVersion'] === 'number' &&
|
||||
typeof candidate['fetchedAt'] === 'number' &&
|
||||
typeof candidate['digest'] === 'string'
|
||||
);
|
||||
}
|
||||
|
||||
function getStorage(): Storage | null {
|
||||
try {
|
||||
return globalThis.sessionStorage ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore a cached snapshot under the active workspace scope. Every failure
|
||||
* mode maps to an explicit invalidation reason or a miss — never to data
|
||||
* that renders as current.
|
||||
*/
|
||||
export function readSnapshotCache<T>(options: ReadSnapshotCacheOptions<T>): SnapshotCacheRead<T> {
|
||||
const storage = getStorage();
|
||||
if (storage === null) return { outcome: 'miss' };
|
||||
|
||||
let raw: string | null;
|
||||
try {
|
||||
raw = storage.getItem(cacheKey(options.key));
|
||||
} catch {
|
||||
return { outcome: 'miss' };
|
||||
}
|
||||
if (raw === null) return { outcome: 'miss' };
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
return { outcome: 'invalidated', reason: 'cache-corruption' };
|
||||
}
|
||||
if (!isStoredSnapshot(parsed)) {
|
||||
return { outcome: 'invalidated', reason: 'cache-corruption' };
|
||||
}
|
||||
if (parsed.workspace !== options.workspace) {
|
||||
return { outcome: 'invalidated', reason: 'cross-workspace' };
|
||||
}
|
||||
if (parsed.schemaVersion > options.policy.schemaVersion) {
|
||||
// Written by a newer build than the running client: version regression.
|
||||
return { outcome: 'invalidated', reason: 'version-regression' };
|
||||
}
|
||||
|
||||
const payload = options.validate(parsed.data);
|
||||
if (payload === null) {
|
||||
return { outcome: 'invalidated', reason: 'schema-mismatch' };
|
||||
}
|
||||
if (computeDigest(payload.data) !== parsed.digest) {
|
||||
return { outcome: 'invalidated', reason: 'cache-corruption' };
|
||||
}
|
||||
|
||||
return {
|
||||
outcome: 'hit',
|
||||
snapshot: {
|
||||
data: payload.data,
|
||||
source: parsed.source,
|
||||
workspace: parsed.workspace,
|
||||
version: parsed.version,
|
||||
schemaVersion: parsed.schemaVersion,
|
||||
fetchedAt: parsed.fetchedAt,
|
||||
digest: parsed.digest,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Persist a verified snapshot. Failures are non-fatal (cache is best-effort). */
|
||||
export function writeSnapshotCache<T>(key: string, snapshot: FreshSnapshot<T>): void {
|
||||
const storage = getStorage();
|
||||
if (storage === null) return;
|
||||
const stored: StoredSnapshot = {
|
||||
data: snapshot.data,
|
||||
source: snapshot.source,
|
||||
workspace: snapshot.workspace,
|
||||
version: snapshot.version,
|
||||
schemaVersion: snapshot.schemaVersion,
|
||||
fetchedAt: snapshot.fetchedAt,
|
||||
digest: snapshot.digest,
|
||||
};
|
||||
try {
|
||||
storage.setItem(cacheKey(key), JSON.stringify(stored));
|
||||
} catch {
|
||||
// Quota or serialization failures simply skip caching.
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop a cached snapshot (used when a surface invalidates its cache entry). */
|
||||
export function clearSnapshotCache(key: string): void {
|
||||
const storage = getStorage();
|
||||
if (storage === null) return;
|
||||
try {
|
||||
storage.removeItem(cacheKey(key));
|
||||
} catch {
|
||||
// Ignorable: a wedged storage entry is detected as corruption on read.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Task } from '@/lib/types';
|
||||
import { acceptSnapshot, StaleMutationError, DEFAULT_FRESHNESS_POLICY } from './model';
|
||||
import type { FreshnessFailure } from './use-fresh-collection';
|
||||
import {
|
||||
describeFailure,
|
||||
useFreshCollection,
|
||||
type FreshCollection,
|
||||
type UseFreshCollectionOptions,
|
||||
} from './use-fresh-collection';
|
||||
import { validateProjectCollection, validateTaskCollection } from './validators';
|
||||
import { projectFixtures, taskFixtures } from '@/spa/pages/page-fixtures';
|
||||
|
||||
/**
|
||||
* Failure-matrix coverage for the freshness seam (RI-5-001): network failure,
|
||||
* auth failure, malformed response, cache corruption, stale age, schema
|
||||
* mismatch, cross-workspace, recovery, and stale-action rejection — with
|
||||
* negative controls proving no case yields current data or an enabled
|
||||
* mutation.
|
||||
*/
|
||||
|
||||
const NOW = 1_800_000_000_000;
|
||||
|
||||
interface Deferred<T> {
|
||||
promise: Promise<T>;
|
||||
resolve: (value: T) => void;
|
||||
reject: (reason?: unknown) => void;
|
||||
}
|
||||
|
||||
function createDeferred<T>(): Deferred<T> {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement;
|
||||
let latest: FreshCollection<Task[]> | null = null;
|
||||
|
||||
function Probe({
|
||||
options,
|
||||
}: {
|
||||
options: UseFreshCollectionOptions<Task[]>;
|
||||
}): React.ReactElement | null {
|
||||
latest = useFreshCollection<Task[]>(options);
|
||||
return null;
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
document.body.replaceChildren();
|
||||
root = null;
|
||||
latest = null;
|
||||
sessionStorage.clear();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function renderCollection(
|
||||
options: UseFreshCollectionOptions<Task[]>,
|
||||
): Promise<FreshCollection<Task[]>> {
|
||||
container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
await act(async () => {
|
||||
root?.render(<Probe options={options} />);
|
||||
});
|
||||
if (latest === null) throw new Error('hook did not run');
|
||||
return latest;
|
||||
}
|
||||
|
||||
function taskOptions(
|
||||
overrides: Partial<UseFreshCollectionOptions<Task[]>> = {},
|
||||
): UseFreshCollectionOptions<Task[]> {
|
||||
return {
|
||||
source: 'gateway:/api/tasks',
|
||||
fetcher: () => Promise.resolve(taskFixtures),
|
||||
validate: validateTaskCollection,
|
||||
cacheKey: 'tasks',
|
||||
clock: () => NOW,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function authError(statusCode: number): Error & { statusCode: number } {
|
||||
return Object.assign(new Error(`Request failed with ${statusCode}`), { statusCode });
|
||||
}
|
||||
|
||||
function seedCache(key: string): number {
|
||||
const result = acceptSnapshot({
|
||||
value: taskFixtures,
|
||||
validate: validateTaskCollection,
|
||||
previous: null,
|
||||
policy: DEFAULT_FRESHNESS_POLICY,
|
||||
source: 'gateway:/api/tasks',
|
||||
now: NOW,
|
||||
});
|
||||
if (result.outcome !== 'accepted') throw new Error('fixture setup failed');
|
||||
sessionStorage.setItem(`mosaic:freshness:v1:${key}`, JSON.stringify({ ...result.snapshot }));
|
||||
return result.snapshot.version;
|
||||
}
|
||||
|
||||
describe('useFreshCollection failure matrix', () => {
|
||||
it('is unknown (not empty) while the first validation is in flight', async () => {
|
||||
const deferred = createDeferred<Task[]>();
|
||||
const collection = await renderCollection(taskOptions({ fetcher: () => deferred.promise }));
|
||||
|
||||
expect(collection.freshness).toBe('unknown');
|
||||
expect(collection.validating).toBe(true);
|
||||
expect(collection.data).toBeNull();
|
||||
expect(collection.canMutate).toBe(false);
|
||||
|
||||
await act(async () => {
|
||||
deferred.resolve(taskFixtures);
|
||||
await deferred.promise;
|
||||
});
|
||||
});
|
||||
|
||||
it('becomes current with provenance after a verified fetch', async () => {
|
||||
const collection = await renderCollection(taskOptions());
|
||||
|
||||
expect(collection.freshness).toBe('current');
|
||||
expect(collection.data).toEqual(taskFixtures);
|
||||
expect(collection.snapshot?.source).toBe('gateway:/api/tasks');
|
||||
expect(collection.snapshot?.version).toBe(1);
|
||||
expect(collection.failure).toBeNull();
|
||||
expect(collection.canMutate).toBe(true);
|
||||
// Verified snapshot is persisted for last-known restore.
|
||||
expect(sessionStorage.getItem('mosaic:freshness:v1:tasks')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('treats a network failure as unavailable — never an empty healthy collection', async () => {
|
||||
const collection = await renderCollection(
|
||||
taskOptions({ fetcher: () => Promise.reject(new Error('network down')) }),
|
||||
);
|
||||
|
||||
expect(collection.freshness).toBe('unavailable');
|
||||
expect(collection.data).toBeNull();
|
||||
expect(collection.failure).toEqual({ kind: 'fetch', message: 'network down' });
|
||||
expect(collection.canMutate).toBe(false);
|
||||
expect(describeFailure(collection.failure)).toBe('network down');
|
||||
});
|
||||
|
||||
it('treats an auth failure as unavailable and drops the last-known snapshot', async () => {
|
||||
let call = 0;
|
||||
const collection = await renderCollection(
|
||||
taskOptions({
|
||||
fetcher: () => {
|
||||
call += 1;
|
||||
return call === 1 ? Promise.resolve(taskFixtures) : Promise.reject(authError(401));
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(collection.freshness).toBe('current');
|
||||
|
||||
await act(async () => {
|
||||
await collection.revalidate();
|
||||
});
|
||||
|
||||
expect(latest?.freshness).toBe('unavailable');
|
||||
expect(latest?.data).toBeNull();
|
||||
expect(latest?.failure?.kind).toBe('fetch');
|
||||
// The previous user's data must not linger in the session cache.
|
||||
expect(sessionStorage.getItem('mosaic:freshness:v1:tasks')).toBeNull();
|
||||
});
|
||||
|
||||
it('invalidates a malformed response as a schema mismatch', async () => {
|
||||
const collection = await renderCollection(
|
||||
taskOptions({ fetcher: () => Promise.resolve({ malformed: true }) }),
|
||||
);
|
||||
|
||||
expect(collection.freshness).toBe('unavailable');
|
||||
expect(collection.data).toBeNull();
|
||||
expect(collection.failure).toEqual({ kind: 'invalidated', reason: 'schema-mismatch' });
|
||||
expect(collection.canMutate).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the previous snapshot as labeled stale when a later payload mismatches', async () => {
|
||||
let call = 0;
|
||||
const collection = await renderCollection(
|
||||
taskOptions({
|
||||
fetcher: () => {
|
||||
call += 1;
|
||||
return call === 1 ? Promise.resolve(taskFixtures) : Promise.resolve('garbage');
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(collection.freshness).toBe('current');
|
||||
|
||||
await act(async () => {
|
||||
await collection.revalidate();
|
||||
});
|
||||
|
||||
expect(latest?.freshness).toBe('stale');
|
||||
expect(latest?.data).toEqual(taskFixtures);
|
||||
expect(latest?.failure).toEqual({ kind: 'invalidated', reason: 'schema-mismatch' });
|
||||
expect(latest?.canMutate).toBe(false);
|
||||
});
|
||||
|
||||
it('drops the snapshot when the workspace changes under it (cross-workspace)', async () => {
|
||||
let call = 0;
|
||||
const collection = await renderCollection(
|
||||
taskOptions({
|
||||
fetcher: () => {
|
||||
call += 1;
|
||||
return Promise.resolve(
|
||||
call === 1 ? projectFixtures : [{ ...projectFixtures[0], userId: 'user-2' }],
|
||||
);
|
||||
},
|
||||
validate: validateProjectCollection as unknown as (value: unknown) => {
|
||||
data: Task[];
|
||||
workspace: string | null;
|
||||
},
|
||||
source: 'gateway:/api/projects',
|
||||
}),
|
||||
);
|
||||
expect(collection.freshness).toBe('current');
|
||||
|
||||
await act(async () => {
|
||||
await collection.revalidate();
|
||||
});
|
||||
|
||||
expect(latest?.freshness).toBe('unavailable');
|
||||
expect(latest?.data).toBeNull();
|
||||
expect(latest?.failure).toEqual({ kind: 'invalidated', reason: 'cross-workspace' });
|
||||
});
|
||||
|
||||
it('ages from current to stale and refuses mutations on stale data', async () => {
|
||||
let fakeNow = NOW;
|
||||
const collection = await renderCollection(
|
||||
taskOptions({
|
||||
clock: () => fakeNow,
|
||||
policy: { staleAfterMs: 40 },
|
||||
tickMs: 10,
|
||||
}),
|
||||
);
|
||||
expect(collection.freshness).toBe('current');
|
||||
|
||||
// Age the snapshot past the policy and let the tick recompute.
|
||||
fakeNow = NOW + 60;
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
});
|
||||
|
||||
expect(latest?.freshness).toBe('stale');
|
||||
expect(latest?.data).toEqual(taskFixtures);
|
||||
expect(latest?.canMutate).toBe(false);
|
||||
|
||||
const operation = vi.fn(async () => 'result');
|
||||
await expect(latest?.mutate(operation)).rejects.toBeInstanceOf(StaleMutationError);
|
||||
expect(operation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('recovers to current after a successful revalidation', async () => {
|
||||
let call = 0;
|
||||
const collection = await renderCollection(
|
||||
taskOptions({
|
||||
fetcher: () => {
|
||||
call += 1;
|
||||
return call === 1
|
||||
? Promise.reject(new Error('first attempt failed'))
|
||||
: Promise.resolve(taskFixtures);
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(collection.freshness).toBe('unavailable');
|
||||
|
||||
await act(async () => {
|
||||
await collection.revalidate();
|
||||
});
|
||||
|
||||
expect(latest?.freshness).toBe('current');
|
||||
expect(latest?.failure).toBeNull();
|
||||
|
||||
const operation = vi.fn(async (data: Task[]) => data.length);
|
||||
await expect(latest?.mutate(operation)).resolves.toBe(taskFixtures.length);
|
||||
expect(operation).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('restores a cached snapshot as unverified stale data, then verifies it', async () => {
|
||||
const seededVersion = seedCache('tasks');
|
||||
const deferred = createDeferred<Task[]>();
|
||||
const collection = await renderCollection(taskOptions({ fetcher: () => deferred.promise }));
|
||||
|
||||
// Restored data is situational awareness only: labeled stale, never
|
||||
// current, and mutations are refused before verification.
|
||||
expect(collection.freshness).toBe('stale');
|
||||
expect(collection.data).toEqual(taskFixtures);
|
||||
expect(collection.canMutate).toBe(false);
|
||||
await expect(collection.mutate(vi.fn())).rejects.toBeInstanceOf(StaleMutationError);
|
||||
|
||||
await act(async () => {
|
||||
deferred.resolve(taskFixtures);
|
||||
await deferred.promise;
|
||||
});
|
||||
|
||||
expect(latest?.freshness).toBe('current');
|
||||
expect(latest?.snapshot?.version).toBe(seededVersion + 1);
|
||||
});
|
||||
|
||||
it('never promotes corrupted cache data to current (cache corruption)', async () => {
|
||||
sessionStorage.setItem('mosaic:freshness:v1:tasks', '{"data":');
|
||||
const collection = await renderCollection(
|
||||
taskOptions({ fetcher: () => Promise.reject(new Error('still down')) }),
|
||||
);
|
||||
|
||||
expect(collection.freshness).toBe('unavailable');
|
||||
expect(collection.data).toBeNull();
|
||||
expect(collection.canMutate).toBe(false);
|
||||
// The corrupted entry is dropped so it cannot come back.
|
||||
expect(sessionStorage.getItem('mosaic:freshness:v1:tasks')).toBeNull();
|
||||
});
|
||||
|
||||
it('refuses mutations while unknown or unavailable — the call itself, not just the button', async () => {
|
||||
const deferred = createDeferred<Task[]>();
|
||||
const unknown = await renderCollection(taskOptions({ fetcher: () => deferred.promise }));
|
||||
const operation = vi.fn(async () => 'result');
|
||||
await expect(unknown.mutate(operation)).rejects.toBeInstanceOf(StaleMutationError);
|
||||
expect(operation).not.toHaveBeenCalled();
|
||||
await act(async () => {
|
||||
deferred.reject(new Error('failed'));
|
||||
await deferred.promise.catch(() => undefined);
|
||||
});
|
||||
|
||||
const unavailable = latest!;
|
||||
await expect(unavailable.mutate(operation)).rejects.toBeInstanceOf(StaleMutationError);
|
||||
expect(operation).not.toHaveBeenCalled();
|
||||
expect(unavailable.canMutate).toBe(false);
|
||||
});
|
||||
|
||||
it('degrades to stale with last-known data when a revalidation fails after success', async () => {
|
||||
let call = 0;
|
||||
const collection = await renderCollection(
|
||||
taskOptions({
|
||||
fetcher: () => {
|
||||
call += 1;
|
||||
return call === 1
|
||||
? Promise.resolve(taskFixtures)
|
||||
: Promise.reject(new Error('connection lost'));
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(collection.freshness).toBe('current');
|
||||
|
||||
await act(async () => {
|
||||
await collection.revalidate();
|
||||
});
|
||||
|
||||
expect(latest?.freshness).toBe('stale');
|
||||
expect(latest?.data).toEqual(taskFixtures);
|
||||
const failure: FreshnessFailure | null = latest?.failure ?? null;
|
||||
expect(failure).toEqual({ kind: 'fetch', message: 'connection lost' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,281 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
acceptSnapshot,
|
||||
assertMutable,
|
||||
computeFreshness,
|
||||
DEFAULT_FRESHNESS_POLICY,
|
||||
invalidationReasonLabels,
|
||||
type FreshPayload,
|
||||
type FreshSnapshot,
|
||||
type FreshnessPolicy,
|
||||
type FreshnessState,
|
||||
type InvalidationReason,
|
||||
StaleMutationError,
|
||||
} from './model';
|
||||
import { clearSnapshotCache, readSnapshotCache, writeSnapshotCache } from './snapshot-cache';
|
||||
|
||||
/**
|
||||
* Freshness-aware collection fetch hook (RI-5-001).
|
||||
*
|
||||
* One hook owns one gateway collection end to end: fetch, schema validation,
|
||||
* snapshot acceptance with provenance, session-scoped last-known caching,
|
||||
* aging, and the mutation guard. Pages consume `freshness` and never infer
|
||||
* health from emptiness.
|
||||
*/
|
||||
|
||||
/** Why the latest validation did not produce a current snapshot. */
|
||||
export type FreshnessFailure =
|
||||
| { readonly kind: 'fetch'; readonly message: string }
|
||||
| { readonly kind: 'invalidated'; readonly reason: InvalidationReason };
|
||||
|
||||
export interface UseFreshCollectionOptions<T> {
|
||||
/** Source identity for provenance labels, e.g. `gateway:/api/tasks`. */
|
||||
readonly source: string;
|
||||
/** Performs the unvalidated fetch. The hook owns abort and verification. */
|
||||
readonly fetcher: (signal: AbortSignal) => Promise<unknown>;
|
||||
/**
|
||||
* Runtime schema validator. Returning `null` invalidates the payload
|
||||
* (`schema-mismatch`) instead of letting malformed JSON flow into render.
|
||||
*/
|
||||
readonly validate: (value: unknown) => FreshPayload<T> | null;
|
||||
/** Overrides of the default freshness policy. */
|
||||
readonly policy?: Partial<FreshnessPolicy>;
|
||||
/**
|
||||
* Session cache key for last-known snapshots. `null`/omitted disables
|
||||
* restore. Restored snapshots are unverified: they render only as
|
||||
* labeled `stale` data until a fetch re-verifies them.
|
||||
*/
|
||||
readonly cacheKey?: string | null;
|
||||
/** Injectable clock for deterministic age transitions in tests. */
|
||||
readonly clock?: () => number;
|
||||
/** Aging tick interval override (default derived from `staleAfterMs`). */
|
||||
readonly tickMs?: number;
|
||||
/** When false, no fetch runs (surfaces stay `unavailable`/`unknown`). */
|
||||
readonly enabled?: boolean;
|
||||
}
|
||||
|
||||
export interface FreshCollection<T> {
|
||||
/** Last verified (or restored-unverified) snapshot, or `null`. */
|
||||
readonly snapshot: FreshSnapshot<T> | null;
|
||||
/** Snapshot data or `null` — never a fabricated empty collection. */
|
||||
readonly data: T | null;
|
||||
readonly freshness: FreshnessState;
|
||||
/** True while a validation request is in flight. */
|
||||
readonly validating: boolean;
|
||||
/** Outcome of the latest failed validation, `null` when healthy. */
|
||||
readonly failure: FreshnessFailure | null;
|
||||
/** False unless freshness is `current`; drives disabled UI affordances. */
|
||||
readonly canMutate: boolean;
|
||||
/** Re-run the fetch and re-verify. Always allowed (it is a read). */
|
||||
readonly revalidate: () => Promise<void>;
|
||||
/**
|
||||
* Run a state-changing operation against verified-current data only.
|
||||
* Rejects with `StaleMutationError` on any other state — the guard fires
|
||||
* even if a disabled button was bypassed (defense in depth).
|
||||
*/
|
||||
readonly mutate: <R>(operation: (data: T) => Promise<R>) => Promise<R>;
|
||||
}
|
||||
|
||||
const defaultClock = (): number => Date.now();
|
||||
|
||||
function resolveTickMs(policy: FreshnessPolicy, override?: number): number {
|
||||
if (override !== undefined && override > 0) return override;
|
||||
return Math.min(5_000, Math.max(250, Math.floor(policy.staleAfterMs / 4)));
|
||||
}
|
||||
|
||||
function isAuthFailure(caught: unknown): boolean {
|
||||
return (
|
||||
typeof caught === 'object' &&
|
||||
caught !== null &&
|
||||
'statusCode' in caught &&
|
||||
((caught as { statusCode?: unknown }).statusCode === 401 ||
|
||||
(caught as { statusCode?: unknown }).statusCode === 403)
|
||||
);
|
||||
}
|
||||
|
||||
function fetchFailureMessage(caught: unknown): string {
|
||||
if (caught instanceof Error && caught.message.trim().length > 0) return caught.message;
|
||||
return 'The request failed.';
|
||||
}
|
||||
|
||||
/** Human-readable summary of a failure for unavailable/stale notices. */
|
||||
export function describeFailure(failure: FreshnessFailure | null): string | null {
|
||||
if (failure === null) return null;
|
||||
if (failure.kind === 'fetch') return failure.message;
|
||||
return `The snapshot was invalidated: ${invalidationReasonLabels[failure.reason]}.`;
|
||||
}
|
||||
|
||||
export function useFreshCollection<T>(options: UseFreshCollectionOptions<T>): FreshCollection<T> {
|
||||
const optionsRef = useRef(options);
|
||||
optionsRef.current = options;
|
||||
|
||||
const policy = useMemo<FreshnessPolicy>(
|
||||
() => ({ ...DEFAULT_FRESHNESS_POLICY, ...options.policy }),
|
||||
[options.policy],
|
||||
);
|
||||
const policyRef = useRef(policy);
|
||||
policyRef.current = policy;
|
||||
|
||||
const clockRef = useRef(options.clock ?? defaultClock);
|
||||
clockRef.current = options.clock ?? defaultClock;
|
||||
|
||||
const [snapshot, setSnapshot] = useState<FreshSnapshot<T> | null>(null);
|
||||
const [failure, setFailure] = useState<FreshnessFailure | null>(null);
|
||||
const [unverified, setUnverified] = useState(false);
|
||||
const [validating, setValidating] = useState(options.enabled !== false);
|
||||
const [now, setNow] = useState(() => (options.clock ?? defaultClock)());
|
||||
|
||||
const snapshotRef = useRef(snapshot);
|
||||
snapshotRef.current = snapshot;
|
||||
const failureRef = useRef(failure);
|
||||
failureRef.current = failure;
|
||||
const unverifiedRef = useRef(unverified);
|
||||
unverifiedRef.current = unverified;
|
||||
|
||||
const runRef = useRef(0);
|
||||
const abortRef = useRef<AbortController | null>(null);
|
||||
|
||||
const revalidate = useCallback(async (): Promise<void> => {
|
||||
const current = optionsRef.current;
|
||||
if (current.enabled === false) {
|
||||
setValidating(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const runId = ++runRef.current;
|
||||
abortRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
abortRef.current = controller;
|
||||
setValidating(true);
|
||||
|
||||
let value: unknown;
|
||||
try {
|
||||
value = await current.fetcher(controller.signal);
|
||||
} catch (caught) {
|
||||
if (runRef.current !== runId || controller.signal.aborted) return;
|
||||
if (isAuthFailure(caught)) {
|
||||
// An unauthenticated viewer must not keep (or be served) the
|
||||
// previous user's last-known data.
|
||||
setSnapshot(null);
|
||||
setUnverified(false);
|
||||
if (current.cacheKey) clearSnapshotCache(current.cacheKey);
|
||||
}
|
||||
setFailure({ kind: 'fetch', message: fetchFailureMessage(caught) });
|
||||
setValidating(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (runRef.current !== runId) return;
|
||||
|
||||
const result = acceptSnapshot({
|
||||
value,
|
||||
validate: current.validate,
|
||||
previous: snapshotRef.current,
|
||||
policy: policyRef.current,
|
||||
source: current.source,
|
||||
now: clockRef.current(),
|
||||
});
|
||||
|
||||
if (result.outcome === 'accepted') {
|
||||
setSnapshot(result.snapshot);
|
||||
setUnverified(false);
|
||||
setFailure(null);
|
||||
if (current.cacheKey) writeSnapshotCache(current.cacheKey, result.snapshot);
|
||||
} else {
|
||||
if (result.reason === 'cross-workspace') {
|
||||
// Data verified for a different workspace must not linger as
|
||||
// last-known situational awareness either.
|
||||
setSnapshot(null);
|
||||
setUnverified(false);
|
||||
}
|
||||
if (current.cacheKey) clearSnapshotCache(current.cacheKey);
|
||||
setFailure({ kind: 'invalidated', reason: result.reason });
|
||||
}
|
||||
setValidating(false);
|
||||
}, []);
|
||||
|
||||
// Restore the last-known snapshot (unverified) and run the first fetch.
|
||||
useEffect(() => {
|
||||
if (optionsRef.current.enabled === false) {
|
||||
setValidating(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const cacheKey = optionsRef.current.cacheKey;
|
||||
if (cacheKey) {
|
||||
const restored = readSnapshotCache<T>({
|
||||
key: cacheKey,
|
||||
workspace: policyRef.current.workspace,
|
||||
policy: policyRef.current,
|
||||
validate: optionsRef.current.validate,
|
||||
});
|
||||
if (restored.outcome === 'hit') {
|
||||
setSnapshot(restored.snapshot);
|
||||
setUnverified(true);
|
||||
} else if (restored.outcome === 'invalidated') {
|
||||
// A corrupted/foreign/regressed entry is dropped immediately; it must
|
||||
// never surface as data. The fetch decides the visible state.
|
||||
clearSnapshotCache(cacheKey);
|
||||
}
|
||||
}
|
||||
|
||||
void revalidate();
|
||||
|
||||
return () => {
|
||||
abortRef.current?.abort();
|
||||
};
|
||||
// Mount-once by design: `revalidate` is stable and reads live options
|
||||
// through refs, so it never needs to re-run when options change.
|
||||
// Route-param pages remount this hook via an identity `key` instead.
|
||||
}, [revalidate]);
|
||||
|
||||
// Aging tick: recomputes freshness as the snapshot ages past the policy.
|
||||
useEffect(() => {
|
||||
const interval = setInterval(
|
||||
() => {
|
||||
setNow(clockRef.current());
|
||||
},
|
||||
resolveTickMs(policyRef.current, optionsRef.current.tickMs),
|
||||
);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
const freshness = useMemo<FreshnessState>(() => {
|
||||
if (snapshot === null) return validating ? 'unknown' : 'unavailable';
|
||||
return computeFreshness({
|
||||
snapshot,
|
||||
policy,
|
||||
now,
|
||||
degraded: failure !== null || unverified,
|
||||
});
|
||||
// `now` from state covers age; refs inside computeFreshness are pure.
|
||||
}, [snapshot, validating, failure, unverified, now, policy]);
|
||||
|
||||
const canMutate = freshness === 'current';
|
||||
|
||||
const mutate = useCallback(async <R>(operation: (data: T) => Promise<R>): Promise<R> => {
|
||||
const currentSnapshot = snapshotRef.current;
|
||||
// No verified snapshot at all: with nothing verified there is nothing
|
||||
// current to mutate, regardless of the recorded failure.
|
||||
if (currentSnapshot === null) throw new StaleMutationError('unavailable');
|
||||
const state = computeFreshness({
|
||||
snapshot: currentSnapshot,
|
||||
policy: policyRef.current,
|
||||
now: clockRef.current(),
|
||||
degraded: failureRef.current !== null || unverifiedRef.current,
|
||||
});
|
||||
assertMutable(state);
|
||||
return operation(currentSnapshot.data);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
snapshot,
|
||||
data: snapshot === null ? null : snapshot.data,
|
||||
freshness,
|
||||
validating,
|
||||
failure,
|
||||
canMutate,
|
||||
revalidate,
|
||||
mutate,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { Mission, Project, Task } from '@/lib/types';
|
||||
import {
|
||||
validateMissionCollection,
|
||||
validateProjectCollection,
|
||||
validateProjectEntity,
|
||||
validateTaskCollection,
|
||||
} from './validators';
|
||||
import { missionFixtures, projectFixtures, taskFixtures } from '@/spa/pages/page-fixtures';
|
||||
|
||||
describe('validateTaskCollection', () => {
|
||||
it('accepts a well-formed task collection', () => {
|
||||
expect(validateTaskCollection(taskFixtures)).toEqual({
|
||||
data: taskFixtures,
|
||||
workspace: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts an empty collection (a healthy empty state is a valid payload)', () => {
|
||||
expect(validateTaskCollection([])).toEqual({ data: [], workspace: null });
|
||||
});
|
||||
|
||||
it.each([
|
||||
['not an array', { items: [] }],
|
||||
['item is not an object', ['nope']],
|
||||
['missing id', [{ ...(taskFixtures[0] as Task), id: undefined }]],
|
||||
['missing title', [{ ...(taskFixtures[0] as Task), title: undefined }]],
|
||||
['unknown status enum', [{ ...(taskFixtures[0] as Task), status: 'finished' }]],
|
||||
['unknown priority enum', [{ ...(taskFixtures[0] as Task), priority: 'urgent' }]],
|
||||
['tags of the wrong type', [{ ...(taskFixtures[0] as Task), tags: 'spa' }]],
|
||||
['metadata of the wrong type', [{ ...(taskFixtures[0] as Task), metadata: 'notes' }]],
|
||||
['createdAt of the wrong type', [{ ...(taskFixtures[0] as Task), createdAt: 1234 }]],
|
||||
['null sneaks past a required string', [{ ...(taskFixtures[0] as Task), title: null }]],
|
||||
])('rejects a malformed payload: %s', (_label, value) => {
|
||||
expect(validateTaskCollection(value)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateMissionCollection', () => {
|
||||
it('accepts a well-formed mission collection', () => {
|
||||
expect(validateMissionCollection(missionFixtures)).toEqual({
|
||||
data: missionFixtures,
|
||||
workspace: null,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['not an array', null],
|
||||
['item missing name', [{ ...(missionFixtures[0] as Mission), name: 42 }]],
|
||||
['unknown status enum', [{ ...(missionFixtures[0] as Mission), status: 'canceled' }]],
|
||||
['projectId of the wrong type', [{ ...(missionFixtures[0] as Mission), projectId: 7 }]],
|
||||
])('rejects a malformed payload: %s', (_label, value) => {
|
||||
expect(validateMissionCollection(value)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateProjectCollection', () => {
|
||||
it('accepts a uniform workspace-scoped collection and reports its workspace', () => {
|
||||
expect(validateProjectCollection(projectFixtures)).toEqual({
|
||||
data: projectFixtures,
|
||||
workspace: 'user-1',
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts an empty collection with no workspace identity', () => {
|
||||
expect(validateProjectCollection([])).toEqual({ data: [], workspace: null });
|
||||
});
|
||||
|
||||
it.each([
|
||||
['not an array', 42],
|
||||
['item missing userId', [{ ...(projectFixtures[0] as Project), userId: undefined }]],
|
||||
['unknown status enum', [{ ...(projectFixtures[0] as Project), status: 'live' }]],
|
||||
['description of the wrong type', [{ ...(projectFixtures[0] as Project), description: 1 }]],
|
||||
])('rejects a malformed payload: %s', (_label, value) => {
|
||||
expect(validateProjectCollection(value)).toBeNull();
|
||||
});
|
||||
|
||||
it('rejects a collection mixing workspace identities (cross-workspace leak)', () => {
|
||||
const mixed = [
|
||||
projectFixtures[0] as Project,
|
||||
{ ...(projectFixtures[1] as Project), userId: 'user-2' },
|
||||
];
|
||||
expect(validateProjectCollection(mixed)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateProjectEntity', () => {
|
||||
it('accepts a well-formed project and reports its workspace', () => {
|
||||
expect(validateProjectEntity(projectFixtures[0])).toEqual({
|
||||
data: projectFixtures[0],
|
||||
workspace: 'user-1',
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['not an object', 'project-1'],
|
||||
['null', null],
|
||||
['array', [projectFixtures[0]]],
|
||||
['missing userId', [{ ...(projectFixtures[0] as Project), userId: null }]],
|
||||
])('rejects a malformed entity: %s', (_label, value) => {
|
||||
expect(validateProjectEntity(value)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import type { Mission, Project, Task, MissionStatus, TaskPriority, TaskStatus } from '@/lib/types';
|
||||
import type { FreshPayload } from './model';
|
||||
|
||||
/**
|
||||
* Runtime schema validators for gateway collections (RI-5-001).
|
||||
*
|
||||
* `api<T>()` returns untrusted JSON cast to `T`; these validators are the
|
||||
* seam where a malformed response becomes an explicit schema mismatch
|
||||
* instead of flowing into the render path as if it were healthy data.
|
||||
*/
|
||||
|
||||
const taskStatuses: readonly TaskStatus[] = [
|
||||
'not-started',
|
||||
'in-progress',
|
||||
'blocked',
|
||||
'done',
|
||||
'cancelled',
|
||||
];
|
||||
const taskPriorities: readonly TaskPriority[] = ['critical', 'high', 'medium', 'low'];
|
||||
const missionStatuses: readonly MissionStatus[] = [
|
||||
'planning',
|
||||
'active',
|
||||
'paused',
|
||||
'completed',
|
||||
'failed',
|
||||
];
|
||||
const projectStatuses: readonly Project['status'][] = ['active', 'paused', 'completed', 'archived'];
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isString(value: unknown): value is string {
|
||||
return typeof value === 'string';
|
||||
}
|
||||
|
||||
function isNullableString(value: unknown): value is string | null {
|
||||
return value === null || typeof value === 'string';
|
||||
}
|
||||
|
||||
function isOneOf<T extends string>(value: unknown, allowed: readonly T[]): value is T {
|
||||
return typeof value === 'string' && (allowed as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
function isNullableRecord(value: unknown): value is Record<string, unknown> | null {
|
||||
return value === null || isRecord(value);
|
||||
}
|
||||
|
||||
function isNullableStringArray(value: unknown): value is string[] | null {
|
||||
if (value === null) return true;
|
||||
if (!Array.isArray(value)) return false;
|
||||
return value.every((item) => typeof item === 'string');
|
||||
}
|
||||
|
||||
function isIsoLike(value: unknown): value is string {
|
||||
return typeof value === 'string' && value.length > 0;
|
||||
}
|
||||
|
||||
function isTask(value: unknown): value is Task {
|
||||
if (!isRecord(value)) return false;
|
||||
return (
|
||||
isString(value['id']) &&
|
||||
isString(value['title']) &&
|
||||
isOneOf(value['status'], taskStatuses) &&
|
||||
isOneOf(value['priority'], taskPriorities) &&
|
||||
isNullableString(value['projectId']) &&
|
||||
isNullableString(value['missionId']) &&
|
||||
isNullableString(value['assignee']) &&
|
||||
isNullableStringArray(value['tags']) &&
|
||||
isNullableRecord(value['metadata']) &&
|
||||
isNullableString(value['dueDate']) &&
|
||||
isIsoLike(value['createdAt']) &&
|
||||
isIsoLike(value['updatedAt'])
|
||||
);
|
||||
}
|
||||
|
||||
/** Tasks carry no workspace identity; scope falls back to the policy. */
|
||||
export function validateTaskCollection(value: unknown): FreshPayload<Task[]> | null {
|
||||
if (!Array.isArray(value) || !value.every(isTask)) return null;
|
||||
return { data: value as Task[], workspace: null };
|
||||
}
|
||||
|
||||
function isMission(value: unknown): value is Mission {
|
||||
if (!isRecord(value)) return false;
|
||||
return (
|
||||
isString(value['id']) &&
|
||||
isString(value['name']) &&
|
||||
isOneOf(value['status'], missionStatuses) &&
|
||||
isNullableString(value['projectId']) &&
|
||||
isNullableString(value['description']) &&
|
||||
isNullableRecord(value['metadata']) &&
|
||||
isIsoLike(value['createdAt']) &&
|
||||
isIsoLike(value['updatedAt'])
|
||||
);
|
||||
}
|
||||
|
||||
/** Missions carry no workspace identity; scope falls back to the policy. */
|
||||
export function validateMissionCollection(value: unknown): FreshPayload<Mission[]> | null {
|
||||
if (!Array.isArray(value) || !value.every(isMission)) return null;
|
||||
return { data: value as Mission[], workspace: null };
|
||||
}
|
||||
|
||||
function isProject(value: unknown): value is Project {
|
||||
if (!isRecord(value)) return false;
|
||||
return (
|
||||
isString(value['id']) &&
|
||||
isString(value['name']) &&
|
||||
isOneOf(value['status'], projectStatuses) &&
|
||||
isString(value['userId']) &&
|
||||
isNullableString(value['description']) &&
|
||||
isNullableRecord(value['metadata']) &&
|
||||
isIsoLike(value['createdAt']) &&
|
||||
isIsoLike(value['updatedAt'])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Projects are workspace-scoped: every item must carry the same `userId`.
|
||||
* A collection mixing identities (cross-workspace leak) is a schema
|
||||
* mismatch; the uniform `userId` becomes the snapshot workspace.
|
||||
*/
|
||||
export function validateProjectCollection(value: unknown): FreshPayload<Project[]> | null {
|
||||
if (!Array.isArray(value) || !value.every(isProject)) return null;
|
||||
const projects = value as Project[];
|
||||
const workspaces = new Set(projects.map((project) => project.userId));
|
||||
if (workspaces.size > 1) return null;
|
||||
return { data: projects, workspace: projects.length > 0 ? projects[0]!.userId : null };
|
||||
}
|
||||
|
||||
/** Single project entity (project detail primary collection). */
|
||||
export function validateProjectEntity(value: unknown): FreshPayload<Project> | null {
|
||||
if (!isProject(value)) return null;
|
||||
const project = value as Project;
|
||||
return { data: project, workspace: project.userId };
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { ioMock } = vi.hoisted(() => ({
|
||||
ioMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('socket.io-client', () => ({
|
||||
io: ioMock,
|
||||
}));
|
||||
|
||||
import { destroySocket, getSocket } from './socket';
|
||||
|
||||
interface MockChatSocket {
|
||||
on: ReturnType<typeof vi.fn>;
|
||||
offAny: ReturnType<typeof vi.fn>;
|
||||
disconnect: ReturnType<typeof vi.fn>;
|
||||
/** Test-only helper: fires every handler registered for `event` via
|
||||
* `.on`, mirroring how a real socket.io-client instance invokes its own
|
||||
* listeners (e.g. calling the registered `disconnect` handler(s) on a
|
||||
* real transient disconnect). */
|
||||
trigger(event: string): void;
|
||||
}
|
||||
|
||||
function createMockSocket(): MockChatSocket {
|
||||
const handlers = new Map<string, Set<() => void>>();
|
||||
const mockSocket: MockChatSocket = {
|
||||
on: vi.fn((event: string, handler: () => void) => {
|
||||
if (!handlers.has(event)) handlers.set(event, new Set());
|
||||
handlers.get(event)?.add(handler);
|
||||
return mockSocket;
|
||||
}),
|
||||
offAny: vi.fn(() => mockSocket),
|
||||
disconnect: vi.fn(() => mockSocket),
|
||||
trigger(event: string): void {
|
||||
for (const handler of handlers.get(event) ?? []) handler();
|
||||
},
|
||||
};
|
||||
return mockSocket;
|
||||
}
|
||||
|
||||
let currentMock!: MockChatSocket;
|
||||
|
||||
describe('chat socket', () => {
|
||||
beforeEach(() => {
|
||||
ioMock.mockReset();
|
||||
// A fresh object per io() call so identity assertions (same singleton vs.
|
||||
// a genuinely new instance) are meaningful.
|
||||
ioMock.mockImplementation(() => {
|
||||
currentMock = createMockSocket();
|
||||
return currentMock;
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
destroySocket();
|
||||
});
|
||||
|
||||
it('creates one same-origin /chat namespace socket', () => {
|
||||
const first = getSocket();
|
||||
const second = getSocket();
|
||||
|
||||
expect(first).toBe(second);
|
||||
expect(ioMock).toHaveBeenCalledOnce();
|
||||
expect(ioMock).toHaveBeenCalledWith('/chat', {
|
||||
withCredentials: true,
|
||||
autoConnect: false,
|
||||
transports: ['websocket', 'polling'],
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the same singleton instance across a transient disconnect', () => {
|
||||
const first = getSocket();
|
||||
|
||||
// socket.ts must not react to a real socket's `disconnect` event by
|
||||
// nulling the singleton — it registers no such handler at all now.
|
||||
// Actually fire every handler registered via `.on('disconnect', ...)`
|
||||
// (mirroring a real socket.io-client reconnect) instead of merely
|
||||
// calling getSocket() again: this is what makes the test fail if
|
||||
// production reintroduces `socket.on('disconnect', () => { socket =
|
||||
// null; })`, since that handler would run here and null the singleton
|
||||
// before the next getSocket() call.
|
||||
currentMock.trigger('disconnect');
|
||||
const second = getSocket();
|
||||
|
||||
expect(second).toBe(first);
|
||||
expect(ioMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('only creates a new singleton after an explicit destroySocket()', () => {
|
||||
const first = getSocket();
|
||||
|
||||
destroySocket();
|
||||
const second = getSocket();
|
||||
|
||||
expect(second).not.toBe(first);
|
||||
expect(ioMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { io } from 'socket.io-client';
|
||||
import type { ChatSocket } from './chat-contract';
|
||||
|
||||
let socket: ChatSocket | null = null;
|
||||
|
||||
export function getSocket(): ChatSocket {
|
||||
if (!socket) {
|
||||
// socket.io-client 4.8.3's `io()` factory declaration always returns the
|
||||
// default unparameterized Socket (it accepts no <ListenEvents, EmitEvents>
|
||||
// generics), so this one cast is the unavoidable boundary between that and the
|
||||
// typed `/chat` contract. Every other call site uses the resulting ChatSocket
|
||||
// with no further assertions.
|
||||
socket = io('/chat', {
|
||||
withCredentials: true,
|
||||
autoConnect: false,
|
||||
transports: ['websocket', 'polling'],
|
||||
}) as unknown as ChatSocket;
|
||||
|
||||
// A transient `disconnect` (network blip, server restart) must NOT null
|
||||
// the singleton: socket.io-client auto-reconnects this same instance,
|
||||
// and its listeners stay registered across that reconnect. Nulling here
|
||||
// previously orphaned those listeners on the next getSocket() call by
|
||||
// handing back a brand-new, unconnected instance. Only destroySocket()
|
||||
// (an explicit, intentional teardown) may reset the singleton.
|
||||
}
|
||||
return socket;
|
||||
}
|
||||
|
||||
/** Tear down the singleton socket and reset the reference. */
|
||||
export function destroySocket(): void {
|
||||
if (socket) {
|
||||
socket.offAny();
|
||||
socket.disconnect();
|
||||
socket = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
export type SsoProtocol = 'oidc' | 'saml';
|
||||
export type SsoLoginMode = 'oidc' | 'saml' | null;
|
||||
|
||||
export interface SsoProviderDiscovery {
|
||||
id: 'authentik' | 'workos' | 'keycloak';
|
||||
name: string;
|
||||
protocols: SsoProtocol[];
|
||||
configured: boolean;
|
||||
loginMode: SsoLoginMode;
|
||||
callbackPath: string | null;
|
||||
teamSync: {
|
||||
enabled: boolean;
|
||||
claim: string | null;
|
||||
};
|
||||
samlFallback: {
|
||||
configured: boolean;
|
||||
loginUrl: string | null;
|
||||
};
|
||||
warnings: string[];
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import type {
|
||||
HarnessAuthState,
|
||||
HarnessModelAvailability,
|
||||
HarnessSelection,
|
||||
} from '@mosaicstack/types';
|
||||
|
||||
// The exact harness/provider/model tuple and its closed enum companions are the
|
||||
// shared domain types — re-exported here so web consumers (and the runtime
|
||||
// guards) import one shape, never a divergent local redefinition.
|
||||
export type { HarnessSelection, HarnessAuthState, HarnessModelAvailability };
|
||||
|
||||
/** Harness summary row from `GET /api/harnesses` (the `HarnessSummaryDto`). The
|
||||
* harness id is kept distinct from any provider id — they are never merged. */
|
||||
export interface HarnessSummary {
|
||||
id: string;
|
||||
displayName: string;
|
||||
capabilities: string[];
|
||||
}
|
||||
|
||||
/** One selectable model in a harness catalog. Extends the `{harnessId,
|
||||
* providerId, modelId}` tuple with the display/availability metadata the UI
|
||||
* needs; `inputTypes` is kept as a plain `string[]` on the client boundary
|
||||
* because it arrives from untrusted JSON and is only ever displayed. */
|
||||
export interface HarnessCatalogEntry extends HarnessSelection {
|
||||
displayName: string;
|
||||
reasoningCapability: boolean;
|
||||
inputTypes: string[];
|
||||
authState: HarnessAuthState;
|
||||
availability: HarnessModelAvailability;
|
||||
}
|
||||
|
||||
/** Harness-scoped catalog from `GET /api/harnesses/:harnessId/catalog`. */
|
||||
export interface HarnessCatalog {
|
||||
harnessId: string;
|
||||
version: string;
|
||||
fingerprint: string;
|
||||
models: HarnessCatalogEntry[];
|
||||
}
|
||||
|
||||
/** Conversation returned by the gateway API. */
|
||||
export interface Conversation {
|
||||
id: string;
|
||||
userId: string;
|
||||
title: string | null;
|
||||
projectId: string | null;
|
||||
archived: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** Message within a conversation. */
|
||||
export interface Message {
|
||||
id: string;
|
||||
conversationId: string;
|
||||
role: 'user' | 'assistant' | 'system';
|
||||
content: string;
|
||||
thinking?: string;
|
||||
model?: string;
|
||||
provider?: string;
|
||||
promptTokens?: number;
|
||||
completionTokens?: number;
|
||||
totalTokens?: number;
|
||||
metadata?: Record<string, unknown>;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
/** Model definition returned by provider APIs. */
|
||||
export interface ModelInfo {
|
||||
id: string;
|
||||
provider: string;
|
||||
name: string;
|
||||
reasoning: boolean;
|
||||
contextWindow: number;
|
||||
maxTokens: number;
|
||||
inputTypes: Array<'text' | 'image'>;
|
||||
cost: {
|
||||
input: number;
|
||||
output: number;
|
||||
cacheRead: number;
|
||||
cacheWrite: number;
|
||||
};
|
||||
}
|
||||
|
||||
/** Provider with associated models. */
|
||||
export interface ProviderInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
available: boolean;
|
||||
models: ModelInfo[];
|
||||
}
|
||||
|
||||
/** Task statuses. */
|
||||
export type TaskStatus = 'not-started' | 'in-progress' | 'blocked' | 'done' | 'cancelled';
|
||||
|
||||
/** Task priorities. */
|
||||
export type TaskPriority = 'critical' | 'high' | 'medium' | 'low';
|
||||
|
||||
/** Task returned by the gateway API. */
|
||||
export interface Task {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
status: TaskStatus;
|
||||
priority: TaskPriority;
|
||||
projectId: string | null;
|
||||
missionId: string | null;
|
||||
assignee: string | null;
|
||||
tags: string[] | null;
|
||||
dueDate: string | null;
|
||||
metadata: Record<string, unknown> | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** Project statuses. */
|
||||
export type ProjectStatus = 'active' | 'paused' | 'completed' | 'archived';
|
||||
|
||||
/** Project returned by the gateway API. */
|
||||
export interface Project {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
status: ProjectStatus;
|
||||
userId: string;
|
||||
ownerId?: string;
|
||||
metadata: Record<string, unknown> | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** Mission statuses. */
|
||||
export type MissionStatus = 'planning' | 'active' | 'paused' | 'completed' | 'failed';
|
||||
|
||||
/** Mission returned by the gateway API. */
|
||||
export interface Mission {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
status: MissionStatus;
|
||||
projectId: string | null;
|
||||
metadata: Record<string, unknown> | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { RouterProvider } from 'react-router-dom';
|
||||
import { ThemeProvider } from '@/providers/theme-provider';
|
||||
import { createAppRouter } from '@/routes';
|
||||
import '@/globals.css';
|
||||
|
||||
const container = document.getElementById('root');
|
||||
if (!container) {
|
||||
throw new Error('missing #root element');
|
||||
}
|
||||
|
||||
createRoot(container).render(
|
||||
<StrictMode>
|
||||
<ThemeProvider>
|
||||
<RouterProvider router={createAppRouter()} />
|
||||
</ThemeProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,60 @@
|
||||
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
|
||||
export type Theme = 'dark' | 'light';
|
||||
|
||||
interface ThemeContextValue {
|
||||
theme: Theme;
|
||||
toggleTheme: () => void;
|
||||
setTheme: (theme: Theme) => void;
|
||||
}
|
||||
|
||||
const STORAGE_KEY = 'mosaic-theme';
|
||||
const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);
|
||||
|
||||
function getInitialTheme(): Theme {
|
||||
if (typeof document === 'undefined') {
|
||||
return 'dark';
|
||||
}
|
||||
|
||||
return document.documentElement.getAttribute('data-theme') === 'light' ? 'light' : 'dark';
|
||||
}
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }): React.JSX.Element {
|
||||
const [theme, setThemeState] = useState<Theme>(getInitialTheme);
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
window.localStorage.setItem(STORAGE_KEY, theme);
|
||||
}, [theme]);
|
||||
|
||||
useEffect(() => {
|
||||
const storedTheme = window.localStorage.getItem(STORAGE_KEY);
|
||||
if (storedTheme === 'light' || storedTheme === 'dark') {
|
||||
setThemeState(storedTheme);
|
||||
return;
|
||||
}
|
||||
|
||||
document.documentElement.setAttribute('data-theme', 'dark');
|
||||
}, []);
|
||||
|
||||
const value = useMemo<ThemeContextValue>(
|
||||
() => ({
|
||||
theme,
|
||||
toggleTheme: () => setThemeState((current) => (current === 'dark' ? 'light' : 'dark')),
|
||||
setTheme: (nextTheme) => setThemeState(nextTheme),
|
||||
}),
|
||||
[theme],
|
||||
);
|
||||
|
||||
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
|
||||
}
|
||||
|
||||
export function useTheme(): ThemeContextValue {
|
||||
const context = useContext(ThemeContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error('useTheme must be used within ThemeProvider');
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { ReactElement } from 'react';
|
||||
import { createBrowserRouter, Navigate, Outlet, type RouteObject } from 'react-router-dom';
|
||||
import { LoginPage } from '@/spa/pages/login';
|
||||
import { RegisterPage } from '@/spa/pages/register';
|
||||
import { SsoCallbackPage } from '@/spa/pages/sso-callback';
|
||||
import { ChatPage } from '@/spa/pages/chat';
|
||||
import { ChatRouteErrorBoundary } from '@/spa/pages/chat-error-boundary';
|
||||
import { ProjectDetailPage } from '@/spa/pages/project-detail';
|
||||
import { ProjectsPage } from '@/spa/pages/projects';
|
||||
import {
|
||||
ProjectDetailRouteErrorBoundary,
|
||||
ProjectsRouteErrorBoundary,
|
||||
TasksRouteErrorBoundary,
|
||||
} from '@/spa/pages/resource-route-error-boundaries';
|
||||
import { TasksPage } from '@/spa/pages/tasks';
|
||||
import { SettingsPage } from '@/spa/pages/settings';
|
||||
import { AdminPage } from '@/spa/pages/admin';
|
||||
import { AdminGuard, AuthGuard, GuestGuard } from '@/spa/guards';
|
||||
import { AppShell } from '@/components/layout/app-shell';
|
||||
|
||||
function DashboardLayout(): ReactElement {
|
||||
return (
|
||||
<AppShell>
|
||||
<Outlet />
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
|
||||
function GuestLayout(): ReactElement {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-surface-bg px-4 py-8">
|
||||
<div className="w-full max-w-md rounded-xl border border-surface-border bg-surface-card p-8 shadow-lg">
|
||||
<Outlet />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const routes: RouteObject[] = [
|
||||
{
|
||||
element: <GuestGuard />,
|
||||
children: [
|
||||
{
|
||||
element: <GuestLayout />,
|
||||
children: [
|
||||
{ path: '/login', element: <LoginPage /> },
|
||||
{ path: '/register', element: <RegisterPage /> },
|
||||
{ path: '/auth/provider/:provider', element: <SsoCallbackPage /> },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
element: <AuthGuard />,
|
||||
children: [
|
||||
{
|
||||
element: <DashboardLayout />,
|
||||
children: [
|
||||
{ path: '/', element: <Navigate to="/chat" replace /> },
|
||||
{ path: '/chat', element: <ChatPage />, errorElement: <ChatRouteErrorBoundary /> },
|
||||
{
|
||||
path: '/projects',
|
||||
element: <ProjectsPage />,
|
||||
errorElement: <ProjectsRouteErrorBoundary />,
|
||||
},
|
||||
{
|
||||
path: '/projects/:id',
|
||||
element: <ProjectDetailPage />,
|
||||
errorElement: <ProjectDetailRouteErrorBoundary />,
|
||||
},
|
||||
{ path: '/tasks', element: <TasksPage />, errorElement: <TasksRouteErrorBoundary /> },
|
||||
{ path: '/settings', element: <SettingsPage /> },
|
||||
{
|
||||
element: <AdminGuard />,
|
||||
children: [{ path: '/admin', element: <AdminPage /> }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export function createAppRouter(): ReturnType<typeof createBrowserRouter> {
|
||||
return createBrowserRouter(routes);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
fetchCatalog,
|
||||
fetchHarnesses,
|
||||
fetchPersistedSelection,
|
||||
persistSelection,
|
||||
} from './chat-api';
|
||||
|
||||
function json(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
function stubFetch(): ReturnType<typeof vi.fn> {
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
return fetchMock;
|
||||
}
|
||||
|
||||
/** Every URL the client actually requested, across all calls. */
|
||||
function requestedUrls(fetchMock: ReturnType<typeof vi.fn>): string[] {
|
||||
return fetchMock.mock.calls.map((call) => String(call[0]));
|
||||
}
|
||||
|
||||
describe('chat-api', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('fetchHarnesses GETs /api/harnesses and returns typed summaries (harness id separate from provider)', async () => {
|
||||
const fetchMock = stubFetch();
|
||||
fetchMock.mockResolvedValue(
|
||||
json([
|
||||
{ id: 'pi', displayName: 'Pi', capabilities: ['chat', 'tools'] },
|
||||
{ id: 'openai', displayName: 'OpenAI', capabilities: ['chat'] },
|
||||
]),
|
||||
);
|
||||
|
||||
const harnesses = await fetchHarnesses();
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
expect(String(fetchMock.mock.calls[0]?.[0])).toBe('/api/harnesses');
|
||||
expect(harnesses).toEqual([
|
||||
{ id: 'pi', displayName: 'Pi', capabilities: ['chat', 'tools'] },
|
||||
{ id: 'openai', displayName: 'OpenAI', capabilities: ['chat'] },
|
||||
]);
|
||||
});
|
||||
|
||||
it('fetchCatalog GETs the harness-scoped catalog and returns only its model entries', async () => {
|
||||
const fetchMock = stubFetch();
|
||||
fetchMock.mockResolvedValue(
|
||||
json({
|
||||
harnessId: 'pi',
|
||||
version: '2026-08-11',
|
||||
fingerprint: 'abc123',
|
||||
models: [
|
||||
{
|
||||
harnessId: 'pi',
|
||||
providerId: 'openai',
|
||||
modelId: 'gpt-5',
|
||||
displayName: 'GPT-5',
|
||||
reasoningCapability: true,
|
||||
inputTypes: ['text'],
|
||||
authState: 'ready',
|
||||
availability: 'available',
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await fetchCatalog('pi');
|
||||
|
||||
expect(String(fetchMock.mock.calls[0]?.[0])).toBe('/api/harnesses/pi/catalog');
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error('expected ok catalog');
|
||||
expect(result.catalog.harnessId).toBe('pi');
|
||||
expect(result.catalog.models).toHaveLength(1);
|
||||
expect(result.catalog.models[0]).toMatchObject({
|
||||
harnessId: 'pi',
|
||||
providerId: 'openai',
|
||||
modelId: 'gpt-5',
|
||||
availability: 'available',
|
||||
});
|
||||
});
|
||||
|
||||
it('normalizes a catalog 404 into a typed catalog_unavailable result without surfacing the raw body', async () => {
|
||||
const fetchMock = stubFetch();
|
||||
fetchMock.mockResolvedValue(
|
||||
json(
|
||||
{
|
||||
code: 'adapter_unavailable',
|
||||
message: 'raw gateway detail that must not leak verbatim',
|
||||
harnessId: 'attacker-echo',
|
||||
extra: { hostile: 'blob' },
|
||||
},
|
||||
404,
|
||||
),
|
||||
);
|
||||
|
||||
const result = await fetchCatalog('ghost');
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error('expected unavailable result');
|
||||
expect(result.code).toBe('catalog_unavailable');
|
||||
// harnessId comes from the request, never the (untrusted) response body.
|
||||
expect(result.harnessId).toBe('ghost');
|
||||
expect(typeof result.message).toBe('string');
|
||||
// The raw response body is never rendered/returned verbatim.
|
||||
expect(JSON.stringify(result)).not.toContain('hostile');
|
||||
expect(JSON.stringify(result)).not.toContain('attacker-echo');
|
||||
});
|
||||
|
||||
it('fetchPersistedSelection returns the stored tuple, or null when unset', async () => {
|
||||
const fetchMock = stubFetch();
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
json({ selection: { harnessId: 'pi', providerId: 'openai', modelId: 'gpt-5' } }),
|
||||
);
|
||||
await expect(fetchPersistedSelection()).resolves.toEqual({
|
||||
harnessId: 'pi',
|
||||
providerId: 'openai',
|
||||
modelId: 'gpt-5',
|
||||
});
|
||||
expect(String(fetchMock.mock.calls[0]?.[0])).toBe('/api/chat/preferences/selection');
|
||||
|
||||
fetchMock.mockResolvedValueOnce(json({ selection: null }));
|
||||
await expect(fetchPersistedSelection()).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('persistSelection PUTs the structured tuple (not free text) and returns the confirmed selection', async () => {
|
||||
const fetchMock = stubFetch();
|
||||
fetchMock.mockResolvedValue(
|
||||
json({ selection: { harnessId: 'pi', providerId: 'openai', modelId: 'gpt-5' } }),
|
||||
);
|
||||
|
||||
const result = await persistSelection({
|
||||
harnessId: 'pi',
|
||||
providerId: 'openai',
|
||||
modelId: 'gpt-5',
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
const call = fetchMock.mock.calls[0];
|
||||
expect(String(call?.[0])).toBe('/api/chat/preferences/selection');
|
||||
const init = call?.[1] as RequestInit;
|
||||
expect(String(init.method).toUpperCase()).toBe('PUT');
|
||||
// The body is exactly the structured tuple — harness/provider/model kept distinct.
|
||||
expect(JSON.parse(String(init.body))).toEqual({
|
||||
harnessId: 'pi',
|
||||
providerId: 'openai',
|
||||
modelId: 'gpt-5',
|
||||
});
|
||||
});
|
||||
|
||||
it('normalizes a selection 422 into a typed error preserving the requested tuple exactly', async () => {
|
||||
const fetchMock = stubFetch();
|
||||
fetchMock.mockResolvedValue(
|
||||
json(
|
||||
{
|
||||
code: 'model_unavailable',
|
||||
message: 'raw detail that must not leak',
|
||||
selection: { harnessId: 'x', providerId: 'y', modelId: 'z' },
|
||||
},
|
||||
422,
|
||||
),
|
||||
);
|
||||
|
||||
const requested = { harnessId: 'pi', providerId: 'openai', modelId: 'gpt-5' };
|
||||
const result = await persistSelection(requested);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error('expected failed persist');
|
||||
expect(['selection_invalid', 'model_unavailable']).toContain(result.code);
|
||||
// The requested tuple is preserved unchanged — not replaced by the body's echo.
|
||||
expect(result.requested).toEqual(requested);
|
||||
expect(JSON.stringify(result)).not.toContain('raw detail');
|
||||
});
|
||||
|
||||
it('never requests any /api/providers* endpoint', async () => {
|
||||
const fetchMock = stubFetch();
|
||||
fetchMock.mockResolvedValue(json([]));
|
||||
await fetchHarnesses();
|
||||
fetchMock.mockResolvedValue(
|
||||
json({ harnessId: 'pi', version: '1', fingerprint: 'f', models: [] }),
|
||||
);
|
||||
await fetchCatalog('pi');
|
||||
fetchMock.mockResolvedValue(json({ selection: null }));
|
||||
await fetchPersistedSelection();
|
||||
|
||||
for (const url of requestedUrls(fetchMock)) {
|
||||
expect(url).not.toContain('/api/providers');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* Typed fetch wrappers for the Task-3 harness HTTP contract the chat selection
|
||||
* UI depends on. Every response body is untrusted and is normalized through the
|
||||
* runtime guards before it reaches state — a 404 (catalog) and a 422 (selection)
|
||||
* are mapped to typed, body-free error results so a raw gateway body is never
|
||||
* rendered, and the caller's requested tuple is preserved verbatim on failure.
|
||||
*
|
||||
* This module talks ONLY to the harness/chat-preferences endpoints. It never
|
||||
* calls `/api/providers*` — provider identity lives inside the harness catalog.
|
||||
*/
|
||||
import { asHarnessCatalog, asHarnessSelection, asHarnessSummaries } from './runtime-guards';
|
||||
import type { HarnessCatalog, HarnessSelection, HarnessSummary } from '@/lib/types';
|
||||
|
||||
/** A catalog fetch either yields the typed catalog or a typed unavailability —
|
||||
* never a thrown raw body. */
|
||||
export type CatalogResult =
|
||||
| { ok: true; catalog: HarnessCatalog }
|
||||
| { ok: false; code: 'catalog_unavailable'; harnessId: string; message: string };
|
||||
|
||||
export type SelectionErrorCode = 'selection_invalid' | 'model_unavailable';
|
||||
|
||||
/** A persist either confirms the stored tuple or reports a typed domain failure
|
||||
* that echoes back the exact tuple the caller requested. */
|
||||
export type SelectionPersistResult =
|
||||
| { ok: true; selection: HarnessSelection }
|
||||
| { ok: false; code: SelectionErrorCode; message: string; requested: HarnessSelection };
|
||||
|
||||
/** A safe, generic message for an unavailable catalog — the raw 404 body is
|
||||
* never surfaced. */
|
||||
const CATALOG_UNAVAILABLE_MESSAGE = 'This harness catalog is currently unavailable.';
|
||||
|
||||
/** A safe, generic message for a rejected selection. The untrusted 422 body's
|
||||
* own `message` is deliberately NEVER surfaced — only this fixed copy — so a
|
||||
* raw gateway detail can never leak into the UI. Only the closed `code` enum is
|
||||
* read from the body. */
|
||||
const SELECTION_REJECTED_MESSAGE = 'This selection was rejected.';
|
||||
|
||||
async function readJson(response: Response): Promise<unknown> {
|
||||
return response.json().catch(() => null);
|
||||
}
|
||||
|
||||
function safeSelectionCode(body: unknown): SelectionErrorCode {
|
||||
if (typeof body === 'object' && body !== null && 'code' in body) {
|
||||
const code = (body as { code: unknown }).code;
|
||||
if (code === 'selection_invalid' || code === 'model_unavailable') return code;
|
||||
}
|
||||
// Default to the more conservative "invalid" classification for anything
|
||||
// unrecognized rather than guessing "model_unavailable".
|
||||
return 'selection_invalid';
|
||||
}
|
||||
|
||||
/** `GET /api/harnesses` → the list of harness summaries. A non-OK response
|
||||
* normalizes to an empty list (the UI then has no harness to select). */
|
||||
export async function fetchHarnesses(): Promise<HarnessSummary[]> {
|
||||
const response = await fetch('/api/harnesses', {
|
||||
credentials: 'include',
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok) return [];
|
||||
return asHarnessSummaries(await readJson(response));
|
||||
}
|
||||
|
||||
/** `GET /api/harnesses/:harnessId/catalog` → the harness-scoped catalog. A 404
|
||||
* (or any non-OK) becomes a typed `catalog_unavailable` result rather than a
|
||||
* fallback catalog or a rendered raw body. */
|
||||
export async function fetchCatalog(harnessId: string): Promise<CatalogResult> {
|
||||
const response = await fetch(`/api/harnesses/${encodeURIComponent(harnessId)}/catalog`, {
|
||||
credentials: 'include',
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
code: 'catalog_unavailable',
|
||||
// Scoped to the requested harness id, never the untrusted body's echo.
|
||||
harnessId,
|
||||
message: CATALOG_UNAVAILABLE_MESSAGE,
|
||||
};
|
||||
}
|
||||
return { ok: true, catalog: asHarnessCatalog(await readJson(response), harnessId) };
|
||||
}
|
||||
|
||||
/** `GET /api/chat/preferences/selection` → the persisted tuple, or null when
|
||||
* unset or malformed. */
|
||||
export async function fetchPersistedSelection(): Promise<HarnessSelection | null> {
|
||||
const response = await fetch('/api/chat/preferences/selection', {
|
||||
credentials: 'include',
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok) return null;
|
||||
const body = await readJson(response);
|
||||
if (typeof body !== 'object' || body === null) return null;
|
||||
return asHarnessSelection((body as { selection?: unknown }).selection);
|
||||
}
|
||||
|
||||
/** `PUT /api/chat/preferences/selection` with the structured tuple as the body.
|
||||
* On success returns the confirmed selection; on a typed domain failure (422)
|
||||
* or validation error, returns a typed result carrying the EXACT requested
|
||||
* tuple — never the body's echo — and never the raw body text. */
|
||||
export async function persistSelection(
|
||||
selection: HarnessSelection,
|
||||
): Promise<SelectionPersistResult> {
|
||||
const requested: HarnessSelection = {
|
||||
harnessId: selection.harnessId,
|
||||
providerId: selection.providerId,
|
||||
modelId: selection.modelId,
|
||||
};
|
||||
const response = await fetch('/api/chat/preferences/selection', {
|
||||
method: 'PUT',
|
||||
credentials: 'include',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(requested),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const body = await readJson(response);
|
||||
return {
|
||||
ok: false,
|
||||
code: safeSelectionCode(body),
|
||||
// Fixed copy only — the untrusted body's message is never surfaced.
|
||||
message: SELECTION_REJECTED_MESSAGE,
|
||||
requested,
|
||||
};
|
||||
}
|
||||
const body = await readJson(response);
|
||||
const confirmed =
|
||||
typeof body === 'object' && body !== null
|
||||
? asHarnessSelection((body as { selection?: unknown }).selection)
|
||||
: null;
|
||||
// A malformed 2xx body is treated as a confirmation of exactly what we sent —
|
||||
// the server accepted the tuple, so the requested tuple is the source of truth.
|
||||
return { ok: true, selection: confirmed ?? requested };
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { CommandsPanel } from './commands-panel';
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
});
|
||||
|
||||
let root: Root | null;
|
||||
let container: HTMLElement | null;
|
||||
|
||||
async function render(node: Parameters<Root['render']>[0]): Promise<void> {
|
||||
container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
await act(async () => {
|
||||
root?.render(node);
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
document.body.replaceChildren();
|
||||
root = null;
|
||||
container = null;
|
||||
});
|
||||
|
||||
describe('CommandsPanel', () => {
|
||||
it('shows the frozen local pendingApproval args in the confirmation area, regardless of misleading server message text', async () => {
|
||||
await render(
|
||||
<CommandsPanel
|
||||
manifest={null}
|
||||
results={[]}
|
||||
approval={{
|
||||
conversationId: 'c1',
|
||||
command: 'deploy', // matches pendingApproval — this is a legitimately approved request
|
||||
success: true,
|
||||
approvalId: 'ap1',
|
||||
expiresAt: '2026-01-01T00:00:00.000Z',
|
||||
// Free-text server message claims a different, less alarming target
|
||||
// than what will actually be sent — the UI must not rely on this.
|
||||
message: 'This will only affect the staging environment.',
|
||||
}}
|
||||
pendingApproval={{ command: 'deploy', args: 'prod' }}
|
||||
hasConversation
|
||||
onExecute={vi.fn()}
|
||||
onApprove={vi.fn()}
|
||||
onRunApproved={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
// The exact frozen combined action is visible...
|
||||
expect(container?.textContent).toContain('/deploy');
|
||||
expect(container?.textContent).toContain('prod');
|
||||
// ...and the misleading server free-text is never shown next to it.
|
||||
expect(container?.textContent).not.toContain('staging environment');
|
||||
});
|
||||
|
||||
it('does not throw when a manifest commands entry is null', async () => {
|
||||
const manifest = {
|
||||
commands: [
|
||||
null,
|
||||
{
|
||||
name: 'model',
|
||||
aliases: [],
|
||||
description: 'Change the active model',
|
||||
scope: 'core',
|
||||
execution: 'socket',
|
||||
available: true,
|
||||
},
|
||||
],
|
||||
skills: [null],
|
||||
version: 1,
|
||||
} as unknown as Parameters<typeof CommandsPanel>[0]['manifest'];
|
||||
|
||||
await expect(
|
||||
render(
|
||||
<CommandsPanel
|
||||
manifest={manifest}
|
||||
results={[]}
|
||||
approval={null}
|
||||
pendingApproval={null}
|
||||
hasConversation={false}
|
||||
onExecute={vi.fn()}
|
||||
onApprove={vi.fn()}
|
||||
onRunApproved={vi.fn()}
|
||||
/>,
|
||||
),
|
||||
).resolves.not.toThrow();
|
||||
|
||||
expect(container?.textContent).toContain('model');
|
||||
});
|
||||
|
||||
it('shows an explicit no-args fallback when the frozen pendingApproval has no args', async () => {
|
||||
await render(
|
||||
<CommandsPanel
|
||||
manifest={null}
|
||||
results={[]}
|
||||
approval={{
|
||||
conversationId: 'c1',
|
||||
command: 'deploy',
|
||||
success: true,
|
||||
approvalId: 'ap1',
|
||||
expiresAt: '2026-01-01T00:00:00.000Z',
|
||||
}}
|
||||
pendingApproval={{ command: 'deploy' }}
|
||||
hasConversation
|
||||
onExecute={vi.fn()}
|
||||
onApprove={vi.fn()}
|
||||
onRunApproved={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(container?.textContent?.toLowerCase()).toContain('no args');
|
||||
});
|
||||
|
||||
it('renders skills from a skills-only manifest', async () => {
|
||||
await render(
|
||||
<CommandsPanel
|
||||
manifest={{
|
||||
commands: [],
|
||||
skills: [{ name: 'brave-search', description: 'Search the web', available: true }],
|
||||
version: 1,
|
||||
}}
|
||||
results={[]}
|
||||
approval={null}
|
||||
pendingApproval={null}
|
||||
hasConversation={false}
|
||||
onExecute={vi.fn()}
|
||||
onApprove={vi.fn()}
|
||||
onRunApproved={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(container?.textContent).toContain('brave-search');
|
||||
expect(container?.textContent).toContain('Search the web');
|
||||
});
|
||||
|
||||
it('does not show the Run affordance when approval.success/approvalId are objects, even though command matches pendingApproval', async () => {
|
||||
const approval = {
|
||||
conversationId: 'c1',
|
||||
command: 'deploy',
|
||||
success: { truthy: 'object' },
|
||||
approvalId: { also: 'object' },
|
||||
} as unknown as Parameters<typeof CommandsPanel>[0]['approval'];
|
||||
|
||||
await render(
|
||||
<CommandsPanel
|
||||
manifest={null}
|
||||
results={[]}
|
||||
approval={approval}
|
||||
pendingApproval={{ command: 'deploy', args: 'prod' }}
|
||||
hasConversation
|
||||
onExecute={vi.fn()}
|
||||
onApprove={vi.fn()}
|
||||
onRunApproved={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(
|
||||
[...(container?.querySelectorAll('button') ?? [])].some((button) =>
|
||||
button.textContent?.includes('Run approved command'),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('shows the guarded server-provided denial reason for a denied approval', async () => {
|
||||
await render(
|
||||
<CommandsPanel
|
||||
manifest={null}
|
||||
results={[]}
|
||||
approval={{
|
||||
conversationId: 'c1',
|
||||
command: 'deploy',
|
||||
success: false,
|
||||
message: 'Not authorized',
|
||||
}}
|
||||
pendingApproval={{ command: 'deploy', args: 'prod' }}
|
||||
hasConversation
|
||||
onExecute={vi.fn()}
|
||||
onApprove={vi.fn()}
|
||||
onRunApproved={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(container?.textContent).toContain('Not authorized');
|
||||
});
|
||||
|
||||
it('falls back to a stable "Denied." copy when a denial has no usable message', async () => {
|
||||
await render(
|
||||
<CommandsPanel
|
||||
manifest={null}
|
||||
results={[]}
|
||||
approval={{ conversationId: 'c1', command: 'deploy', success: false }}
|
||||
pendingApproval={{ command: 'deploy', args: 'prod' }}
|
||||
hasConversation
|
||||
onExecute={vi.fn()}
|
||||
onApprove={vi.fn()}
|
||||
onRunApproved={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(container?.textContent).toContain('Denied.');
|
||||
});
|
||||
|
||||
it('shows the guarded contract-provided reason for a failed command result, falling back to a stable copy only when absent', async () => {
|
||||
await render(
|
||||
<CommandsPanel
|
||||
manifest={null}
|
||||
results={[
|
||||
{ conversationId: 'c1', command: 'model', success: false, message: 'Unknown model' },
|
||||
{ conversationId: 'c1', command: 'deploy', success: false },
|
||||
]}
|
||||
approval={null}
|
||||
pendingApproval={null}
|
||||
hasConversation={false}
|
||||
onExecute={vi.fn()}
|
||||
onApprove={vi.fn()}
|
||||
onRunApproved={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(container?.textContent).toContain('Unknown model');
|
||||
expect(container?.textContent).toContain('Command failed.');
|
||||
});
|
||||
|
||||
it('bounds an oversized command result message at the render site as defense-in-depth', async () => {
|
||||
const hostileMessage = 'y'.repeat(50_000);
|
||||
await render(
|
||||
<CommandsPanel
|
||||
manifest={null}
|
||||
results={[
|
||||
{ conversationId: 'c1', command: 'model', success: false, message: hostileMessage },
|
||||
]}
|
||||
approval={null}
|
||||
pendingApproval={null}
|
||||
hasConversation={false}
|
||||
onExecute={vi.fn()}
|
||||
onApprove={vi.fn()}
|
||||
onRunApproved={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
const text = container?.textContent ?? '';
|
||||
expect(text.length).toBeLessThan(hostileMessage.length);
|
||||
});
|
||||
|
||||
it('does not throw when the manifest fields are malformed (non-array commands/skills)', async () => {
|
||||
const manifest = {
|
||||
commands: 'not-an-array',
|
||||
skills: null,
|
||||
version: 1,
|
||||
} as unknown as Parameters<typeof CommandsPanel>[0]['manifest'];
|
||||
|
||||
await expect(
|
||||
render(
|
||||
<CommandsPanel
|
||||
manifest={manifest}
|
||||
results={[]}
|
||||
approval={null}
|
||||
pendingApproval={null}
|
||||
hasConversation={false}
|
||||
onExecute={vi.fn()}
|
||||
onApprove={vi.fn()}
|
||||
onRunApproved={vi.fn()}
|
||||
/>,
|
||||
),
|
||||
).resolves.not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,164 @@
|
||||
import { useState, type ReactElement } from 'react';
|
||||
import type { PendingApproval } from './use-chat-connection';
|
||||
import { MAX_COMMAND_MESSAGE_CHARS } from './limits';
|
||||
import { asNonEmptyString, asString } from './runtime-guards';
|
||||
import type {
|
||||
CommandManifest,
|
||||
SlashCommandApprovalResultPayload,
|
||||
SlashCommandResultPayload,
|
||||
} from '@/lib/chat-contract';
|
||||
|
||||
/** Stable fallback copy shown for a failed command only when the server's
|
||||
* own guarded, non-empty `message` (e.g. "Unknown model") is absent or
|
||||
* malformed — the structured contract reason itself is otherwise shown
|
||||
* directly, never a raw thrown exception, stack trace, or object value. */
|
||||
const COMMAND_FAILURE_COPY = 'Command failed.';
|
||||
|
||||
/** Render-site defense-in-depth: `use-chat-connection.ts` already bounds a
|
||||
* stored command:result message at ingestion, but this component must never
|
||||
* assume every caller went through that path — bounding again here means a
|
||||
* hostile/oversized message can never force an unbounded render. */
|
||||
function boundMessage(value: string): string {
|
||||
return value.length > MAX_COMMAND_MESSAGE_CHARS
|
||||
? value.slice(0, MAX_COMMAND_MESSAGE_CHARS)
|
||||
: value;
|
||||
}
|
||||
|
||||
interface CommandsPanelProps {
|
||||
manifest: CommandManifest | null;
|
||||
results: SlashCommandResultPayload[];
|
||||
approval: SlashCommandApprovalResultPayload | null;
|
||||
pendingApproval: PendingApproval | null;
|
||||
hasConversation: boolean;
|
||||
onExecute: (input: { command: string; args?: string }) => void;
|
||||
onApprove: (input: { command: string; args?: string }) => void;
|
||||
onRunApproved: () => void;
|
||||
}
|
||||
|
||||
export function CommandsPanel({
|
||||
manifest,
|
||||
results,
|
||||
approval,
|
||||
pendingApproval,
|
||||
hasConversation,
|
||||
onExecute,
|
||||
onApprove,
|
||||
onRunApproved,
|
||||
}: CommandsPanelProps): ReactElement {
|
||||
const [command, setCommand] = useState('');
|
||||
const [args, setArgs] = useState('');
|
||||
|
||||
// Defense-in-depth: the reducer already normalizes success/approvalId
|
||||
// before storing `approval`, but a matching command string alone must
|
||||
// never be trusted here either — require the literal boolean `true` and a
|
||||
// non-empty string approvalId, not merely truthy values.
|
||||
const canRunApproved =
|
||||
approval?.success === true &&
|
||||
typeof approval.approvalId === 'string' &&
|
||||
approval.approvalId.length > 0 &&
|
||||
!!pendingApproval &&
|
||||
pendingApproval.command === approval.command;
|
||||
|
||||
// A manifest arrives from the server as untyped JSON at runtime — guard
|
||||
// both collections before mapping so a malformed manifest cannot throw.
|
||||
const commands = Array.isArray(manifest?.commands) ? manifest.commands : [];
|
||||
const skills = Array.isArray(manifest?.skills) ? manifest.skills : [];
|
||||
|
||||
return (
|
||||
<section aria-label="Commands" className="flex flex-col gap-2 border-b px-4 py-3 text-xs">
|
||||
{commands.length > 0 ? (
|
||||
<ul aria-label="Available commands" className="flex flex-col gap-1">
|
||||
{commands.map((cmd, index) => (
|
||||
<li key={asString(cmd?.name) || `cmd-${index}`}>
|
||||
<strong>/{asString(cmd?.name)}</strong> — {asString(cmd?.description)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
|
||||
{skills.length > 0 ? (
|
||||
<ul aria-label="Available skills" className="flex flex-col gap-1">
|
||||
{skills.map((skill, index) => (
|
||||
<li key={asString(skill?.name) || `skill-${index}`}>
|
||||
<strong>/skill:{asString(skill?.name)}</strong> — {asString(skill?.description)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
aria-label="Command name"
|
||||
value={command}
|
||||
onChange={(event) => setCommand(event.target.value)}
|
||||
placeholder="command"
|
||||
/>
|
||||
<input
|
||||
aria-label="Command arguments"
|
||||
value={args}
|
||||
onChange={(event) => setArgs(event.target.value)}
|
||||
placeholder="args (optional)"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!hasConversation || !command.trim()}
|
||||
onClick={() => onExecute({ command: command.trim(), args: args.trim() || undefined })}
|
||||
>
|
||||
Run command
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!hasConversation || !command.trim()}
|
||||
onClick={() => onApprove({ command: command.trim(), args: args.trim() || undefined })}
|
||||
>
|
||||
Request approval
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{approval ? (
|
||||
<div role={approval.success ? 'status' : 'alert'} className="flex items-center gap-2">
|
||||
{/* A successful approval shows stable client copy only — never
|
||||
the server-controlled approval.message or echoed
|
||||
approval.command as the primary confirmation. The frozen local
|
||||
pendingApproval below (not this line) is the sole authoritative
|
||||
statement of what will run. A denial, by contrast, is not an
|
||||
execution authority and safely surfaces the guarded structured
|
||||
reason the server gave (e.g. "Not authorized"), falling back to
|
||||
a stable copy only when absent/malformed. */}
|
||||
<span>
|
||||
{approval.success ? 'Approved.' : asNonEmptyString(approval.message, 'Denied.')}
|
||||
</span>
|
||||
{canRunApproved && pendingApproval ? (
|
||||
<>
|
||||
{/* Authoritative frozen local command+args — what the click below
|
||||
will actually emit. The server's `approval` above is display-only
|
||||
and must never be trusted to represent the executed payload. */}
|
||||
<span>
|
||||
Will run: /{pendingApproval.command}{' '}
|
||||
{pendingApproval.args ? pendingApproval.args : '(no args)'}
|
||||
</span>
|
||||
<button type="button" onClick={onRunApproved}>
|
||||
Run approved command
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{results.length > 0 ? (
|
||||
<ul aria-label="Command results" className="flex flex-col gap-1">
|
||||
{results.map((result, index) => (
|
||||
<li key={`${result.command}-${index}`} role={result.success ? 'status' : 'alert'}>
|
||||
/{asString(result.command)}: {result.success ? 'success' : 'failed'}
|
||||
{result.success
|
||||
? typeof result.message === 'string' && result.message
|
||||
? ` — ${boundMessage(result.message)}`
|
||||
: ''
|
||||
: ` — ${boundMessage(asNonEmptyString(result.message, COMMAND_FAILURE_COPY))}`}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import { useState, type KeyboardEvent, type ReactElement } from 'react';
|
||||
import type { HarnessSelection } from '@/lib/types';
|
||||
import type { HarnessSelectionValue } from './use-harness-selection';
|
||||
|
||||
interface ComposerProps {
|
||||
onSend: (input: { content: string; selection: HarnessSelection }) => boolean;
|
||||
onStop: () => void;
|
||||
streaming: boolean;
|
||||
/** True from local send time through server turn startup/ack and
|
||||
* throughout streaming — a superset of `streaming` that also covers the
|
||||
* pre-ack window where a second send could otherwise slip through. */
|
||||
sending: boolean;
|
||||
hasConversation: boolean;
|
||||
/** Structured harness/provider/model selection state. The composer never
|
||||
* accepts free-text provider/model — every sendable tuple is a validated,
|
||||
* persisted catalog entry, and the send projection is derived from it. */
|
||||
harness: HarnessSelectionValue;
|
||||
}
|
||||
|
||||
/** The distinct provider ids present in the current catalog, in first-seen
|
||||
* order — the provider select is catalog-derived, never a hardcoded list. */
|
||||
function providerOptions(harness: HarnessSelectionValue): string[] {
|
||||
const seen = new Set<string>();
|
||||
const out: string[] = [];
|
||||
for (const model of harness.catalog?.models ?? []) {
|
||||
if (seen.has(model.providerId)) continue;
|
||||
seen.add(model.providerId);
|
||||
out.push(model.providerId);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function Composer({
|
||||
onSend,
|
||||
onStop,
|
||||
streaming,
|
||||
sending,
|
||||
hasConversation,
|
||||
harness,
|
||||
}: ComposerProps): ReactElement {
|
||||
const [content, setContent] = useState('');
|
||||
const busy = streaming || sending;
|
||||
|
||||
function submit(): void {
|
||||
if (busy) return;
|
||||
// Send is gated on a validated, persisted catalog tuple — a draft or unset
|
||||
// selection can never emit, so provider/model never travel as free text.
|
||||
if (!harness.canSend || harness.persistedSelection === null) return;
|
||||
const trimmed = content.trim();
|
||||
if (!trimmed) return;
|
||||
// Pass the validated, persisted selection tuple only. The hook derives the
|
||||
// wire projection (legacy `message` provider/model, or `turn:send`) from the
|
||||
// negotiated `chat:send-capability` protocol — never from flat caller input.
|
||||
const selection = harness.persistedSelection;
|
||||
const ok = onSend({ content: trimmed, selection });
|
||||
// Clear the input only when the send was accepted — a refused turn (e.g. a
|
||||
// failed idempotency mint) must retain the user's text so it is not lost.
|
||||
if (ok) setContent('');
|
||||
}
|
||||
|
||||
function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>): void {
|
||||
if (event.key === 'Enter' && !event.shiftKey) {
|
||||
event.preventDefault();
|
||||
submit();
|
||||
}
|
||||
}
|
||||
|
||||
// Scope the model options to the intentionally selected provider. With no
|
||||
// provider chosen (`providerId === ''`) nothing matches, so the model select
|
||||
// offers only the placeholder — never a cross-provider row.
|
||||
const models = (harness.catalog?.models ?? []).filter(
|
||||
(model) => model.providerId === harness.providerId,
|
||||
);
|
||||
// A collision-safe composite option identity covering the full provider+model
|
||||
// tuple. The controlled select mirrors the same identity so the exact catalog
|
||||
// row highlights (a bare modelId would collide across providers).
|
||||
const modelOptionValue = (model: { providerId: string; modelId: string }): string =>
|
||||
`${model.providerId}:${model.modelId}`;
|
||||
const selectedModelValue = harness.modelId ? `${harness.providerId}:${harness.modelId}` : '';
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
submit();
|
||||
}}
|
||||
className="flex flex-col gap-2 border-t p-4"
|
||||
>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<select
|
||||
aria-label="Harness"
|
||||
value={harness.harnessId}
|
||||
onChange={(event) => harness.selectHarness(event.target.value)}
|
||||
className="rounded border px-2 py-1 text-xs"
|
||||
>
|
||||
<option value="">Select a harness…</option>
|
||||
{harness.harnesses.map((item) => (
|
||||
<option key={item.id} value={item.id}>
|
||||
{item.displayName}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
aria-label="Provider"
|
||||
value={harness.providerId}
|
||||
onChange={(event) => harness.selectProvider(event.target.value)}
|
||||
disabled={harness.catalogUnavailable || providerOptions(harness).length === 0}
|
||||
className="rounded border px-2 py-1 text-xs"
|
||||
>
|
||||
<option value="">Select a provider…</option>
|
||||
{providerOptions(harness).map((providerId) => (
|
||||
<option key={providerId} value={providerId}>
|
||||
{providerId}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
aria-label="Model"
|
||||
value={selectedModelValue}
|
||||
onChange={(event) => {
|
||||
// Resolve the composite option identity back to the exact catalog
|
||||
// row and persist that row's own provider+model — never a bare id.
|
||||
const selected = models.find((model) => modelOptionValue(model) === event.target.value);
|
||||
if (selected) harness.selectModel(selected.providerId, selected.modelId);
|
||||
}}
|
||||
disabled={harness.catalogUnavailable || models.length === 0}
|
||||
className="rounded border px-2 py-1 text-xs"
|
||||
>
|
||||
<option value="">Select a model…</option>
|
||||
{models.map((model) => (
|
||||
<option key={modelOptionValue(model)} value={modelOptionValue(model)}>
|
||||
{model.displayName}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
{harness.catalogUnavailable ? (
|
||||
<p role="status" className="text-xs opacity-70">
|
||||
This harness catalog is currently unavailable.
|
||||
</p>
|
||||
) : null}
|
||||
{harness.isStale ? (
|
||||
<p role="status" className="text-xs opacity-70">
|
||||
The saved model is no longer available — pick another to continue.
|
||||
</p>
|
||||
) : null}
|
||||
{harness.persistError ? (
|
||||
<p role="alert" className="text-xs">
|
||||
{harness.persistError.message}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex items-end gap-2">
|
||||
<textarea
|
||||
aria-label="Message"
|
||||
value={content}
|
||||
onChange={(event) => setContent(event.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
rows={2}
|
||||
placeholder="Message… (Enter to send, Shift+Enter for a new line)"
|
||||
className="flex-1 resize-none rounded border px-3 py-2 text-sm"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!content.trim() || busy || !harness.canSend}
|
||||
className="rounded px-3 py-2 text-sm font-medium"
|
||||
>
|
||||
Send
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Stop"
|
||||
disabled={!hasConversation || !streaming}
|
||||
onClick={onStop}
|
||||
className="rounded px-3 py-2 text-sm font-medium"
|
||||
>
|
||||
Stop
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Bounds on server-fed chat state. A hostile or malfunctioning gateway can
|
||||
* flood any of these collections; caps keep memory/render cost flat instead
|
||||
* of growing unboundedly for the lifetime of the connection.
|
||||
*/
|
||||
|
||||
/** Max characters retained for the in-flight streamed text/thinking buffers. */
|
||||
export const MAX_STREAM_CHARS = 20_000;
|
||||
/** Max transcript turns retained (oldest dropped first). */
|
||||
export const MAX_MESSAGES = 500;
|
||||
/** Max tool-call entries (including anomaly entries) retained per turn history. */
|
||||
export const MAX_TOOLS = 200;
|
||||
/** Max slash-command results retained. */
|
||||
export const MAX_COMMAND_RESULTS = 200;
|
||||
/** Max commands/skills accepted from a single manifest push. */
|
||||
export const MAX_MANIFEST_ITEMS = 500;
|
||||
/** Max executed approval IDs remembered for single-flight dedup. */
|
||||
export const MAX_EXECUTED_APPROVAL_IDS = 200;
|
||||
/** Max characters retained for a single command:result message — a hostile
|
||||
* or malfunctioning gateway must not be able to push an unbounded curated
|
||||
* success/failure reason into state (or, defensively, onto the page). */
|
||||
export const MAX_COMMAND_MESSAGE_CHARS = 1_000;
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { ReactElement } from 'react';
|
||||
import type { ChatTranscriptMessage } from './use-chat-connection';
|
||||
|
||||
interface MessageTranscriptProps {
|
||||
messages: ChatTranscriptMessage[];
|
||||
streaming: boolean;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export function MessageTranscript({
|
||||
messages,
|
||||
streaming,
|
||||
text,
|
||||
}: MessageTranscriptProps): ReactElement {
|
||||
return (
|
||||
<div
|
||||
role="log"
|
||||
aria-live="polite"
|
||||
aria-label="Conversation"
|
||||
className="flex flex-1 flex-col gap-3 overflow-y-auto p-4"
|
||||
>
|
||||
{messages.map((message) => (
|
||||
<div key={message.id} data-role={message.role} className="whitespace-pre-wrap text-sm">
|
||||
<span className="font-medium">{message.role === 'user' ? 'You' : 'Assistant'}: </span>
|
||||
<span>{message.text}</span>
|
||||
{message.thinking ? (
|
||||
<div className="pt-1 text-xs italic opacity-70">{message.thinking}</div>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
{streaming ? (
|
||||
<div data-role="assistant-streaming" className="whitespace-pre-wrap text-sm">
|
||||
<span className="font-medium">Assistant: </span>
|
||||
<span>{text || 'Thinking…'}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* Socket.IO payloads are only statically typed at the call site — a
|
||||
* misbehaving or compromised gateway can send anything at runtime. These
|
||||
* guards protect the dereference sites that would otherwise throw (`.map` on
|
||||
* a non-array, `.toFixed` on a non-number) or render an object as a React
|
||||
* child.
|
||||
*/
|
||||
import type {
|
||||
HarnessAuthState,
|
||||
HarnessCatalog,
|
||||
HarnessCatalogEntry,
|
||||
HarnessModelAvailability,
|
||||
HarnessSelection,
|
||||
HarnessSummary,
|
||||
} from '@/lib/types';
|
||||
|
||||
export function asString(value: unknown, fallback = ''): string {
|
||||
return typeof value === 'string' ? value : fallback;
|
||||
}
|
||||
|
||||
/** Like `asString`, but an empty string also falls back — used for guarded
|
||||
* contract-provided reason strings (e.g. a denial or failure message) where
|
||||
* an empty string is not a meaningful value to display in place of the
|
||||
* stable fallback copy. */
|
||||
export function asNonEmptyString(value: unknown, fallback: string): string {
|
||||
return typeof value === 'string' && value.length > 0 ? value : fallback;
|
||||
}
|
||||
|
||||
export function asFiniteNumber(value: unknown, fallback = 0): number {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : fallback;
|
||||
}
|
||||
|
||||
/** Like `asFiniteNumber`, but returns `null` on failure instead of a numeric
|
||||
* fallback — callers that must not fabricate a plausible-looking value (e.g.
|
||||
* `0 tokens` / `$0.0000` for genuinely unknown usage) use this to render an
|
||||
* honest "unavailable" label instead. */
|
||||
export function asFiniteNumberOrNull(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
export function asStringArray(value: unknown): string[] {
|
||||
return Array.isArray(value) && value.every((item) => typeof item === 'string') ? value : [];
|
||||
}
|
||||
|
||||
export function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The HTTP harness/catalog/selection JSON bodies are as untrusted as the socket
|
||||
* payloads above — a misbehaving or compromised gateway can send anything. The
|
||||
* guards below normalize those bodies into the typed client shapes without ever
|
||||
* rendering a raw body, so a 404/422/malformed response can never inject an
|
||||
* object into React or a non-tuple into the selection state.
|
||||
*/
|
||||
|
||||
/** Normalizes an untrusted `authState` to the closed set, defaulting to the
|
||||
* safest value (`unavailable`) for anything unrecognized. */
|
||||
export function asHarnessAuthState(value: unknown): HarnessAuthState {
|
||||
return value === 'ready' || value === 'auth_required' || value === 'unavailable'
|
||||
? value
|
||||
: 'unavailable';
|
||||
}
|
||||
|
||||
/** Normalizes an untrusted `availability` to the closed set, defaulting to
|
||||
* `unavailable` so a malformed row can never present as sendable. */
|
||||
export function asHarnessAvailability(value: unknown): HarnessModelAvailability {
|
||||
return value === 'available' ? 'available' : 'unavailable';
|
||||
}
|
||||
|
||||
/** A tuple is valid only when all three ids are non-empty strings — a partial
|
||||
* or malformed selection is rejected (null) rather than half-adopted. */
|
||||
export function asHarnessSelection(value: unknown): HarnessSelection | null {
|
||||
if (!isRecord(value)) return null;
|
||||
const harnessId = value.harnessId;
|
||||
const providerId = value.providerId;
|
||||
const modelId = value.modelId;
|
||||
if (
|
||||
typeof harnessId !== 'string' ||
|
||||
typeof providerId !== 'string' ||
|
||||
typeof modelId !== 'string' ||
|
||||
harnessId.length === 0 ||
|
||||
providerId.length === 0 ||
|
||||
modelId.length === 0
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return { harnessId, providerId, modelId };
|
||||
}
|
||||
|
||||
/** Normalizes an untrusted array into typed harness summaries, dropping any row
|
||||
* without a usable id. */
|
||||
export function asHarnessSummaries(value: unknown): HarnessSummary[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const out: HarnessSummary[] = [];
|
||||
for (const item of value) {
|
||||
if (!isRecord(item)) continue;
|
||||
const id = asString(item.id);
|
||||
if (id.length === 0) continue;
|
||||
out.push({
|
||||
id,
|
||||
displayName: asNonEmptyString(item.displayName, id),
|
||||
capabilities: asStringArray(item.capabilities),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function asHarnessCatalogEntry(value: unknown): HarnessCatalogEntry | null {
|
||||
const selection = asHarnessSelection(value);
|
||||
if (selection === null || !isRecord(value)) return null;
|
||||
return {
|
||||
...selection,
|
||||
displayName: asNonEmptyString(value.displayName, selection.modelId),
|
||||
reasoningCapability: value.reasoningCapability === true,
|
||||
inputTypes: asStringArray(value.inputTypes),
|
||||
authState: asHarnessAuthState(value.authState),
|
||||
availability: asHarnessAvailability(value.availability),
|
||||
};
|
||||
}
|
||||
|
||||
/** Normalizes an untrusted catalog body into the typed client catalog. The
|
||||
* caller supplies `harnessId` (from the request path) so the returned catalog
|
||||
* is scoped to the harness that was actually requested, never a body-echoed id.
|
||||
* Malformed model rows are dropped rather than invalidating the whole catalog. */
|
||||
export function asHarnessCatalog(value: unknown, harnessId: string): HarnessCatalog {
|
||||
const record = isRecord(value) ? value : {};
|
||||
const rawModels = Array.isArray(record.models) ? record.models : [];
|
||||
const models: HarnessCatalogEntry[] = [];
|
||||
for (const row of rawModels) {
|
||||
const entry = asHarnessCatalogEntry(row);
|
||||
if (entry !== null) models.push(entry);
|
||||
}
|
||||
return {
|
||||
harnessId,
|
||||
version: asString(record.version),
|
||||
fingerprint: asString(record.fingerprint),
|
||||
models,
|
||||
};
|
||||
}
|
||||
|
||||
/** The single point of truth for what counts as a valid conversation ID
|
||||
* anywhere a scoped server event may adopt one into state — a non-empty
|
||||
* string, nothing else. Every site that establishes or compares
|
||||
* `state.conversationId` against a raw socket payload must route through
|
||||
* this guard so a malformed first frame (null/object/number/empty string)
|
||||
* can never be adopted verbatim. */
|
||||
export function asConversationId(value: unknown): string | null {
|
||||
return typeof value === 'string' && value.length > 0 ? value : null;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { ReactElement } from 'react';
|
||||
import type { SessionInfoPayload } from '@/lib/chat-contract';
|
||||
import { MAX_MANIFEST_ITEMS } from './limits';
|
||||
import { asString, asStringArray } from './runtime-guards';
|
||||
|
||||
interface SessionPanelProps {
|
||||
sessionInfo: SessionInfoPayload | null;
|
||||
onSetThinking: (level: string) => void;
|
||||
}
|
||||
|
||||
const THINKING_LEVEL_UNAVAILABLE = '';
|
||||
|
||||
export function SessionPanel({
|
||||
sessionInfo,
|
||||
onSetThinking,
|
||||
}: SessionPanelProps): ReactElement | null {
|
||||
if (!sessionInfo) return null;
|
||||
|
||||
// The reducer already caps this before storing it, but the render site
|
||||
// defends independently — a hostile payload must never be able to force
|
||||
// this <select> to lay out an unbounded number of options.
|
||||
const availableThinkingLevels = asStringArray(sessionInfo.availableThinkingLevels).slice(
|
||||
0,
|
||||
MAX_MANIFEST_ITEMS,
|
||||
);
|
||||
const hasThinkingLevels = availableThinkingLevels.length > 0;
|
||||
|
||||
return (
|
||||
<section
|
||||
aria-label="Session info"
|
||||
className="flex flex-wrap items-center gap-3 border-b px-4 py-2 text-xs"
|
||||
>
|
||||
<span>{asString(sessionInfo.provider, 'unknown')}</span>
|
||||
<span>{asString(sessionInfo.modelId, 'unknown')}</span>
|
||||
<label className="flex items-center gap-2">
|
||||
<span>Thinking level</span>
|
||||
<select
|
||||
aria-label="Thinking level"
|
||||
value={
|
||||
hasThinkingLevels ? asString(sessionInfo.thinkingLevel) : THINKING_LEVEL_UNAVAILABLE
|
||||
}
|
||||
onChange={(event) => {
|
||||
// The placeholder option is not a real, settable level — a
|
||||
// malformed availableThinkingLevels list must never let the
|
||||
// client emit set:thinking for it.
|
||||
if (!hasThinkingLevels) return;
|
||||
onSetThinking(event.target.value);
|
||||
}}
|
||||
>
|
||||
{hasThinkingLevels ? (
|
||||
availableThinkingLevels.map((level) => (
|
||||
<option key={level} value={level}>
|
||||
{level}
|
||||
</option>
|
||||
))
|
||||
) : (
|
||||
<option value={THINKING_LEVEL_UNAVAILABLE}>Thinking level unavailable</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
{sessionInfo.routingDecision ? (
|
||||
<span title={asString(sessionInfo.routingDecision.ruleName)}>
|
||||
{asString(sessionInfo.routingDecision.reason)}
|
||||
</span>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { vi } from 'vitest';
|
||||
import type { ClientToServerEvents, ServerToClientEvents } from '@/lib/chat-contract';
|
||||
|
||||
type ServerEvent = keyof ServerToClientEvents;
|
||||
type ClientEvent = keyof ClientToServerEvents;
|
||||
type ServerHandler<K extends ServerEvent> = ServerToClientEvents[K];
|
||||
type ClientPayload<K extends ClientEvent> = Parameters<ClientToServerEvents[K]>[0];
|
||||
|
||||
export interface EmittedEvent<K extends ClientEvent = ClientEvent> {
|
||||
event: K;
|
||||
payload: ClientPayload<K>;
|
||||
}
|
||||
|
||||
/** The subset of a Socket.IO `ChatSocket` that `useChatConnection` drives. */
|
||||
export interface FakeChatSocket {
|
||||
connected: boolean;
|
||||
/** Mirrors socket.io-client's `Socket.id`: the connection identity the server
|
||||
* echoes in a `chat:send-capability` payload. The generation-bound send
|
||||
* protocol accepts an advertisement only when `payload.connectionId === id`. */
|
||||
id: string;
|
||||
connect(): FakeChatSocket;
|
||||
on<K extends ServerEvent>(event: K, handler: ServerHandler<K>): FakeChatSocket;
|
||||
off<K extends ServerEvent>(event: K, handler: ServerHandler<K>): FakeChatSocket;
|
||||
emit<K extends ClientEvent>(event: K, payload: ClientPayload<K>): FakeChatSocket;
|
||||
}
|
||||
|
||||
/**
|
||||
* A typed in-memory stand-in for `getSocket()`. Unlike a bare
|
||||
* `(event: string, payload: unknown) => void` mock, every public method here is
|
||||
* checked against the real `/chat` contract — a typo'd event name or a payload
|
||||
* missing a required field fails to compile instead of silently no-op'ing at
|
||||
* runtime.
|
||||
*/
|
||||
/** Socket.IO's built-in connection-state events. Not part of the app-level
|
||||
* ServerToClientEvents contract, but real sockets always support them and
|
||||
* `useChatConnection` registers a `disconnect` handler on the real socket. */
|
||||
type LifecycleEvent = 'connect' | 'disconnect';
|
||||
|
||||
export function createFakeChatSocket(): {
|
||||
socket: FakeChatSocket;
|
||||
listeners: Map<ServerEvent, Set<(payload: never) => void>>;
|
||||
emitted: EmittedEvent[];
|
||||
serverEmit<K extends ServerEvent>(
|
||||
event: K,
|
||||
payload: Parameters<ServerToClientEvents[K]>[0],
|
||||
): void;
|
||||
/** Escape hatch for malformed-payload tests: bypasses the compile-time
|
||||
* payload contract to simulate a genuinely untrusted runtime value from the
|
||||
* server, e.g. a `session:info` with a non-array `availableThinkingLevels`. */
|
||||
serverEmitRaw(event: ServerEvent, payload: unknown): void;
|
||||
/** Simulates a transient Socket.IO `disconnect` — fires any handler(s)
|
||||
* registered via `socket.on('disconnect', ...)` without clearing any
|
||||
* listeners, mirroring how a real reconnecting socket behaves. */
|
||||
simulateDisconnect(): void;
|
||||
/** Simulates socket.io-client's automatic reconnect of the *same*
|
||||
* instance after a transient disconnect: marks the socket connected again
|
||||
* and fires any handler(s) registered via `socket.on('connect', ...)`,
|
||||
* without clearing or replacing any listeners. A real reconnect is assigned
|
||||
* a fresh `Socket.id`; pass `nextId` to model that new connection identity
|
||||
* (defaults to the current id so existing callers are unaffected). */
|
||||
simulateReconnect(nextId?: string): void;
|
||||
} {
|
||||
const listeners = new Map<ServerEvent, Set<(payload: never) => void>>();
|
||||
const emitted: EmittedEvent[] = [];
|
||||
|
||||
// Internal storage is intentionally keyed loosely (the per-event handler shape
|
||||
// varies by K, which a single Map can't express); the generic signatures on the
|
||||
// exported `socket`/`serverEmit` above and below are what keep test call sites
|
||||
// type-checked against ServerToClientEvents/ClientToServerEvents.
|
||||
const socket = {
|
||||
connected: false,
|
||||
id: 'socket-a',
|
||||
connect: vi.fn(function connect(this: void) {
|
||||
socket.connected = true;
|
||||
return socket;
|
||||
}),
|
||||
on: vi.fn(function on(this: void, event: ServerEvent, handler: (payload: never) => void) {
|
||||
if (!listeners.has(event)) listeners.set(event, new Set());
|
||||
listeners.get(event)?.add(handler);
|
||||
return socket;
|
||||
}),
|
||||
off: vi.fn(function off(this: void, event: ServerEvent, handler: (payload: never) => void) {
|
||||
listeners.get(event)?.delete(handler);
|
||||
return socket;
|
||||
}),
|
||||
emit: vi.fn(function emit(this: void, event: ClientEvent, payload: unknown) {
|
||||
emitted.push({ event, payload } as EmittedEvent);
|
||||
return socket;
|
||||
}),
|
||||
} as unknown as FakeChatSocket;
|
||||
|
||||
function serverEmit<K extends ServerEvent>(
|
||||
event: K,
|
||||
payload: Parameters<ServerToClientEvents[K]>[0],
|
||||
): void {
|
||||
for (const handler of listeners.get(event) ?? []) {
|
||||
(handler as (payload: Parameters<ServerToClientEvents[K]>[0]) => void)(payload);
|
||||
}
|
||||
}
|
||||
|
||||
function serverEmitRaw(event: ServerEvent, payload: unknown): void {
|
||||
for (const handler of listeners.get(event) ?? []) {
|
||||
(handler as (payload: unknown) => void)(payload);
|
||||
}
|
||||
}
|
||||
|
||||
function simulateDisconnect(): void {
|
||||
socket.connected = false;
|
||||
const lifecycleKey = 'disconnect' satisfies LifecycleEvent as unknown as ServerEvent;
|
||||
for (const handler of listeners.get(lifecycleKey) ?? []) {
|
||||
(handler as () => void)();
|
||||
}
|
||||
}
|
||||
|
||||
function simulateReconnect(nextId: string = socket.id): void {
|
||||
socket.connected = true;
|
||||
socket.id = nextId;
|
||||
const lifecycleKey = 'connect' satisfies LifecycleEvent as unknown as ServerEvent;
|
||||
for (const handler of listeners.get(lifecycleKey) ?? []) {
|
||||
(handler as () => void)();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
socket,
|
||||
listeners,
|
||||
emitted,
|
||||
serverEmit,
|
||||
serverEmitRaw,
|
||||
simulateDisconnect,
|
||||
simulateReconnect,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { ToolCallList } from './tool-call-list';
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
});
|
||||
|
||||
let root: Root | null;
|
||||
let container: HTMLElement | null;
|
||||
|
||||
async function render(node: Parameters<Root['render']>[0]): Promise<void> {
|
||||
container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
await act(async () => {
|
||||
root?.render(node);
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
document.body.replaceChildren();
|
||||
root = null;
|
||||
container = null;
|
||||
});
|
||||
|
||||
describe('ToolCallList', () => {
|
||||
it('renders two entries independently, without a duplicate-key warning, when a valid toolCallId is shared', async () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
|
||||
await render(
|
||||
<ToolCallList
|
||||
tools={[
|
||||
{ toolCallId: 'dup', toolName: 'search', status: 'success' },
|
||||
{ toolCallId: 'dup', toolName: 'search', status: 'running' },
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
const items = [...(container?.querySelectorAll('li') ?? [])];
|
||||
expect(items).toHaveLength(2);
|
||||
expect(items[0]?.textContent).toContain('success');
|
||||
expect(items[1]?.textContent).toContain('running');
|
||||
|
||||
const duplicateKeyWarning = consoleError.mock.calls.some((args) =>
|
||||
args.some((arg) => typeof arg === 'string' && arg.includes('same key')),
|
||||
);
|
||||
expect(duplicateKeyWarning).toBe(false);
|
||||
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { ReactElement } from 'react';
|
||||
import type { ToolCallState } from './use-chat-connection';
|
||||
|
||||
export function ToolCallList({ tools }: { tools: ToolCallState[] }): ReactElement | null {
|
||||
if (tools.length === 0) return null;
|
||||
|
||||
return (
|
||||
<ul aria-label="Tool calls" className="flex flex-col gap-1 px-4 pb-2 text-xs">
|
||||
{tools.map((tool, index) => (
|
||||
<li
|
||||
// A valid server-controlled toolCallId can legitimately repeat
|
||||
// (e.g. two tool:start events sharing one id) — keying on it alone
|
||||
// would give React two identical keys. Pairing it with its
|
||||
// (stable, append-only) render index keeps every key unique.
|
||||
key={`${tool.toolCallId}-${index}`}
|
||||
role={tool.status === 'error' || tool.status === 'anomaly' ? 'alert' : 'status'}
|
||||
>
|
||||
{tool.toolName} —{' '}
|
||||
{tool.status === 'anomaly' ? 'unexpected end (unknown tool call)' : tool.status}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,450 @@
|
||||
import { act, type ReactElement } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { useHarnessSelection, type HarnessSelectionValue } from './use-harness-selection';
|
||||
|
||||
function json(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
interface Scenario {
|
||||
harnesses?: unknown;
|
||||
catalog?: { body: unknown; status?: number };
|
||||
selection?: unknown;
|
||||
/** When set, the PUT resolves only when this is called (for race tests). */
|
||||
deferPut?: boolean;
|
||||
}
|
||||
|
||||
interface Deferred<T> {
|
||||
promise: Promise<T>;
|
||||
resolve: (value: T) => void;
|
||||
}
|
||||
|
||||
function defer<T>(): Deferred<T> {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((r) => {
|
||||
resolve = r;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
let putBodies: unknown[] = [];
|
||||
let putDeferred: Deferred<Response> | null = null;
|
||||
|
||||
function installFetch(scenario: Scenario): ReturnType<typeof vi.fn> {
|
||||
putBodies = [];
|
||||
putDeferred = scenario.deferPut ? defer<Response>() : null;
|
||||
const fetchMock = vi.fn(async (input: unknown, init?: RequestInit) => {
|
||||
const url = String(input);
|
||||
const method = String(init?.method ?? 'GET').toUpperCase();
|
||||
if (url === '/api/harnesses') return json(scenario.harnesses ?? []);
|
||||
if (url.startsWith('/api/harnesses/') && url.endsWith('/catalog')) {
|
||||
const spec = scenario.catalog ?? {
|
||||
body: { harnessId: 'pi', version: '1', fingerprint: 'f', models: [] },
|
||||
};
|
||||
return json(spec.body, spec.status ?? 200);
|
||||
}
|
||||
if (url === '/api/chat/preferences/selection' && method === 'GET') {
|
||||
return json({ selection: scenario.selection ?? null });
|
||||
}
|
||||
if (url === '/api/chat/preferences/selection' && method === 'PUT') {
|
||||
putBodies.push(JSON.parse(String(init?.body)));
|
||||
const ok = json({ selection: JSON.parse(String(init?.body)) });
|
||||
if (putDeferred) return putDeferred.promise;
|
||||
return ok;
|
||||
}
|
||||
return new Response('not found', { status: 404 });
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
return fetchMock;
|
||||
}
|
||||
|
||||
let latest: HarnessSelectionValue | null = null;
|
||||
|
||||
function Probe(): ReactElement | null {
|
||||
latest = useHarnessSelection();
|
||||
return null;
|
||||
}
|
||||
|
||||
let root: Root | null;
|
||||
let container: HTMLElement;
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
latest = null;
|
||||
container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
document.body.replaceChildren();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
async function mount(): Promise<void> {
|
||||
await act(async () => {
|
||||
root?.render(<Probe />);
|
||||
});
|
||||
await flush();
|
||||
}
|
||||
|
||||
async function flush(times = 5): Promise<void> {
|
||||
for (let i = 0; i < times; i += 1) {
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function value(): HarnessSelectionValue {
|
||||
if (!latest) throw new Error('hook value not captured');
|
||||
return latest;
|
||||
}
|
||||
|
||||
const PI_CATALOG = {
|
||||
harnessId: 'pi',
|
||||
version: '2026-08-11',
|
||||
fingerprint: 'fp',
|
||||
models: [
|
||||
{
|
||||
harnessId: 'pi',
|
||||
providerId: 'openai',
|
||||
modelId: 'gpt-5',
|
||||
displayName: 'GPT-5',
|
||||
reasoningCapability: true,
|
||||
inputTypes: ['text'],
|
||||
authState: 'ready',
|
||||
availability: 'available',
|
||||
},
|
||||
{
|
||||
harnessId: 'pi',
|
||||
providerId: 'anthropic',
|
||||
modelId: 'claude',
|
||||
displayName: 'Claude',
|
||||
reasoningCapability: true,
|
||||
inputTypes: ['text'],
|
||||
authState: 'ready',
|
||||
availability: 'available',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe('useHarnessSelection', () => {
|
||||
it('loads harnesses and, once a harness is chosen, the model options come only from its catalog', async () => {
|
||||
installFetch({
|
||||
harnesses: [{ id: 'pi', displayName: 'Pi', capabilities: [] }],
|
||||
catalog: { body: PI_CATALOG },
|
||||
selection: null,
|
||||
});
|
||||
await mount();
|
||||
|
||||
expect(value().harnesses).toEqual([{ id: 'pi', displayName: 'Pi', capabilities: [] }]);
|
||||
expect(value().catalog).toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
value().selectHarness('pi');
|
||||
});
|
||||
await flush();
|
||||
|
||||
expect(value().catalog?.harnessId).toBe('pi');
|
||||
expect(value().catalog?.models.map((m) => m.modelId)).toEqual(['gpt-5', 'claude']);
|
||||
});
|
||||
|
||||
it('does not auto-select any catalog row when there is no persisted selection (no first-row fallback)', async () => {
|
||||
const fetchMock = installFetch({
|
||||
harnesses: [{ id: 'pi', displayName: 'Pi', capabilities: [] }],
|
||||
catalog: { body: PI_CATALOG },
|
||||
selection: null,
|
||||
});
|
||||
await mount();
|
||||
await act(async () => {
|
||||
value().selectHarness('pi');
|
||||
});
|
||||
await flush();
|
||||
|
||||
expect(value().modelId).toBe('');
|
||||
expect(value().persistedSelection).toBeNull();
|
||||
expect(value().canSend).toBe(false);
|
||||
// Nothing was persisted — no PUT fired for an unset selection.
|
||||
const putCalls = fetchMock.mock.calls.filter(
|
||||
(c) => String((c[1] as RequestInit)?.method).toUpperCase() === 'PUT',
|
||||
);
|
||||
expect(putCalls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('persists the structured tuple and only enables send AFTER the PUT resolves (no race ahead of persistence)', async () => {
|
||||
installFetch({
|
||||
harnesses: [{ id: 'pi', displayName: 'Pi', capabilities: [] }],
|
||||
catalog: { body: PI_CATALOG },
|
||||
selection: null,
|
||||
deferPut: true,
|
||||
});
|
||||
await mount();
|
||||
await act(async () => {
|
||||
value().selectHarness('pi');
|
||||
});
|
||||
await flush();
|
||||
await act(async () => {
|
||||
value().selectProvider('openai');
|
||||
});
|
||||
await act(async () => {
|
||||
value().selectModel('openai', 'gpt-5');
|
||||
});
|
||||
await flush();
|
||||
|
||||
// PUT is in flight (deferred) — send MUST NOT be enabled yet.
|
||||
expect(value().canSend).toBe(false);
|
||||
|
||||
await act(async () => {
|
||||
putDeferred?.resolve(
|
||||
json({ selection: { harnessId: 'pi', providerId: 'openai', modelId: 'gpt-5' } }),
|
||||
);
|
||||
});
|
||||
await flush();
|
||||
|
||||
expect(putBodies).toContainEqual({ harnessId: 'pi', providerId: 'openai', modelId: 'gpt-5' });
|
||||
expect(value().persistedSelection).toEqual({
|
||||
harnessId: 'pi',
|
||||
providerId: 'openai',
|
||||
modelId: 'gpt-5',
|
||||
});
|
||||
expect(value().canSend).toBe(true);
|
||||
// Task Five: the composer sends the nested `persistedSelection` tuple directly.
|
||||
// The Task-Four compat flat `projection` ({provider, modelId}) is removed — the
|
||||
// harnessId must never be dropped on the way to the wire.
|
||||
expect('projection' in value()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps a stale/unavailable persisted selection visibly displayed rather than silently dropping it', async () => {
|
||||
installFetch({
|
||||
harnesses: [{ id: 'pi', displayName: 'Pi', capabilities: [] }],
|
||||
catalog: { body: PI_CATALOG },
|
||||
selection: { harnessId: 'pi', providerId: 'openai', modelId: 'retired-model' },
|
||||
});
|
||||
await mount();
|
||||
|
||||
// The persisted tuple is displayed even though its model is gone from the catalog.
|
||||
expect(value().persistedSelection).toEqual({
|
||||
harnessId: 'pi',
|
||||
providerId: 'openai',
|
||||
modelId: 'retired-model',
|
||||
});
|
||||
expect(value().modelId).toBe('retired-model');
|
||||
expect(value().isStale).toBe(true);
|
||||
// A stale model is not a valid catalog option, so send stays disabled.
|
||||
expect(value().canSend).toBe(false);
|
||||
});
|
||||
|
||||
it('disables send for an empty catalog (no viable model) and never fabricates one', async () => {
|
||||
installFetch({
|
||||
harnesses: [{ id: 'pi', displayName: 'Pi', capabilities: [] }],
|
||||
catalog: { body: { harnessId: 'pi', version: '1', fingerprint: 'f', models: [] } },
|
||||
selection: null,
|
||||
});
|
||||
await mount();
|
||||
await act(async () => {
|
||||
value().selectHarness('pi');
|
||||
});
|
||||
await flush();
|
||||
|
||||
expect(value().catalog?.models ?? []).toHaveLength(0);
|
||||
expect(value().canSend).toBe(false);
|
||||
});
|
||||
|
||||
it('marks the catalog unavailable and disables send when the catalog request 404s', async () => {
|
||||
installFetch({
|
||||
harnesses: [{ id: 'pi', displayName: 'Pi', capabilities: [] }],
|
||||
catalog: {
|
||||
body: { code: 'adapter_unavailable', message: 'x', harnessId: 'pi' },
|
||||
status: 404,
|
||||
},
|
||||
selection: null,
|
||||
});
|
||||
await mount();
|
||||
await act(async () => {
|
||||
value().selectHarness('pi');
|
||||
});
|
||||
await flush();
|
||||
|
||||
expect(value().catalogUnavailable).toBe(true);
|
||||
expect(value().canSend).toBe(false);
|
||||
});
|
||||
|
||||
it('on a 422 persist, keeps the requested tuple visible, surfaces a typed error, and leaves send disabled', async () => {
|
||||
installFetch({
|
||||
harnesses: [{ id: 'pi', displayName: 'Pi', capabilities: [] }],
|
||||
catalog: {
|
||||
body: {
|
||||
...PI_CATALOG,
|
||||
models: [{ ...PI_CATALOG.models[0], availability: 'unavailable' }],
|
||||
},
|
||||
},
|
||||
selection: null,
|
||||
});
|
||||
// Override PUT to 422.
|
||||
const fetchMock = vi.fn(async (input: unknown, init?: RequestInit) => {
|
||||
const url = String(input);
|
||||
const method = String(init?.method ?? 'GET').toUpperCase();
|
||||
if (url === '/api/harnesses')
|
||||
return json([{ id: 'pi', displayName: 'Pi', capabilities: [] }]);
|
||||
if (url.endsWith('/catalog')) return json(PI_CATALOG);
|
||||
if (url === '/api/chat/preferences/selection' && method === 'GET')
|
||||
return json({ selection: null });
|
||||
if (url === '/api/chat/preferences/selection' && method === 'PUT') {
|
||||
return json(
|
||||
{
|
||||
code: 'model_unavailable',
|
||||
message: 'nope',
|
||||
selection: { harnessId: 'a', providerId: 'b', modelId: 'c' },
|
||||
},
|
||||
422,
|
||||
);
|
||||
}
|
||||
return new Response('nf', { status: 404 });
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await mount();
|
||||
await act(async () => {
|
||||
value().selectHarness('pi');
|
||||
});
|
||||
await flush();
|
||||
await act(async () => {
|
||||
value().selectProvider('openai');
|
||||
});
|
||||
await act(async () => {
|
||||
value().selectModel('openai', 'gpt-5');
|
||||
});
|
||||
await flush();
|
||||
|
||||
expect(value().modelId).toBe('gpt-5');
|
||||
expect(value().persistError?.code).toBe('model_unavailable');
|
||||
expect(value().persistError?.requested).toEqual({
|
||||
harnessId: 'pi',
|
||||
providerId: 'openai',
|
||||
modelId: 'gpt-5',
|
||||
});
|
||||
expect(value().persistedSelection).toBeNull();
|
||||
expect(value().canSend).toBe(false);
|
||||
});
|
||||
|
||||
it('invalidates the model on a provider change and keeps send disabled until the new tuple persists', async () => {
|
||||
installFetch({
|
||||
harnesses: [{ id: 'pi', displayName: 'Pi', capabilities: [] }],
|
||||
catalog: { body: PI_CATALOG },
|
||||
selection: null,
|
||||
});
|
||||
await mount();
|
||||
await act(async () => {
|
||||
value().selectHarness('pi');
|
||||
});
|
||||
await flush();
|
||||
await act(async () => {
|
||||
value().selectProvider('openai');
|
||||
});
|
||||
await act(async () => {
|
||||
value().selectModel('openai', 'gpt-5');
|
||||
});
|
||||
await flush();
|
||||
// A valid provider-A tuple has persisted.
|
||||
expect(value().canSend).toBe(true);
|
||||
expect(value().persistedSelection).toEqual({
|
||||
harnessId: 'pi',
|
||||
providerId: 'openai',
|
||||
modelId: 'gpt-5',
|
||||
});
|
||||
|
||||
// Switching provider clears the model that no longer belongs to it.
|
||||
await act(async () => {
|
||||
value().selectProvider('anthropic');
|
||||
});
|
||||
expect(value().modelId).toBe('');
|
||||
expect(value().canSend).toBe(false);
|
||||
|
||||
// Send stays disabled until the new exact provider-B tuple persists.
|
||||
await act(async () => {
|
||||
value().selectModel('anthropic', 'claude');
|
||||
});
|
||||
await flush();
|
||||
expect(value().canSend).toBe(true);
|
||||
expect(value().persistedSelection).toEqual({
|
||||
harnessId: 'pi',
|
||||
providerId: 'anthropic',
|
||||
modelId: 'claude',
|
||||
});
|
||||
// Task Five: no compat flat projection — the nested persistedSelection is the wire tuple.
|
||||
expect('projection' in value()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not enable send on a model pick until the PUT for that exact new tuple resolves', async () => {
|
||||
installFetch({
|
||||
harnesses: [{ id: 'pi', displayName: 'Pi', capabilities: [] }],
|
||||
catalog: { body: PI_CATALOG },
|
||||
selection: { harnessId: 'pi', providerId: 'openai', modelId: 'gpt-5' },
|
||||
deferPut: true,
|
||||
});
|
||||
await mount();
|
||||
// The persisted, in-catalog tuple is sendable after mount (no PUT needed).
|
||||
expect(value().canSend).toBe(true);
|
||||
|
||||
await act(async () => {
|
||||
value().selectProvider('anthropic');
|
||||
});
|
||||
expect(value().modelId).toBe('');
|
||||
expect(value().canSend).toBe(false);
|
||||
|
||||
await act(async () => {
|
||||
value().selectModel('anthropic', 'claude');
|
||||
});
|
||||
await flush();
|
||||
// PUT for the new tuple is still in flight — send MUST stay disabled.
|
||||
expect(value().canSend).toBe(false);
|
||||
|
||||
await act(async () => {
|
||||
putDeferred?.resolve(
|
||||
json({ selection: { harnessId: 'pi', providerId: 'anthropic', modelId: 'claude' } }),
|
||||
);
|
||||
});
|
||||
await flush();
|
||||
expect(value().canSend).toBe(true);
|
||||
// Task Five: no compat flat projection — the nested persistedSelection is the wire tuple.
|
||||
expect('projection' in value()).toBe(false);
|
||||
});
|
||||
|
||||
it('never requests any /api/providers* endpoint across the whole flow', async () => {
|
||||
const fetchMock = installFetch({
|
||||
harnesses: [{ id: 'pi', displayName: 'Pi', capabilities: [] }],
|
||||
catalog: { body: PI_CATALOG },
|
||||
selection: { harnessId: 'pi', providerId: 'openai', modelId: 'gpt-5' },
|
||||
});
|
||||
await mount();
|
||||
await act(async () => {
|
||||
value().selectProvider('anthropic');
|
||||
});
|
||||
await act(async () => {
|
||||
value().selectModel('anthropic', 'claude');
|
||||
});
|
||||
await flush();
|
||||
|
||||
for (const call of fetchMock.mock.calls) {
|
||||
expect(String(call[0])).not.toContain('/api/providers');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
fetchCatalog,
|
||||
fetchHarnesses,
|
||||
fetchPersistedSelection,
|
||||
persistSelection,
|
||||
type SelectionErrorCode,
|
||||
} from './chat-api';
|
||||
import type { HarnessCatalog, HarnessSelection, HarnessSummary } from '@/lib/types';
|
||||
|
||||
export interface HarnessPersistError {
|
||||
code: SelectionErrorCode;
|
||||
message: string;
|
||||
/** The exact tuple the user requested — preserved so the failed selection
|
||||
* stays visible rather than being silently dropped. */
|
||||
requested: HarnessSelection;
|
||||
}
|
||||
|
||||
export interface HarnessSelectionValue {
|
||||
harnesses: HarnessSummary[];
|
||||
catalog: HarnessCatalog | null;
|
||||
/** True when the selected harness has no usable catalog (404/error). */
|
||||
catalogUnavailable: boolean;
|
||||
/** The working (displayed) selection, kept as three distinct ids. Empty
|
||||
* strings mean "not chosen yet" — there is deliberately no first-row default. */
|
||||
harnessId: string;
|
||||
providerId: string;
|
||||
modelId: string;
|
||||
/** The last tuple confirmed persisted by the server, or null. */
|
||||
persistedSelection: HarnessSelection | null;
|
||||
/** True when a persisted selection references a model no longer present as an
|
||||
* available catalog entry — it stays visibly displayed rather than dropped. */
|
||||
isStale: boolean;
|
||||
/** True ONLY once a full tuple has been confirmed persisted AND it is a
|
||||
* currently-available catalog entry. Send stays disabled otherwise, so a send
|
||||
* can never race ahead of successful persistence. */
|
||||
canSend: boolean;
|
||||
persistError: HarnessPersistError | null;
|
||||
selectHarness: (harnessId: string) => void;
|
||||
selectProvider: (providerId: string) => void;
|
||||
/** Persist the EXACT catalog row's `{providerId, modelId}` — the caller
|
||||
* resolves the composite option identity to the real entry and passes both
|
||||
* ids, so a bare model id is never combined with ambient provider state. */
|
||||
selectModel: (providerId: string, modelId: string) => void;
|
||||
}
|
||||
|
||||
/** A tuple is a currently-usable catalog option only when the catalog holds a
|
||||
* matching, available entry — the single gate that keeps a stale/unavailable
|
||||
* model from ever counting as sendable. */
|
||||
function isAvailableInCatalog(
|
||||
selection: HarnessSelection | null,
|
||||
catalog: HarnessCatalog | null,
|
||||
): boolean {
|
||||
if (selection === null || catalog === null) return false;
|
||||
return catalog.models.some(
|
||||
(model) =>
|
||||
model.providerId === selection.providerId &&
|
||||
model.modelId === selection.modelId &&
|
||||
model.availability === 'available',
|
||||
);
|
||||
}
|
||||
|
||||
function tuplesEqual(a: HarnessSelection | null, b: HarnessSelection | null): boolean {
|
||||
if (a === null || b === null) return a === b;
|
||||
return a.harnessId === b.harnessId && a.providerId === b.providerId && a.modelId === b.modelId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the harness/catalog/selection state for the chat composer: loads the
|
||||
* harness list and any persisted tuple on mount, loads a harness's catalog when
|
||||
* chosen, and PUT-persists the full `{harnessId, providerId, modelId}` tuple
|
||||
* when a model is picked. It never auto-selects a catalog row, keeps a
|
||||
* stale/unavailable persisted tuple visible, and only reports `canSend` true
|
||||
* once a full tuple has actually persisted as an available catalog entry.
|
||||
*/
|
||||
export function useHarnessSelection(): HarnessSelectionValue {
|
||||
const [harnesses, setHarnesses] = useState<HarnessSummary[]>([]);
|
||||
const [catalog, setCatalog] = useState<HarnessCatalog | null>(null);
|
||||
const [catalogUnavailable, setCatalogUnavailable] = useState(false);
|
||||
const [harnessId, setHarnessId] = useState('');
|
||||
const [providerId, setProviderId] = useState('');
|
||||
const [modelId, setModelId] = useState('');
|
||||
const [persistedSelection, setPersistedSelection] = useState<HarnessSelection | null>(null);
|
||||
const [persistError, setPersistError] = useState<HarnessPersistError | null>(null);
|
||||
|
||||
// Monotonic request ids so a slow in-flight catalog/persist response can never
|
||||
// overwrite the result of a newer request the user has since triggered.
|
||||
const catalogRequestRef = useRef(0);
|
||||
const persistRequestRef = useRef(0);
|
||||
|
||||
const loadCatalog = useCallback(async (id: string): Promise<void> => {
|
||||
const requestId = catalogRequestRef.current + 1;
|
||||
catalogRequestRef.current = requestId;
|
||||
setCatalog(null);
|
||||
setCatalogUnavailable(false);
|
||||
const result = await fetchCatalog(id);
|
||||
if (catalogRequestRef.current !== requestId) return;
|
||||
if (result.ok) {
|
||||
setCatalog(result.catalog);
|
||||
setCatalogUnavailable(false);
|
||||
} else {
|
||||
setCatalog(null);
|
||||
setCatalogUnavailable(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
void (async (): Promise<void> => {
|
||||
const [list, persisted] = await Promise.all([fetchHarnesses(), fetchPersistedSelection()]);
|
||||
if (!active) return;
|
||||
setHarnesses(list);
|
||||
if (persisted !== null) {
|
||||
// Adopt the persisted tuple as the displayed selection and load its
|
||||
// catalog. If the model has since been retired, it still shows (stale).
|
||||
setHarnessId(persisted.harnessId);
|
||||
setProviderId(persisted.providerId);
|
||||
setModelId(persisted.modelId);
|
||||
setPersistedSelection(persisted);
|
||||
await loadCatalog(persisted.harnessId);
|
||||
}
|
||||
// No persisted selection → nothing is auto-selected; the user must choose.
|
||||
})();
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [loadCatalog]);
|
||||
|
||||
const selectHarness = useCallback(
|
||||
(id: string): void => {
|
||||
setHarnessId(id);
|
||||
// Changing harness invalidates the provider/model draft — never carry a
|
||||
// model across harnesses.
|
||||
setProviderId('');
|
||||
setModelId('');
|
||||
setPersistError(null);
|
||||
void loadCatalog(id);
|
||||
},
|
||||
[loadCatalog],
|
||||
);
|
||||
|
||||
const selectProvider = useCallback((id: string): void => {
|
||||
setProviderId(id);
|
||||
// A new provider invalidates the chosen model — no cross-provider carryover.
|
||||
setModelId('');
|
||||
setPersistError(null);
|
||||
}, []);
|
||||
|
||||
const selectModel = useCallback(
|
||||
(selectedProviderId: string, selectedModelId: string): void => {
|
||||
// Bind the model to the EXACT catalog row's provider — never to ambient
|
||||
// provider state — so two providers exposing the same modelId can never
|
||||
// collide or mis-resolve. Keep the displayed provider consistent with the
|
||||
// resolved row.
|
||||
setProviderId(selectedProviderId);
|
||||
setModelId(selectedModelId);
|
||||
setPersistError(null);
|
||||
const requested: HarnessSelection = {
|
||||
harnessId,
|
||||
providerId: selectedProviderId,
|
||||
modelId: selectedModelId,
|
||||
};
|
||||
const requestId = persistRequestRef.current + 1;
|
||||
persistRequestRef.current = requestId;
|
||||
void (async (): Promise<void> => {
|
||||
const result = await persistSelection(requested);
|
||||
if (persistRequestRef.current !== requestId) return;
|
||||
if (result.ok) {
|
||||
setPersistedSelection(result.selection);
|
||||
setPersistError(null);
|
||||
} else {
|
||||
// Leave persistedSelection unchanged (send stays disabled) and surface
|
||||
// the typed error carrying the exact requested tuple.
|
||||
setPersistError({
|
||||
code: result.code,
|
||||
message: result.message,
|
||||
requested: result.requested,
|
||||
});
|
||||
}
|
||||
})();
|
||||
},
|
||||
[harnessId],
|
||||
);
|
||||
|
||||
const draft: HarnessSelection = { harnessId, providerId, modelId };
|
||||
const isStale = persistedSelection !== null && !isAvailableInCatalog(persistedSelection, catalog);
|
||||
const canSend =
|
||||
persistedSelection !== null &&
|
||||
!catalogUnavailable &&
|
||||
tuplesEqual(draft, persistedSelection) &&
|
||||
isAvailableInCatalog(persistedSelection, catalog);
|
||||
|
||||
return {
|
||||
harnesses,
|
||||
catalog,
|
||||
catalogUnavailable,
|
||||
harnessId,
|
||||
providerId,
|
||||
modelId,
|
||||
persistedSelection,
|
||||
isStale,
|
||||
canSend,
|
||||
persistError,
|
||||
selectHarness,
|
||||
selectProvider,
|
||||
selectModel,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { createMemoryRouter, RouterProvider, type RouteObject } from 'react-router-dom';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { useSessionMock } = vi.hoisted(() => ({
|
||||
useSessionMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/auth-client', () => ({
|
||||
useSession: useSessionMock,
|
||||
}));
|
||||
|
||||
import { AuthGuard, GuestGuard } from './guards';
|
||||
|
||||
interface RenderedRouter {
|
||||
container: HTMLDivElement;
|
||||
router: ReturnType<typeof createMemoryRouter>;
|
||||
}
|
||||
|
||||
const mountedRoots: Root[] = [];
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
});
|
||||
|
||||
async function renderRouter(
|
||||
routeObjects: RouteObject[],
|
||||
initialEntry: string,
|
||||
): Promise<RenderedRouter> {
|
||||
const container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
const router = createMemoryRouter(routeObjects, { initialEntries: [initialEntry] });
|
||||
const root = createRoot(container);
|
||||
mountedRoots.push(root);
|
||||
|
||||
await act(async () => {
|
||||
root.render(<RouterProvider router={router} />);
|
||||
});
|
||||
|
||||
return { container, router };
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
for (const root of mountedRoots.splice(0)) {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
}
|
||||
document.body.replaceChildren();
|
||||
useSessionMock.mockReset();
|
||||
});
|
||||
|
||||
const guestRoutes: RouteObject[] = [
|
||||
{
|
||||
path: '/login',
|
||||
element: <GuestGuard />,
|
||||
children: [{ index: true, element: <p>Guest page</p> }],
|
||||
},
|
||||
{ path: '/chat', element: <p>Chat page</p> },
|
||||
];
|
||||
|
||||
const authenticatedRoutes: RouteObject[] = [
|
||||
{
|
||||
path: '/chat',
|
||||
element: <AuthGuard />,
|
||||
children: [{ index: true, element: <p>Private page</p> }],
|
||||
},
|
||||
{ path: '/login', element: <p>Login page</p> },
|
||||
];
|
||||
|
||||
describe('GuestGuard', () => {
|
||||
it('renders the guest outlet while session lookup is pending', async () => {
|
||||
useSessionMock.mockReturnValue({ data: null, isPending: true });
|
||||
|
||||
const view = await renderRouter(guestRoutes, '/login');
|
||||
|
||||
expect(view.container.textContent).toContain('Guest page');
|
||||
expect(view.router.state.location.pathname).toBe('/login');
|
||||
});
|
||||
|
||||
it('renders the guest outlet when no session exists', async () => {
|
||||
useSessionMock.mockReturnValue({ data: null, isPending: false });
|
||||
|
||||
const view = await renderRouter(guestRoutes, '/login');
|
||||
|
||||
expect(view.container.textContent).toContain('Guest page');
|
||||
expect(view.router.state.location.pathname).toBe('/login');
|
||||
});
|
||||
|
||||
it('redirects an authenticated session to chat', async () => {
|
||||
useSessionMock.mockReturnValue({ data: { user: { id: 'user-1' } }, isPending: false });
|
||||
|
||||
const view = await renderRouter(guestRoutes, '/login');
|
||||
|
||||
expect(view.container.textContent).toContain('Chat page');
|
||||
expect(view.router.state.location.pathname).toBe('/chat');
|
||||
});
|
||||
});
|
||||
|
||||
describe('AuthGuard', () => {
|
||||
it('renders the existing loading treatment while session lookup is pending', async () => {
|
||||
useSessionMock.mockReturnValue({ data: null, isPending: true });
|
||||
|
||||
const view = await renderRouter(authenticatedRoutes, '/chat');
|
||||
|
||||
expect(view.container.textContent).toContain('Loading...');
|
||||
expect(view.router.state.location.pathname).toBe('/chat');
|
||||
});
|
||||
|
||||
it('redirects an unauthenticated visitor to login', async () => {
|
||||
useSessionMock.mockReturnValue({ data: null, isPending: false });
|
||||
|
||||
const view = await renderRouter(authenticatedRoutes, '/chat');
|
||||
|
||||
expect(view.container.textContent).toContain('Login page');
|
||||
expect(view.router.state.location.pathname).toBe('/login');
|
||||
});
|
||||
|
||||
it('renders the authenticated outlet when a session exists', async () => {
|
||||
useSessionMock.mockReturnValue({ data: { user: { id: 'user-1' } }, isPending: false });
|
||||
|
||||
const view = await renderRouter(authenticatedRoutes, '/chat');
|
||||
|
||||
expect(view.container.textContent).toContain('Private page');
|
||||
expect(view.router.state.location.pathname).toBe('/chat');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { ReactElement } from 'react';
|
||||
import { Navigate, Outlet } from 'react-router-dom';
|
||||
import { useSession } from '@/lib/auth-client';
|
||||
|
||||
export function GuestGuard(): ReactElement {
|
||||
const { data: session } = useSession();
|
||||
|
||||
return session ? <Navigate to="/chat" replace /> : <Outlet />;
|
||||
}
|
||||
|
||||
export function AuthGuard(): ReactElement {
|
||||
const { data: session, isPending } = useSession();
|
||||
|
||||
if (isPending) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="text-sm text-text-muted">Loading...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return session ? <Outlet /> : <Navigate to="/login" replace />;
|
||||
}
|
||||
|
||||
export function AdminGuard(): ReactElement {
|
||||
const { data: session, isPending } = useSession();
|
||||
|
||||
if (isPending) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="text-sm text-text-muted">Loading...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
return <Navigate to="/login" replace />;
|
||||
}
|
||||
|
||||
const user = session.user as typeof session.user & { role?: string };
|
||||
|
||||
return user.role === 'admin' ? <Outlet /> : <Navigate to="/" replace />;
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { createMemoryRouter, RouterProvider, type RouteObject } from 'react-router-dom';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { apiMock, useSessionMock } = vi.hoisted(() => ({
|
||||
apiMock: vi.fn(),
|
||||
useSessionMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
api: apiMock,
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/auth-client', () => ({
|
||||
useSession: useSessionMock,
|
||||
authClient: {},
|
||||
}));
|
||||
|
||||
import { AdminPage } from './admin';
|
||||
import { AdminGuard } from '@/spa/guards';
|
||||
|
||||
const userFixtures = {
|
||||
users: [
|
||||
{
|
||||
id: 'u-admin',
|
||||
name: 'Ada Admin',
|
||||
email: '[email protected]',
|
||||
role: 'admin',
|
||||
banned: false,
|
||||
banReason: null,
|
||||
createdAt: '2026-08-01T00:00:00.000Z',
|
||||
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 'u-member',
|
||||
name: 'Mel Member',
|
||||
email: '[email protected]',
|
||||
role: 'member',
|
||||
banned: true,
|
||||
banReason: 'spam',
|
||||
createdAt: '2026-08-02T00:00:00.000Z',
|
||||
updatedAt: '2026-08-02T00:00:00.000Z',
|
||||
},
|
||||
],
|
||||
total: 2,
|
||||
};
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
document.body.replaceChildren();
|
||||
root = null;
|
||||
apiMock.mockReset();
|
||||
useSessionMock.mockReset();
|
||||
});
|
||||
|
||||
async function renderAdminRoute(): Promise<void> {
|
||||
const routes: RouteObject[] = [
|
||||
{
|
||||
element: <AdminGuard />,
|
||||
children: [{ path: '/admin', element: <AdminPage /> }],
|
||||
},
|
||||
{ path: '/', element: <div>home page</div> },
|
||||
{ path: '/login', element: <div>login page</div> },
|
||||
];
|
||||
const router = createMemoryRouter(routes, { initialEntries: ['/admin'] });
|
||||
container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root?.render(<RouterProvider router={router} />);
|
||||
});
|
||||
}
|
||||
|
||||
function sessionWithRole(role: string | undefined): { data: unknown; isPending: boolean } {
|
||||
return {
|
||||
data: { user: { id: 'u-1', name: 'Test', email: '[email protected]', role } },
|
||||
isPending: false,
|
||||
};
|
||||
}
|
||||
|
||||
describe('AdminGuard', () => {
|
||||
it('redirects unauthenticated visitors to /login', async () => {
|
||||
useSessionMock.mockReturnValue({ data: null, isPending: false });
|
||||
|
||||
await renderAdminRoute();
|
||||
|
||||
expect(container.textContent).toContain('login page');
|
||||
expect(apiMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects non-admin users to /', async () => {
|
||||
useSessionMock.mockReturnValue(sessionWithRole('member'));
|
||||
|
||||
await renderAdminRoute();
|
||||
|
||||
expect(container.textContent).toContain('home page');
|
||||
expect(apiMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('renders the admin page for admin users', async () => {
|
||||
useSessionMock.mockReturnValue(sessionWithRole('admin'));
|
||||
apiMock.mockResolvedValueOnce(userFixtures);
|
||||
|
||||
await renderAdminRoute();
|
||||
|
||||
expect(container.textContent).toContain('Admin Panel');
|
||||
});
|
||||
});
|
||||
|
||||
describe('AdminPage users tab', () => {
|
||||
it('lists users with role and ban status after load', async () => {
|
||||
useSessionMock.mockReturnValue(sessionWithRole('admin'));
|
||||
apiMock.mockResolvedValueOnce(userFixtures);
|
||||
|
||||
await renderAdminRoute();
|
||||
|
||||
expect(apiMock).toHaveBeenCalledWith('/api/admin/users');
|
||||
expect(container.textContent).toContain('Ada Admin');
|
||||
expect(container.textContent).toContain('Mel Member');
|
||||
expect(container.textContent).toContain('Banned');
|
||||
expect(container.textContent).toContain('2 user(s)');
|
||||
});
|
||||
|
||||
it('shows the load error with a retry control', async () => {
|
||||
useSessionMock.mockReturnValue(sessionWithRole('admin'));
|
||||
apiMock.mockRejectedValueOnce(new Error('gateway unavailable'));
|
||||
|
||||
await renderAdminRoute();
|
||||
|
||||
expect(container.textContent).toContain('gateway unavailable');
|
||||
|
||||
apiMock.mockResolvedValueOnce(userFixtures);
|
||||
const retry = [...container.querySelectorAll('button')].find((b) =>
|
||||
b.textContent?.includes('Retry'),
|
||||
);
|
||||
expect(retry).toBeTruthy();
|
||||
await act(async () => {
|
||||
retry?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain('Ada Admin');
|
||||
});
|
||||
|
||||
it('posts to the ban endpoint and reloads on Ban', async () => {
|
||||
useSessionMock.mockReturnValue(sessionWithRole('admin'));
|
||||
apiMock.mockResolvedValue(userFixtures);
|
||||
|
||||
await renderAdminRoute();
|
||||
|
||||
const banButton = [...container.querySelectorAll('button')].find(
|
||||
(b) => b.textContent === 'Ban',
|
||||
);
|
||||
expect(banButton).toBeTruthy();
|
||||
await act(async () => {
|
||||
banButton?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(apiMock).toHaveBeenCalledWith('/api/admin/users/u-admin/ban', { method: 'POST' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('AdminPage health tab', () => {
|
||||
it('loads health status when the tab is opened', async () => {
|
||||
useSessionMock.mockReturnValue(sessionWithRole('admin'));
|
||||
apiMock.mockResolvedValueOnce(userFixtures).mockResolvedValueOnce({
|
||||
status: 'ok',
|
||||
database: { status: 'ok', latencyMs: 3 },
|
||||
cache: { status: 'ok', latencyMs: 1 },
|
||||
agentPool: { activeSessions: 2 },
|
||||
providers: [{ id: 'ollama', name: 'Ollama', available: true, modelCount: 4 }],
|
||||
checkedAt: '2026-08-26T00:00:00.000Z',
|
||||
});
|
||||
|
||||
await renderAdminRoute();
|
||||
|
||||
const healthTab = [...container.querySelectorAll('button')].find((b) =>
|
||||
b.textContent?.includes('System Health'),
|
||||
);
|
||||
await act(async () => {
|
||||
healthTab?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(apiMock).toHaveBeenCalledWith('/api/admin/health');
|
||||
expect(container.textContent).toContain('Database (PostgreSQL)');
|
||||
expect(container.textContent).toContain('Active sessions: 2');
|
||||
expect(container.textContent).toContain('4 models');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,522 @@
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { api } from '@/lib/api';
|
||||
import { cn } from '@/lib/cn';
|
||||
|
||||
// ── Types ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface UserDto {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: string;
|
||||
banned: boolean;
|
||||
banReason: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
interface UserListDto {
|
||||
users: UserDto[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
interface ServiceStatusDto {
|
||||
status: 'ok' | 'error';
|
||||
latencyMs?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface ProviderStatusDto {
|
||||
id: string;
|
||||
name: string;
|
||||
available: boolean;
|
||||
modelCount: number;
|
||||
}
|
||||
|
||||
interface HealthStatusDto {
|
||||
status: 'ok' | 'degraded' | 'error';
|
||||
database: ServiceStatusDto;
|
||||
cache: ServiceStatusDto;
|
||||
agentPool: { activeSessions: number };
|
||||
providers: ProviderStatusDto[];
|
||||
checkedAt: string;
|
||||
}
|
||||
|
||||
// ── Admin Page ─────────────────────────────────────────────────────────────────
|
||||
|
||||
// Route-level access control lives in AdminGuard (spa/guards.tsx); this page
|
||||
// assumes an authenticated admin session.
|
||||
export function AdminPage(): React.ReactElement {
|
||||
const [activeTab, setActiveTab] = useState<'users' | 'health'>('users');
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-5xl space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-semibold text-text-primary">Admin Panel</h1>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1 border-b border-surface-border">
|
||||
{(['users', 'health'] as const).map((tab) => (
|
||||
<button
|
||||
key={tab}
|
||||
type="button"
|
||||
onClick={() => setActiveTab(tab)}
|
||||
className={cn(
|
||||
'px-4 py-2 text-sm font-medium capitalize transition-colors',
|
||||
activeTab === tab
|
||||
? 'border-b-2 border-blue-500 text-blue-400'
|
||||
: 'text-text-secondary hover:text-text-primary',
|
||||
)}
|
||||
>
|
||||
{tab === 'users' ? 'User Management' : 'System Health'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{activeTab === 'users' ? <UsersTab /> : <HealthTab />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Users Tab ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function UsersTab(): React.ReactElement {
|
||||
const [users, setUsers] = useState<UserDto[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
|
||||
const loadUsers = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await api<UserListDto>('/api/admin/users');
|
||||
setUsers(data.users);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load users');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void loadUsers();
|
||||
}, [loadUsers]);
|
||||
|
||||
async function handleRoleToggle(user: UserDto): Promise<void> {
|
||||
const newRole = user.role === 'admin' ? 'member' : 'admin';
|
||||
try {
|
||||
await api(`/api/admin/users/${user.id}/role`, {
|
||||
method: 'PATCH',
|
||||
body: { role: newRole },
|
||||
});
|
||||
await loadUsers();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : 'Failed to update role');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleBanToggle(user: UserDto): Promise<void> {
|
||||
const endpoint = user.banned ? 'unban' : 'ban';
|
||||
try {
|
||||
await api(`/api/admin/users/${user.id}/${endpoint}`, { method: 'POST' });
|
||||
await loadUsers();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : 'Failed to update ban status');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(user: UserDto): Promise<void> {
|
||||
if (!confirm(`Delete user ${user.email}? This cannot be undone.`)) return;
|
||||
try {
|
||||
await api(`/api/admin/users/${user.id}`, { method: 'DELETE' });
|
||||
await loadUsers();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : 'Failed to delete user');
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return <p className="text-sm text-text-muted">Loading users...</p>;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="rounded-lg border border-red-500/30 bg-red-500/10 p-4">
|
||||
<p className="text-sm text-red-400">{error}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void loadUsers()}
|
||||
className="mt-2 text-xs text-red-300 underline hover:no-underline"
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm text-text-muted">{users.length} user(s)</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowCreate(true)}
|
||||
className="rounded-md bg-blue-600 px-3 py-1.5 text-sm text-white transition-colors hover:bg-blue-700"
|
||||
>
|
||||
+ New User
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showCreate && (
|
||||
<CreateUserForm
|
||||
onCancel={() => setShowCreate(false)}
|
||||
onCreated={() => {
|
||||
setShowCreate(false);
|
||||
void loadUsers();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{users.length === 0 ? (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-6 text-center">
|
||||
<p className="text-sm text-text-muted">No users found</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-hidden rounded-lg border border-surface-border">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr className="border-b border-surface-border bg-surface-elevated text-left text-xs text-text-muted">
|
||||
<th className="px-4 py-2 font-medium">Name / Email</th>
|
||||
<th className="px-4 py-2 font-medium">Role</th>
|
||||
<th className="hidden px-4 py-2 font-medium md:table-cell">Status</th>
|
||||
<th className="hidden px-4 py-2 font-medium md:table-cell">Created</th>
|
||||
<th className="px-4 py-2 font-medium">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((user) => (
|
||||
<tr key={user.id} className="border-b border-surface-border last:border-b-0">
|
||||
<td className="px-4 py-3">
|
||||
<div className="text-sm font-medium text-text-primary">{user.name}</div>
|
||||
<div className="text-xs text-text-muted">{user.email}</div>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<span
|
||||
className={cn(
|
||||
'inline-flex rounded-full px-2 py-0.5 text-xs font-medium',
|
||||
user.role === 'admin'
|
||||
? 'bg-purple-500/20 text-purple-400'
|
||||
: 'bg-surface-elevated text-text-secondary',
|
||||
)}
|
||||
>
|
||||
{user.role}
|
||||
</span>
|
||||
</td>
|
||||
<td className="hidden px-4 py-3 md:table-cell">
|
||||
{user.banned ? (
|
||||
<span className="inline-flex rounded-full bg-red-500/20 px-2 py-0.5 text-xs font-medium text-red-400">
|
||||
Banned
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex rounded-full bg-green-500/20 px-2 py-0.5 text-xs font-medium text-green-400">
|
||||
Active
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="hidden px-4 py-3 text-xs text-text-muted md:table-cell">
|
||||
{new Date(user.createdAt).toLocaleDateString()}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleRoleToggle(user)}
|
||||
className="text-xs text-blue-400 hover:text-blue-300"
|
||||
title={user.role === 'admin' ? 'Demote to member' : 'Promote to admin'}
|
||||
>
|
||||
{user.role === 'admin' ? 'Demote' : 'Promote'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleBanToggle(user)}
|
||||
className={cn(
|
||||
'text-xs',
|
||||
user.banned
|
||||
? 'text-green-400 hover:text-green-300'
|
||||
: 'text-yellow-400 hover:text-yellow-300',
|
||||
)}
|
||||
>
|
||||
{user.banned ? 'Unban' : 'Ban'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleDelete(user)}
|
||||
className="text-xs text-red-400 hover:text-red-300"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Create User Form ──────────────────────────────────────────────────────────
|
||||
|
||||
interface CreateUserFormProps {
|
||||
onCancel: () => void;
|
||||
onCreated: () => void;
|
||||
}
|
||||
|
||||
function CreateUserForm({ onCancel, onCreated }: CreateUserFormProps): React.ReactElement {
|
||||
const [name, setName] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [role, setRole] = useState('member');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent): Promise<void> {
|
||||
e.preventDefault();
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api('/api/admin/users', {
|
||||
method: 'POST',
|
||||
body: { name, email, password, role },
|
||||
});
|
||||
onCreated();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to create user');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-4">
|
||||
<h3 className="mb-3 text-sm font-medium text-text-primary">Create New User</h3>
|
||||
<form onSubmit={(e) => void handleSubmit(e)} className="space-y-3">
|
||||
{error && <p className="text-xs text-red-400">{error}</p>}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="mb-1 block text-xs text-text-muted">Name</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className="w-full rounded-md border border-surface-border bg-surface-elevated px-3 py-1.5 text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs text-text-muted">Email</label>
|
||||
<input
|
||||
type="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="w-full rounded-md border border-surface-border bg-surface-elevated px-3 py-1.5 text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs text-text-muted">Password</label>
|
||||
<input
|
||||
type="password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="w-full rounded-md border border-surface-border bg-surface-elevated px-3 py-1.5 text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs text-text-muted">Role</label>
|
||||
<select
|
||||
value={role}
|
||||
onChange={(e) => setRole(e.target.value)}
|
||||
className="w-full rounded-md border border-surface-border bg-surface-elevated px-3 py-1.5 text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
>
|
||||
<option value="member">member</option>
|
||||
<option value="admin">admin</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancel}
|
||||
className="rounded-md px-3 py-1.5 text-sm text-text-muted hover:text-text-primary"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submitting}
|
||||
className="rounded-md bg-blue-600 px-3 py-1.5 text-sm text-white hover:bg-blue-700 disabled:opacity-50"
|
||||
>
|
||||
{submitting ? 'Creating...' : 'Create'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Health Tab ────────────────────────────────────────────────────────────────
|
||||
|
||||
function HealthTab(): React.ReactElement {
|
||||
const [health, setHealth] = useState<HealthStatusDto | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const loadHealth = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await api<HealthStatusDto>('/api/admin/health');
|
||||
setHealth(data);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load health');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void loadHealth();
|
||||
}, [loadHealth]);
|
||||
|
||||
if (loading) {
|
||||
return <p className="text-sm text-text-muted">Loading health status...</p>;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="rounded-lg border border-red-500/30 bg-red-500/10 p-4">
|
||||
<p className="text-sm text-red-400">{error}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void loadHealth()}
|
||||
className="mt-2 text-xs text-red-300 underline hover:no-underline"
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!health) return <></>;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<StatusBadge status={health.status} />
|
||||
<span className="text-sm text-text-muted">
|
||||
Last checked: {new Date(health.checkedAt).toLocaleTimeString()}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void loadHealth()}
|
||||
className="text-xs text-blue-400 hover:text-blue-300"
|
||||
>
|
||||
Refresh
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
{/* Database */}
|
||||
<HealthCard title="Database (PostgreSQL)" status={health.database.status}>
|
||||
{health.database.latencyMs !== undefined && (
|
||||
<p className="text-xs text-text-muted">Latency: {health.database.latencyMs}ms</p>
|
||||
)}
|
||||
{health.database.error && <p className="text-xs text-red-400">{health.database.error}</p>}
|
||||
</HealthCard>
|
||||
|
||||
{/* Cache */}
|
||||
<HealthCard title="Cache (Valkey)" status={health.cache.status}>
|
||||
{health.cache.latencyMs !== undefined && (
|
||||
<p className="text-xs text-text-muted">Latency: {health.cache.latencyMs}ms</p>
|
||||
)}
|
||||
{health.cache.error && <p className="text-xs text-red-400">{health.cache.error}</p>}
|
||||
</HealthCard>
|
||||
|
||||
{/* Agent Pool */}
|
||||
<HealthCard title="Agent Pool" status="ok">
|
||||
<p className="text-xs text-text-muted">
|
||||
Active sessions: {health.agentPool.activeSessions}
|
||||
</p>
|
||||
</HealthCard>
|
||||
|
||||
{/* Providers */}
|
||||
<HealthCard
|
||||
title="LLM Providers"
|
||||
status={health.providers.some((p) => p.available) ? 'ok' : 'error'}
|
||||
>
|
||||
{health.providers.length === 0 ? (
|
||||
<p className="text-xs text-text-muted">No providers configured</p>
|
||||
) : (
|
||||
<ul className="space-y-1">
|
||||
{health.providers.map((p) => (
|
||||
<li key={p.id} className="flex items-center justify-between text-xs">
|
||||
<span className="text-text-secondary">{p.name}</span>
|
||||
<span
|
||||
className={cn(
|
||||
'rounded-full px-1.5 py-0.5',
|
||||
p.available ? 'bg-green-500/20 text-green-400' : 'bg-red-500/20 text-red-400',
|
||||
)}
|
||||
>
|
||||
{p.available ? `${p.modelCount} models` : 'unavailable'}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</HealthCard>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Helper Components ─────────────────────────────────────────────────────────
|
||||
|
||||
function StatusBadge({ status }: { status: 'ok' | 'degraded' | 'error' }): React.ReactElement {
|
||||
const map = {
|
||||
ok: 'bg-green-500/20 text-green-400',
|
||||
degraded: 'bg-yellow-500/20 text-yellow-400',
|
||||
error: 'bg-red-500/20 text-red-400',
|
||||
};
|
||||
return (
|
||||
<span className={cn('rounded-full px-2 py-0.5 text-xs font-medium capitalize', map[status])}>
|
||||
{status}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
interface HealthCardProps {
|
||||
title: string;
|
||||
status: 'ok' | 'error';
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
function HealthCard({ title, status, children }: HealthCardProps): React.ReactElement {
|
||||
return (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-4">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<h3 className="text-sm font-medium text-text-primary">{title}</h3>
|
||||
<span
|
||||
className={cn('h-2 w-2 rounded-full', status === 'ok' ? 'bg-green-400' : 'bg-red-400')}
|
||||
/>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { createMemoryRouter, RouterProvider, type RouteObject } from 'react-router-dom';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { useSessionMock } = vi.hoisted(() => ({
|
||||
useSessionMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/auth-client', () => ({
|
||||
useSession: useSessionMock,
|
||||
}));
|
||||
|
||||
import { ThemeProvider } from '@/providers/theme-provider';
|
||||
import { routes } from '@/routes';
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
});
|
||||
|
||||
function Boom(): never {
|
||||
throw new Error('render blew up');
|
||||
}
|
||||
|
||||
/** Recursively clones the real exported route table, replacing only the
|
||||
* `/chat` route's `element` with `<Boom />` — every other route (including
|
||||
* the real `AuthGuard` nesting and the real `/chat` `errorElement`) is left
|
||||
* exactly as exported. This is what makes the test fail if a future change
|
||||
* removes the real route's `errorElement`, unlike a hand-built independent
|
||||
* route tree that could drift from production undetected. */
|
||||
function replaceChatElementWithBoom(nodes: RouteObject[]): RouteObject[] {
|
||||
return nodes.map((node) => {
|
||||
const cloned: RouteObject = { ...node };
|
||||
if (cloned.path === '/chat') {
|
||||
cloned.element = <Boom />;
|
||||
}
|
||||
if (cloned.children) {
|
||||
cloned.children = replaceChatElementWithBoom(cloned.children);
|
||||
}
|
||||
return cloned;
|
||||
});
|
||||
}
|
||||
|
||||
let root: Root | null;
|
||||
let container: HTMLElement;
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
document.body.replaceChildren();
|
||||
root = null;
|
||||
useSessionMock.mockReset();
|
||||
});
|
||||
|
||||
describe('ChatRouteErrorBoundary', () => {
|
||||
it('renders a recoverable, non-blank fallback when the /chat route element throws during render', async () => {
|
||||
useSessionMock.mockReturnValue({ data: { user: { id: 'user-1' } }, isPending: false });
|
||||
|
||||
const routeObjects = replaceChatElementWithBoom(routes);
|
||||
const router = createMemoryRouter(routeObjects, { initialEntries: ['/chat'] });
|
||||
|
||||
container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
|
||||
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
try {
|
||||
await act(async () => {
|
||||
root?.render(
|
||||
<ThemeProvider>
|
||||
<RouterProvider router={router} />
|
||||
</ThemeProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalled();
|
||||
} finally {
|
||||
consoleErrorSpy.mockRestore();
|
||||
}
|
||||
|
||||
expect(container.textContent).not.toBe('');
|
||||
expect(container.querySelector('[role="alert"]')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { ReactElement } from 'react';
|
||||
import { useRouteError } from 'react-router-dom';
|
||||
|
||||
/**
|
||||
* `/chat` renders live, server-driven state (streamed text, tool calls,
|
||||
* manifests) that can carry malformed payloads no compile-time contract can
|
||||
* fully rule out at every dereference site. This is the last line of
|
||||
* defense: if something still throws during render, show a recoverable
|
||||
* alert instead of leaving the user on a blank/white screen.
|
||||
*/
|
||||
export function ChatRouteErrorBoundary(): ReactElement {
|
||||
useRouteError();
|
||||
|
||||
return (
|
||||
<div role="alert" className="flex min-h-screen flex-col items-center justify-center gap-3 p-8">
|
||||
<p className="text-sm font-medium">Something went wrong loading chat.</p>
|
||||
<a href="/chat" className="text-sm underline">
|
||||
Reload chat
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,95 @@
|
||||
import type { ReactElement } from 'react';
|
||||
import { CommandsPanel } from '@/spa/chat/commands-panel';
|
||||
import { Composer } from '@/spa/chat/composer';
|
||||
import { MessageTranscript } from '@/spa/chat/message-transcript';
|
||||
import { asFiniteNumberOrNull, asString } from '@/spa/chat/runtime-guards';
|
||||
import { SessionPanel } from '@/spa/chat/session-panel';
|
||||
import { ToolCallList } from '@/spa/chat/tool-call-list';
|
||||
import { useChatConnection } from '@/spa/chat/use-chat-connection';
|
||||
import { useHarnessSelection } from '@/spa/chat/use-harness-selection';
|
||||
|
||||
/** Renders a real value normally, but an honest "unavailable" label instead
|
||||
* of a fabricated `0` for a missing/malformed count — a real `0 tokens` and
|
||||
* an unknown token count must never look the same. */
|
||||
function formatTokens(value: unknown): string {
|
||||
const tokens = asFiniteNumberOrNull(value);
|
||||
return tokens === null ? 'tokens unavailable' : `${tokens} tokens`;
|
||||
}
|
||||
|
||||
/** Same honesty guarantee as `formatTokens`, for cost. */
|
||||
function formatCost(value: unknown): string {
|
||||
const cost = asFiniteNumberOrNull(value);
|
||||
return cost === null ? 'cost unavailable' : `$${cost.toFixed(4)}`;
|
||||
}
|
||||
|
||||
export function ChatPage(): ReactElement {
|
||||
const { state, actions } = useChatConnection();
|
||||
const harness = useHarnessSelection();
|
||||
const hasConversation = state.conversationId !== null;
|
||||
|
||||
return (
|
||||
<div className="flex h-[calc(100vh-3.5rem)] min-h-0 flex-col overflow-hidden md:h-screen">
|
||||
<header className="border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Chat</h1>
|
||||
</header>
|
||||
|
||||
{state.systemReload ? (
|
||||
<div role="status" className="border-b px-4 py-2 text-sm">
|
||||
{asString(state.systemReload.message)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{state.error ? (
|
||||
<div role="alert" className="border-b px-4 py-2 text-sm">
|
||||
{asString(state.error)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{state.ack ? (
|
||||
<div role="status" className="border-b px-4 py-1 text-xs opacity-70">
|
||||
Message accepted · conversation {asString(state.ack.conversationId, 'unknown')} · id{' '}
|
||||
{asString(state.ack.messageId, 'unknown')}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<SessionPanel sessionInfo={state.sessionInfo} onSetThinking={actions.setThinking} />
|
||||
|
||||
<MessageTranscript messages={state.messages} streaming={state.streaming} text={state.text} />
|
||||
|
||||
{state.thinking ? (
|
||||
<section aria-label="Thinking" className="px-4 pb-2 text-xs italic opacity-80">
|
||||
{state.thinking}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<ToolCallList tools={state.tools} />
|
||||
|
||||
{state.usage ? (
|
||||
<div aria-label="Usage" className="px-4 pb-2 text-xs opacity-80">
|
||||
{formatTokens(state.usage.tokens?.total)} · {formatCost(state.usage.cost)} ·{' '}
|
||||
{asString(state.usage.provider, 'unknown')}/{asString(state.usage.modelId, 'unknown')}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<CommandsPanel
|
||||
manifest={state.manifest}
|
||||
results={state.commandResults}
|
||||
approval={state.approval}
|
||||
pendingApproval={state.pendingApproval}
|
||||
hasConversation={hasConversation}
|
||||
onExecute={actions.executeCommand}
|
||||
onApprove={actions.approveCommand}
|
||||
onRunApproved={actions.runApprovedCommand}
|
||||
/>
|
||||
|
||||
<Composer
|
||||
onSend={actions.sendMessage}
|
||||
onStop={actions.abort}
|
||||
streaming={state.streaming}
|
||||
sending={state.sending}
|
||||
hasConversation={hasConversation}
|
||||
harness={harness}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { useEffect, useState, type FormEvent, type ReactElement } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { SsoProviderButtons } from '@/components/auth/sso-provider-buttons';
|
||||
import { api } from '@/lib/api';
|
||||
import { authClient, signIn } from '@/lib/auth-client';
|
||||
import type { SsoProviderDiscovery } from '@/lib/sso';
|
||||
|
||||
export function LoginPage(): ReactElement {
|
||||
const navigate = useNavigate();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [ssoProviders, setSsoProviders] = useState<SsoProviderDiscovery[]>([]);
|
||||
const [ssoLoadingProviderId, setSsoLoadingProviderId] = useState<
|
||||
SsoProviderDiscovery['id'] | null
|
||||
>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
|
||||
void api<SsoProviderDiscovery[]>('/api/sso/providers').then(
|
||||
(providers) => {
|
||||
if (active) setSsoProviders(providers.filter((provider) => provider.configured));
|
||||
},
|
||||
() => {
|
||||
if (active) setSsoProviders([]);
|
||||
},
|
||||
);
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>): Promise<void> {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
|
||||
const form = new FormData(event.currentTarget);
|
||||
const email = String(form.get('email') ?? '');
|
||||
const password = String(form.get('password') ?? '');
|
||||
|
||||
try {
|
||||
const result = await signIn.email({ email, password });
|
||||
|
||||
if (result.error) {
|
||||
setError(result.error.message ?? 'Sign in failed');
|
||||
return;
|
||||
}
|
||||
|
||||
navigate('/chat', { replace: true });
|
||||
} catch (caught: unknown) {
|
||||
setError(caught instanceof Error ? caught.message : 'Sign in failed');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSsoSignIn(providerId: SsoProviderDiscovery['id']): Promise<void> {
|
||||
setError(null);
|
||||
setSsoLoadingProviderId(providerId);
|
||||
|
||||
try {
|
||||
const result = await authClient.signIn.oauth2({
|
||||
providerId,
|
||||
callbackURL: '/chat',
|
||||
newUserCallbackURL: '/chat',
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
setError(result.error.message ?? `Sign in with ${providerId} failed`);
|
||||
setSsoLoadingProviderId(null);
|
||||
}
|
||||
} catch (caught: unknown) {
|
||||
setError(caught instanceof Error ? caught.message : `Sign in with ${providerId} failed`);
|
||||
setSsoLoadingProviderId(null);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold">Sign in</h1>
|
||||
<p className="mt-1 text-sm text-text-secondary">Sign in to your Mosaic account</p>
|
||||
|
||||
{error ? (
|
||||
<div
|
||||
role="alert"
|
||||
className="mt-4 rounded-lg border border-error/30 bg-error/10 px-4 py-3 text-sm text-error"
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<form className="mt-6 space-y-4" onSubmit={handleSubmit}>
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-text-secondary">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
disabled={loading}
|
||||
className="mt-1 block w-full rounded-lg border border-surface-border bg-surface-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:opacity-50"
|
||||
placeholder="[email protected]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-text-secondary">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
disabled={loading}
|
||||
className="mt-1 block w-full rounded-lg border border-surface-border bg-surface-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:opacity-50"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full rounded-lg bg-blue-600 px-4 py-2.5 text-sm font-medium text-white transition-colors hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-surface-card disabled:opacity-50"
|
||||
>
|
||||
{loading ? 'Signing in...' : 'Sign in'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<SsoProviderButtons
|
||||
providers={ssoProviders}
|
||||
loadingProviderId={ssoLoadingProviderId}
|
||||
onOidcSignIn={(providerId) => {
|
||||
void handleSsoSignIn(providerId);
|
||||
}}
|
||||
/>
|
||||
|
||||
<p className="mt-4 text-center text-sm text-text-muted">
|
||||
Don't have an account?{' '}
|
||||
<Link to="/register" className="text-blue-400 hover:text-blue-300">
|
||||
Sign up
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export function getErrorMessage(error: unknown, fallback: string): string {
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import type { Mission, Project, Task } from '@/lib/types';
|
||||
|
||||
export const projectFixtures: Project[] = [
|
||||
{
|
||||
id: 'project-1',
|
||||
name: 'Mosaic Stack',
|
||||
description: 'Gateway and dashboard parity work',
|
||||
status: 'active',
|
||||
userId: 'user-1',
|
||||
metadata: {
|
||||
prd: '# Mosaic Stack PRD\n\n## Objective\n\nShip the SPA route parity pages.',
|
||||
},
|
||||
createdAt: '2026-08-01T12:00:00.000Z',
|
||||
updatedAt: '2026-08-09T18:30:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 'project-2',
|
||||
name: 'Agent Runtime',
|
||||
description: 'Pi SDK integration',
|
||||
status: 'paused',
|
||||
userId: 'user-1',
|
||||
metadata: null,
|
||||
createdAt: '2026-08-02T08:00:00.000Z',
|
||||
updatedAt: '2026-08-05T10:00:00.000Z',
|
||||
},
|
||||
];
|
||||
|
||||
export const missionFixtures: Mission[] = [
|
||||
{
|
||||
id: 'mission-1',
|
||||
name: 'Ship web parity',
|
||||
description: 'Port read-only routes into the SPA',
|
||||
status: 'active',
|
||||
projectId: 'project-1',
|
||||
metadata: null,
|
||||
createdAt: '2026-08-03T12:00:00.000Z',
|
||||
updatedAt: '2026-08-09T12:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 'mission-2',
|
||||
name: 'Unrelated mission',
|
||||
description: 'Must be filtered out of the project detail view',
|
||||
status: 'planning',
|
||||
projectId: 'project-2',
|
||||
metadata: null,
|
||||
createdAt: '2026-08-04T12:00:00.000Z',
|
||||
updatedAt: '2026-08-04T12:00:00.000Z',
|
||||
},
|
||||
];
|
||||
|
||||
export const taskFixtures: Task[] = [
|
||||
{
|
||||
id: 'task-1',
|
||||
title: 'Route /projects',
|
||||
description: 'Port the read-only projects listing into the SPA',
|
||||
status: 'done',
|
||||
priority: 'high',
|
||||
projectId: 'project-1',
|
||||
missionId: 'mission-1',
|
||||
assignee: 'Jarvis',
|
||||
tags: ['spa', 'projects'],
|
||||
dueDate: '2026-08-12T00:00:00.000Z',
|
||||
metadata: {
|
||||
notes: 'Read-only modal content should remain intact.',
|
||||
pr_links: [{ url: 'https://example.invalid/pr/1', label: 'PR #1' }],
|
||||
},
|
||||
createdAt: '2026-08-04T10:00:00.000Z',
|
||||
updatedAt: '2026-08-09T15:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 'task-2',
|
||||
title: 'Route /projects/:id',
|
||||
description: 'Reuse overview, tasks, missions, and PRD tabs',
|
||||
status: 'in-progress',
|
||||
priority: 'critical',
|
||||
projectId: 'project-1',
|
||||
missionId: 'mission-1',
|
||||
assignee: null,
|
||||
tags: ['spa', 'detail'],
|
||||
dueDate: null,
|
||||
metadata: null,
|
||||
createdAt: '2026-08-05T09:00:00.000Z',
|
||||
updatedAt: '2026-08-10T08:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 'task-3',
|
||||
title: 'Route /tasks',
|
||||
description: 'Wire list and kanban modal interactions',
|
||||
status: 'blocked',
|
||||
priority: 'medium',
|
||||
projectId: 'project-1',
|
||||
missionId: null,
|
||||
assignee: null,
|
||||
tags: ['spa', 'tasks'],
|
||||
dueDate: null,
|
||||
metadata: null,
|
||||
createdAt: '2026-08-06T09:00:00.000Z',
|
||||
updatedAt: '2026-08-08T08:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 'task-4',
|
||||
title: 'Other project task',
|
||||
description: 'Used only to confirm mission filtering remains project-scoped',
|
||||
status: 'not-started',
|
||||
priority: 'low',
|
||||
projectId: 'project-2',
|
||||
missionId: 'mission-2',
|
||||
assignee: null,
|
||||
tags: null,
|
||||
dueDate: null,
|
||||
metadata: null,
|
||||
createdAt: '2026-08-06T09:00:00.000Z',
|
||||
updatedAt: '2026-08-06T09:00:00.000Z',
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,318 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { createMemoryRouter, RouterProvider, type RouteObject } from 'react-router-dom';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { missionFixtures, projectFixtures, taskFixtures } from './page-fixtures';
|
||||
|
||||
const { apiMock } = vi.hoisted(() => ({
|
||||
apiMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
api: apiMock,
|
||||
}));
|
||||
|
||||
import { ProjectDetailPage } from './project-detail';
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
document.body.replaceChildren();
|
||||
root = null;
|
||||
apiMock.mockReset();
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
async function renderProjectDetailPage(): Promise<ReturnType<typeof createMemoryRouter>> {
|
||||
const routes: RouteObject[] = [
|
||||
{ path: '/projects', element: <p>Projects index target</p> },
|
||||
{ path: '/projects/:id', element: <ProjectDetailPage /> },
|
||||
];
|
||||
const router = createMemoryRouter(routes, { initialEntries: ['/projects/project-1'] });
|
||||
container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root?.render(<RouterProvider router={router} />);
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
function clickButtonByText(text: string): void {
|
||||
const button = [...container.querySelectorAll('button')].find((candidate) =>
|
||||
candidate.textContent?.includes(text),
|
||||
);
|
||||
if (!button) {
|
||||
throw new Error(`Button containing "${text}" not found`);
|
||||
}
|
||||
button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
}
|
||||
|
||||
async function flushAct(): Promise<void> {
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
|
||||
interface Deferred<T> {
|
||||
promise: Promise<T>;
|
||||
resolve: (value: T) => void;
|
||||
}
|
||||
|
||||
function createDeferred<T>(): Deferred<T> {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((res) => {
|
||||
resolve = res;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
const projectOneTasks = taskFixtures.filter((task) => task.projectId === 'project-1');
|
||||
|
||||
function mockHealthyLoad(): void {
|
||||
apiMock
|
||||
.mockResolvedValueOnce(projectFixtures[0])
|
||||
.mockResolvedValueOnce(missionFixtures)
|
||||
.mockResolvedValueOnce(projectOneTasks);
|
||||
}
|
||||
|
||||
describe('ProjectDetailPage', () => {
|
||||
it('loads the project, tasks, missions, and optional PRD content for the active project', async () => {
|
||||
mockHealthyLoad();
|
||||
|
||||
await renderProjectDetailPage();
|
||||
|
||||
expect(apiMock.mock.calls.map((call) => call[0])).toEqual([
|
||||
'/api/projects/project-1',
|
||||
'/api/missions',
|
||||
'/api/tasks?projectId=project-1',
|
||||
]);
|
||||
|
||||
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||
'current',
|
||||
);
|
||||
expect(container.textContent).toContain('Mosaic Stack');
|
||||
expect(container.textContent).toContain('Route /projects/:id');
|
||||
expect(container.textContent).toContain('Tasks');
|
||||
expect(container.textContent).toContain('Done');
|
||||
expect(container.textContent).toContain('Blocked');
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Missions (1)');
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain('Ship web parity');
|
||||
expect(container.textContent).not.toContain('Unrelated mission');
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('PRD');
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain('Mosaic Stack PRD');
|
||||
expect(container.textContent).toContain('Ship the SPA route parity pages.');
|
||||
});
|
||||
|
||||
it('opens and closes the existing read-only task modal from the tasks tab', async () => {
|
||||
mockHealthyLoad();
|
||||
|
||||
await renderProjectDetailPage();
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Tasks (3)');
|
||||
});
|
||||
|
||||
const row = [...container.querySelectorAll('tr')].find((candidate) =>
|
||||
candidate.textContent?.includes('Route /projects'),
|
||||
);
|
||||
expect(row).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
row?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(container.querySelector('[role="dialog"]')).toBeTruthy();
|
||||
expect(container.textContent).toContain('Read-only modal content should remain intact.');
|
||||
|
||||
const closeButton = container.querySelector('button[aria-label="Close task details"]');
|
||||
expect(closeButton).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
closeButton?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(container.querySelector('[role="dialog"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows verified completion verdicts when the task collection is current', async () => {
|
||||
mockHealthyLoad();
|
||||
|
||||
await renderProjectDetailPage();
|
||||
|
||||
const doneCard = [...container.querySelectorAll('div')].find(
|
||||
(candidate) => candidate.textContent === 'Done1',
|
||||
);
|
||||
expect(doneCard).toBeTruthy();
|
||||
const inProgressCard = [...container.querySelectorAll('div')].find(
|
||||
(candidate) => candidate.textContent === 'In Progress1',
|
||||
);
|
||||
expect(inProgressCard).toBeTruthy();
|
||||
});
|
||||
|
||||
it('renders an explicit unavailable missions tab when the missions request fails (partial, not empty)', async () => {
|
||||
apiMock
|
||||
.mockResolvedValueOnce(projectFixtures[0])
|
||||
.mockRejectedValueOnce(new Error('Missions request failed'))
|
||||
.mockResolvedValueOnce(projectOneTasks);
|
||||
|
||||
await renderProjectDetailPage();
|
||||
|
||||
// Secondary failure degrades the surface to partial; the project itself
|
||||
// still renders.
|
||||
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||
'partial',
|
||||
);
|
||||
expect(container.textContent).toContain('Mosaic Stack');
|
||||
const partial = container.querySelector('[role="status"]');
|
||||
expect(partial?.textContent).toContain('Missions');
|
||||
expect(partial?.textContent).toContain('unavailable');
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Missions (?)');
|
||||
});
|
||||
|
||||
const alert = container.querySelector('[role="alert"]');
|
||||
expect(alert?.textContent).toContain('Missions request failed');
|
||||
// Negative control: a failed fetch must not look like an empty list.
|
||||
expect(container.textContent).not.toContain('No missions for this project');
|
||||
});
|
||||
|
||||
it('marks derived verdicts unknown when the tasks collection is unavailable', async () => {
|
||||
apiMock
|
||||
.mockResolvedValueOnce(projectFixtures[0])
|
||||
.mockResolvedValueOnce(missionFixtures)
|
||||
.mockRejectedValueOnce(new Error('Tasks request failed'));
|
||||
|
||||
await renderProjectDetailPage();
|
||||
|
||||
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||
'partial',
|
||||
);
|
||||
|
||||
// Completion verdicts become unknown ('?') — never green counts.
|
||||
for (const label of ['Done', 'In Progress', 'Blocked', 'Tasks']) {
|
||||
const unknownCard = [...container.querySelectorAll('div')].find(
|
||||
(candidate) => candidate.textContent === `${label}?`,
|
||||
);
|
||||
expect(unknownCard, `expected ${label} card to render ?`).toBeTruthy();
|
||||
}
|
||||
// Negative control: no green "Done 1" verdict anywhere.
|
||||
expect(
|
||||
[...container.querySelectorAll('div')].some((candidate) => candidate.textContent === 'Done1'),
|
||||
).toBe(false);
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Tasks (?)');
|
||||
});
|
||||
|
||||
const alert = container.querySelector('[role="alert"]');
|
||||
expect(alert?.textContent).toContain('Tasks request failed');
|
||||
// Negative control: no healthy empty task list from a failed fetch.
|
||||
expect(container.textContent).not.toContain('No tasks found');
|
||||
expect(container.querySelector('table')).toBeNull();
|
||||
});
|
||||
|
||||
it('recovers a partial surface to current after revalidation', async () => {
|
||||
apiMock
|
||||
.mockResolvedValueOnce(projectFixtures[0])
|
||||
.mockResolvedValueOnce(missionFixtures)
|
||||
.mockRejectedValueOnce(new Error('Tasks request failed'))
|
||||
.mockResolvedValueOnce(projectFixtures[0])
|
||||
.mockResolvedValueOnce(missionFixtures)
|
||||
.mockResolvedValueOnce(projectOneTasks);
|
||||
|
||||
await renderProjectDetailPage();
|
||||
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||
'partial',
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Revalidate');
|
||||
});
|
||||
await flushAct();
|
||||
|
||||
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||
'current',
|
||||
);
|
||||
expect(
|
||||
[...container.querySelectorAll('div')].some((candidate) => candidate.textContent === 'Done1'),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("never shows one project's data on another project's route after navigation", async () => {
|
||||
mockHealthyLoad();
|
||||
|
||||
const router = await renderProjectDetailPage();
|
||||
expect(container.textContent).toContain('Mosaic Stack');
|
||||
|
||||
const deferred = createDeferred<(typeof projectFixtures)[number]>();
|
||||
apiMock
|
||||
.mockResolvedValueOnce(deferred.promise)
|
||||
.mockResolvedValueOnce([])
|
||||
.mockResolvedValueOnce([]);
|
||||
|
||||
await act(async () => {
|
||||
await router.navigate('/projects/project-2');
|
||||
});
|
||||
|
||||
// While project-2 loads, nothing from project-1 may render on its route.
|
||||
expect(container.textContent).toContain('Loading project...');
|
||||
expect(container.textContent).not.toContain('Mosaic Stack');
|
||||
expect(container.textContent).not.toContain('Route /projects/:id');
|
||||
|
||||
await act(async () => {
|
||||
deferred.resolve(projectFixtures[1]!);
|
||||
await deferred.promise;
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain('Agent Runtime');
|
||||
expect(apiMock.mock.calls[3]?.[0]).toBe('/api/projects/project-2');
|
||||
});
|
||||
|
||||
it('renders a visible unavailable state when the project request fails and lets the user navigate back', async () => {
|
||||
apiMock
|
||||
.mockRejectedValueOnce(new Error('Project request failed'))
|
||||
.mockResolvedValueOnce(missionFixtures)
|
||||
.mockResolvedValueOnce(projectOneTasks);
|
||||
|
||||
const router = await renderProjectDetailPage();
|
||||
|
||||
const alert = container.querySelector('[role="alert"]');
|
||||
expect(alert).toBeTruthy();
|
||||
expect(alert?.textContent).toContain('Project request failed');
|
||||
expect(alert?.textContent).toContain('not an empty result');
|
||||
expect(container.textContent).not.toContain('Mosaic Stack');
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Back to projects');
|
||||
});
|
||||
|
||||
expect(router.state.location.pathname).toBe('/projects');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,457 @@
|
||||
import { useState, type ReactElement } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { MissionTimeline } from '@/components/projects/mission-timeline';
|
||||
import { PrdViewer } from '@/components/projects/prd-viewer';
|
||||
import { TaskDetailModal } from '@/components/tasks/task-detail-modal';
|
||||
import { TaskListView } from '@/components/tasks/task-list-view';
|
||||
import { TaskStatusSummary } from '@/components/tasks/task-status-summary';
|
||||
import {
|
||||
PartialDataNotice,
|
||||
StaleDataNotice,
|
||||
UnavailableDataNotice,
|
||||
} from '@/components/freshness/freshness-notices';
|
||||
import { api } from '@/lib/api';
|
||||
import { cn } from '@/lib/cn';
|
||||
import type { Mission, Project, Task, TaskStatus } from '@/lib/types';
|
||||
import {
|
||||
combineFreshness,
|
||||
UNKNOWN_VERDICT,
|
||||
verdictValue,
|
||||
type FreshSnapshot,
|
||||
} from '@/lib/freshness/model';
|
||||
import { describeFailure, useFreshCollection } from '@/lib/freshness/use-fresh-collection';
|
||||
import {
|
||||
validateMissionCollection,
|
||||
validateProjectEntity,
|
||||
validateTaskCollection,
|
||||
} from '@/lib/freshness/validators';
|
||||
|
||||
type Tab = 'overview' | 'tasks' | 'missions' | 'prd';
|
||||
|
||||
const projectStatusColors: Record<string, string> = {
|
||||
active: 'bg-success/20 text-success',
|
||||
paused: 'bg-warning/20 text-warning',
|
||||
completed: 'bg-blue-600/20 text-blue-400',
|
||||
archived: 'bg-gray-600/20 text-gray-400',
|
||||
};
|
||||
|
||||
const taskStatusColors: Record<string, string> = {
|
||||
'not-started': 'bg-gray-600/20 text-gray-300',
|
||||
'in-progress': 'bg-blue-600/20 text-blue-400',
|
||||
blocked: 'bg-error/20 text-error',
|
||||
done: 'bg-success/20 text-success',
|
||||
cancelled: 'bg-gray-600/20 text-gray-500',
|
||||
};
|
||||
|
||||
interface TabButtonProps {
|
||||
id: Tab;
|
||||
label: string;
|
||||
activeTab: Tab;
|
||||
onClick: (tab: Tab) => void;
|
||||
}
|
||||
|
||||
function TabButton({ id, label, activeTab, onClick }: TabButtonProps): ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onClick(id)}
|
||||
className={cn(
|
||||
'border-b-2 px-4 py-2 text-sm transition-colors',
|
||||
activeTab === id
|
||||
? 'border-text-primary text-text-primary'
|
||||
: 'border-transparent text-text-muted hover:text-text-secondary',
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** Remounts per project id so no state from one project renders for another. */
|
||||
export function ProjectDetailPage(): ReactElement {
|
||||
const { id = '' } = useParams();
|
||||
return <ProjectDetail id={id} key={id} />;
|
||||
}
|
||||
|
||||
function ProjectDetail({ id }: { id: string }): ReactElement {
|
||||
const navigate = useNavigate();
|
||||
const enabled = id.length > 0;
|
||||
|
||||
// Primary collection gates the surface; missions and tasks are secondaries
|
||||
// whose failures degrade the surface to `partial` instead of rendering
|
||||
// empty healthy lists.
|
||||
const project = useFreshCollection<Project>({
|
||||
source: `gateway:/api/projects/${id}`,
|
||||
fetcher: (signal) => api<unknown>(`/api/projects/${id}`, { signal }),
|
||||
validate: validateProjectEntity,
|
||||
// No last-known restore: the entity carries workspace identity that
|
||||
// cannot be scope-checked before display (see ProjectsPage note).
|
||||
enabled,
|
||||
});
|
||||
const missions = useFreshCollection<Mission[]>({
|
||||
source: 'gateway:/api/missions',
|
||||
fetcher: (signal) => api<unknown>('/api/missions', { signal }),
|
||||
validate: validateMissionCollection,
|
||||
cacheKey: enabled ? 'missions' : null,
|
||||
enabled,
|
||||
});
|
||||
const tasks = useFreshCollection<Task[]>({
|
||||
source: `gateway:/api/tasks?projectId=${id}`,
|
||||
fetcher: (signal) => api<unknown>(`/api/tasks?projectId=${id}`, { signal }),
|
||||
validate: validateTaskCollection,
|
||||
cacheKey: enabled ? `project-tasks:${id}` : null,
|
||||
enabled,
|
||||
});
|
||||
|
||||
const [activeTab, setActiveTab] = useState<Tab>('overview');
|
||||
const [taskFilter, setTaskFilter] = useState<TaskStatus | 'all'>('all');
|
||||
const [selectedTask, setSelectedTask] = useState<Task | null>(null);
|
||||
|
||||
const surface = combineFreshness(project.freshness, [missions.freshness, tasks.freshness]);
|
||||
const tasksVerified = tasks.freshness === 'current';
|
||||
const projectMissions = missions.data?.filter((mission) => mission.projectId === id) ?? null;
|
||||
|
||||
const retryAll = (): void => {
|
||||
void Promise.all([project.revalidate(), missions.revalidate(), tasks.revalidate()]);
|
||||
};
|
||||
|
||||
if (!enabled) {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col px-4 py-6 sm:px-6">
|
||||
<header className="mb-6 border-b px-1 pb-3">
|
||||
<h1 className="text-2xl font-semibold">Project</h1>
|
||||
</header>
|
||||
<div role="alert" className="rounded-lg border border-error/40 px-4 py-3 text-sm">
|
||||
Project id is missing.
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate('/projects')}
|
||||
className="mt-4 w-fit text-sm underline"
|
||||
>
|
||||
Back to projects
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (project.freshness === 'unknown') {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col px-4 py-6 sm:px-6">
|
||||
<header className="mb-6 border-b px-1 pb-3">
|
||||
<h1 className="text-2xl font-semibold">Project</h1>
|
||||
</header>
|
||||
<p className="py-16 text-center text-sm text-text-muted">Loading project...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (project.freshness === 'unavailable' || project.data === null) {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col px-4 py-6 sm:px-6">
|
||||
<header className="mb-6 border-b px-1 pb-3">
|
||||
<h1 className="text-2xl font-semibold">Project</h1>
|
||||
</header>
|
||||
<UnavailableDataNotice
|
||||
title="This project"
|
||||
detail={describeFailure(project.failure)}
|
||||
onRetry={retryAll}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate('/projects')}
|
||||
className="mt-4 w-fit text-sm underline"
|
||||
>
|
||||
Back to projects
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const projectTasks = tasks.data ?? null;
|
||||
const filteredTasks =
|
||||
projectTasks === null
|
||||
? []
|
||||
: taskFilter === 'all'
|
||||
? projectTasks
|
||||
: projectTasks.filter((task) => task.status === taskFilter);
|
||||
|
||||
// Derived completion verdicts: unknown (never green) unless the task
|
||||
// collection is verified current.
|
||||
const doneCount = projectTasks?.filter((task) => task.status === 'done').length ?? 0;
|
||||
const inProgressCount = projectTasks?.filter((task) => task.status === 'in-progress').length ?? 0;
|
||||
const blockedCount = projectTasks?.filter((task) => task.status === 'blocked').length ?? 0;
|
||||
|
||||
const prdContent = getPrdContent(project.data);
|
||||
const tabs: Array<{ id: Tab; label: string }> = [
|
||||
{ id: 'overview', label: 'Overview' },
|
||||
{
|
||||
id: 'tasks',
|
||||
label: `Tasks (${projectTasks === null ? UNKNOWN_VERDICT : projectTasks.length})`,
|
||||
},
|
||||
{
|
||||
id: 'missions',
|
||||
label: `Missions (${projectMissions === null ? UNKNOWN_VERDICT : projectMissions.length})`,
|
||||
},
|
||||
...(prdContent ? [{ id: 'prd' as const, label: 'PRD' }] : []),
|
||||
];
|
||||
|
||||
const staleSnapshot: FreshSnapshot<unknown> | null =
|
||||
project.freshness === 'stale'
|
||||
? project.snapshot
|
||||
: missions.freshness === 'stale'
|
||||
? missions.snapshot
|
||||
: tasks.freshness === 'stale'
|
||||
? tasks.snapshot
|
||||
: null;
|
||||
const missingSections: string[] = [];
|
||||
if (missions.freshness === 'unavailable') missingSections.push('Missions');
|
||||
if (tasks.freshness === 'unavailable') missingSections.push('Tasks');
|
||||
|
||||
return (
|
||||
<div data-freshness={surface} className="flex min-h-screen flex-col px-4 py-6 sm:px-6">
|
||||
<header className="mb-6 border-b px-1 pb-3">
|
||||
<nav className="mb-4 flex items-center gap-2 text-sm text-text-muted">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate('/projects')}
|
||||
className="hover:text-text-secondary"
|
||||
>
|
||||
Projects
|
||||
</button>
|
||||
<span>/</span>
|
||||
<span className="text-text-primary">{project.data.name}</span>
|
||||
</nav>
|
||||
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-2xl font-semibold text-text-primary">{project.data.name}</h1>
|
||||
<span
|
||||
className={cn(
|
||||
'rounded-full px-2 py-0.5 text-xs',
|
||||
projectStatusColors[project.data.status] ?? 'bg-gray-600/20 text-gray-400',
|
||||
)}
|
||||
>
|
||||
{project.data.status}
|
||||
</span>
|
||||
</div>
|
||||
{project.data.description ? (
|
||||
<p className="mt-1 text-sm text-text-muted">{project.data.description}</p>
|
||||
) : null}
|
||||
<p className="mt-2 text-xs text-text-muted">
|
||||
Created {new Date(project.data.createdAt).toLocaleDateString()} · Updated{' '}
|
||||
{new Date(project.data.updatedAt).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{staleSnapshot !== null ? (
|
||||
<div className="mb-6">
|
||||
<StaleDataNotice label={staleSnapshot} onRetry={retryAll} />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{missingSections.length > 0 ? (
|
||||
<div className="mb-6">
|
||||
<PartialDataNotice missing={missingSections} onRetry={retryAll} />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||
<StatCard
|
||||
label="Tasks"
|
||||
value={projectTasks === null ? UNKNOWN_VERDICT : String(projectTasks.length)}
|
||||
/>
|
||||
<StatCard
|
||||
label="Done"
|
||||
value={verdictValue(tasksVerified, String(doneCount))}
|
||||
valueClass={tasksVerified ? 'text-success' : undefined}
|
||||
/>
|
||||
<StatCard
|
||||
label="In Progress"
|
||||
value={verdictValue(tasksVerified, String(inProgressCount))}
|
||||
valueClass={tasksVerified ? 'text-blue-400' : undefined}
|
||||
/>
|
||||
<StatCard
|
||||
label="Blocked"
|
||||
value={verdictValue(tasksVerified, String(blockedCount))}
|
||||
valueClass={tasksVerified && blockedCount > 0 ? 'text-error' : undefined}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mb-6 flex gap-0 border-b border-surface-border">
|
||||
{tabs.map((tab) => (
|
||||
<TabButton
|
||||
key={tab.id}
|
||||
id={tab.id}
|
||||
label={tab.label}
|
||||
activeTab={activeTab}
|
||||
onClick={setActiveTab}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{activeTab === 'overview' ? (
|
||||
<OverviewTab project={project.data} missions={projectMissions} tasks={projectTasks} />
|
||||
) : null}
|
||||
|
||||
{activeTab === 'tasks' ? (
|
||||
<div>
|
||||
{projectTasks === null ? (
|
||||
<UnavailableDataNotice
|
||||
title="Tasks"
|
||||
detail={describeFailure(tasks.failure)}
|
||||
onRetry={retryAll}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div className="mb-4">
|
||||
<TaskStatusSummary
|
||||
tasks={projectTasks}
|
||||
activeFilter={taskFilter}
|
||||
onFilterChange={setTaskFilter}
|
||||
/>
|
||||
</div>
|
||||
<TaskListView tasks={filteredTasks} onTaskClick={setSelectedTask} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{activeTab === 'missions' ? (
|
||||
projectMissions === null ? (
|
||||
<UnavailableDataNotice
|
||||
title="Missions"
|
||||
detail={describeFailure(missions.failure)}
|
||||
onRetry={retryAll}
|
||||
/>
|
||||
) : (
|
||||
<MissionTimeline missions={projectMissions} />
|
||||
)
|
||||
) : null}
|
||||
|
||||
{activeTab === 'prd' && prdContent ? (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-6">
|
||||
<PrdViewer content={prdContent} />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{selectedTask ? (
|
||||
<TaskDetailModal task={selectedTask} onClose={() => setSelectedTask(null)} />
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OverviewTab({
|
||||
project,
|
||||
missions,
|
||||
tasks,
|
||||
}: {
|
||||
project: Project;
|
||||
missions: Mission[] | null;
|
||||
tasks: Task[] | null;
|
||||
}): ReactElement {
|
||||
const recentTasks =
|
||||
tasks === null
|
||||
? null
|
||||
: [...tasks]
|
||||
.sort(
|
||||
(left, right) =>
|
||||
new Date(right.updatedAt).getTime() - new Date(left.updatedAt).getTime(),
|
||||
)
|
||||
.slice(0, 5);
|
||||
|
||||
return (
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
<section>
|
||||
<h2 className="mb-3 text-sm font-semibold text-text-secondary">Recent Tasks</h2>
|
||||
{recentTasks === null ? (
|
||||
<UnavailableDataNotice title="Tasks" />
|
||||
) : recentTasks.length === 0 ? (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-4 text-center">
|
||||
<p className="text-sm text-text-muted">No tasks yet</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{recentTasks.map((task) => (
|
||||
<div
|
||||
key={task.id}
|
||||
className="flex items-center justify-between gap-2 rounded-lg border border-surface-border bg-surface-card px-3 py-2"
|
||||
>
|
||||
<span className="truncate text-sm text-text-primary">{task.title}</span>
|
||||
<span
|
||||
className={cn(
|
||||
'shrink-0 rounded-full px-2 py-0.5 text-xs',
|
||||
taskStatusColors[task.status] ?? 'bg-gray-600/20 text-gray-400',
|
||||
)}
|
||||
>
|
||||
{task.status}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 className="mb-3 text-sm font-semibold text-text-secondary">Missions</h2>
|
||||
{missions === null ? (
|
||||
<UnavailableDataNotice title="Missions" />
|
||||
) : missions.length === 0 ? (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-4 text-center">
|
||||
<p className="text-sm text-text-muted">No missions yet</p>
|
||||
</div>
|
||||
) : (
|
||||
<MissionTimeline missions={missions.slice(0, 4)} />
|
||||
)}
|
||||
</section>
|
||||
|
||||
{project.metadata && Object.keys(project.metadata).length > 0 ? (
|
||||
<section className="lg:col-span-2">
|
||||
<h2 className="mb-3 text-sm font-semibold text-text-secondary">Project Metadata</h2>
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-4">
|
||||
<pre className="overflow-x-auto text-xs text-text-muted">
|
||||
{JSON.stringify(project.metadata, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StatCard({
|
||||
label,
|
||||
value,
|
||||
valueClass,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
valueClass?: string;
|
||||
}): ReactElement {
|
||||
return (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-3">
|
||||
<p className="text-xs text-text-muted">{label}</p>
|
||||
<p className={cn('mt-1 text-lg font-semibold', valueClass ?? 'text-text-primary')}>{value}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function getPrdContent(project: Project): string | null {
|
||||
if (!project.metadata) return null;
|
||||
|
||||
const prd = project.metadata['prd'];
|
||||
if (typeof prd === 'string' && prd.trim().length > 0) {
|
||||
return prd;
|
||||
}
|
||||
|
||||
const prdContent = project.metadata['prdContent'];
|
||||
if (typeof prdContent === 'string' && prdContent.trim().length > 0) {
|
||||
return prdContent;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { createMemoryRouter, RouterProvider, type RouteObject } from 'react-router-dom';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { projectFixtures } from './page-fixtures';
|
||||
|
||||
const { apiMock } = vi.hoisted(() => ({
|
||||
apiMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
api: apiMock,
|
||||
}));
|
||||
|
||||
import { ProjectsPage } from './projects';
|
||||
|
||||
interface Deferred<T> {
|
||||
promise: Promise<T>;
|
||||
resolve: (value: T) => void;
|
||||
reject: (reason?: unknown) => void;
|
||||
}
|
||||
|
||||
function createDeferred<T>(): Deferred<T> {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
document.body.replaceChildren();
|
||||
root = null;
|
||||
apiMock.mockReset();
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
async function renderProjectsPage(): Promise<ReturnType<typeof createMemoryRouter>> {
|
||||
const routes: RouteObject[] = [
|
||||
{ path: '/projects', element: <ProjectsPage /> },
|
||||
{ path: '/projects/:id', element: <p>Project detail target</p> },
|
||||
];
|
||||
|
||||
const router = createMemoryRouter(routes, { initialEntries: ['/projects'] });
|
||||
container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root?.render(<RouterProvider router={router} />);
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
function clickButtonByText(text: string): void {
|
||||
const button = [...container.querySelectorAll('button')].find((candidate) =>
|
||||
candidate.textContent?.includes(text),
|
||||
);
|
||||
if (!button) {
|
||||
throw new Error(`Button containing "${text}" not found`);
|
||||
}
|
||||
button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
}
|
||||
|
||||
async function flushAct(): Promise<void> {
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
|
||||
describe('ProjectsPage', () => {
|
||||
it('shows a visible loading state while the project request is in flight', async () => {
|
||||
const deferred = createDeferred<typeof projectFixtures>();
|
||||
apiMock.mockReturnValueOnce(deferred.promise);
|
||||
|
||||
await renderProjectsPage();
|
||||
|
||||
expect(container.textContent).toContain('Loading projects...');
|
||||
|
||||
await act(async () => {
|
||||
deferred.resolve(projectFixtures);
|
||||
await deferred.promise;
|
||||
});
|
||||
});
|
||||
|
||||
it('renders project cards from the API and navigates to a project detail route on click', async () => {
|
||||
apiMock.mockResolvedValueOnce(projectFixtures);
|
||||
|
||||
const router = await renderProjectsPage();
|
||||
|
||||
expect(apiMock.mock.calls[0]?.[0]).toBe('/api/projects');
|
||||
expect(container.textContent).toContain('Mosaic Stack');
|
||||
expect(container.textContent).toContain('Agent Runtime');
|
||||
|
||||
const button = [...container.querySelectorAll('button')].find((candidate) =>
|
||||
candidate.textContent?.includes('Mosaic Stack'),
|
||||
);
|
||||
expect(button).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
button?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(router.state.location.pathname).toBe('/projects/project-1');
|
||||
expect(container.textContent).toContain('Project detail target');
|
||||
});
|
||||
|
||||
it('renders the empty state only for a verified empty collection', async () => {
|
||||
apiMock.mockResolvedValueOnce([]);
|
||||
|
||||
await renderProjectsPage();
|
||||
|
||||
expect(container.textContent).toContain('No projects yet');
|
||||
expect(container.textContent).toContain(
|
||||
'Projects will appear here when created via the gateway API',
|
||||
);
|
||||
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||
'current',
|
||||
);
|
||||
});
|
||||
|
||||
it('renders a failed fetch as an explicit unavailable state, never an empty collection', async () => {
|
||||
apiMock.mockRejectedValueOnce(new Error('Projects are unavailable'));
|
||||
|
||||
await renderProjectsPage();
|
||||
|
||||
const alert = container.querySelector('[role="alert"]');
|
||||
expect(alert).toBeTruthy();
|
||||
expect(alert?.textContent).toContain('Projects are unavailable');
|
||||
expect(alert?.textContent).toContain('not an empty result');
|
||||
|
||||
// Negative controls: no healthy empty state and no project cards render
|
||||
// from a failed fetch.
|
||||
expect(container.textContent).not.toContain('No projects yet');
|
||||
expect(container.textContent).not.toContain('Mosaic Stack');
|
||||
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||
'unavailable',
|
||||
);
|
||||
});
|
||||
|
||||
it('renders an auth failure as unavailable and recovers after retry', async () => {
|
||||
apiMock
|
||||
.mockRejectedValueOnce(Object.assign(new Error('Unauthorized'), { statusCode: 401 }))
|
||||
.mockResolvedValueOnce(projectFixtures);
|
||||
|
||||
await renderProjectsPage();
|
||||
|
||||
const alert = container.querySelector('[role="alert"]');
|
||||
expect(alert?.textContent).toContain('Unauthorized');
|
||||
expect(container.textContent).not.toContain('No projects yet');
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Retry');
|
||||
});
|
||||
await flushAct();
|
||||
|
||||
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||||
expect(container.textContent).toContain('Mosaic Stack');
|
||||
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||
'current',
|
||||
);
|
||||
});
|
||||
|
||||
it('renders a schema-mismatched response as unavailable, never as data', async () => {
|
||||
apiMock.mockResolvedValueOnce({ results: projectFixtures });
|
||||
|
||||
await renderProjectsPage();
|
||||
|
||||
const alert = container.querySelector('[role="alert"]');
|
||||
expect(alert?.textContent).toContain('not an empty result');
|
||||
expect(container.textContent).not.toContain('Mosaic Stack');
|
||||
expect(container.textContent).not.toContain('No projects yet');
|
||||
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||
'unavailable',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { type ReactElement } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { ProjectCard } from '@/components/projects/project-card';
|
||||
import { StaleDataNotice, UnavailableDataNotice } from '@/components/freshness/freshness-notices';
|
||||
import { api } from '@/lib/api';
|
||||
import type { Project } from '@/lib/types';
|
||||
import { useFreshCollection, describeFailure } from '@/lib/freshness/use-fresh-collection';
|
||||
import { validateProjectCollection } from '@/lib/freshness/validators';
|
||||
|
||||
export function ProjectsPage(): ReactElement {
|
||||
const navigate = useNavigate();
|
||||
const projects = useFreshCollection<Project[]>({
|
||||
source: 'gateway:/api/projects',
|
||||
fetcher: (signal) => api<unknown>('/api/projects', { signal }),
|
||||
validate: validateProjectCollection,
|
||||
// Projects carry workspace identity (userId) that is only knowable from
|
||||
// the payload itself, so a restored entry cannot be scope-checked before
|
||||
// display. Conservative choice: no last-known restore for this surface;
|
||||
// cross-workspace switching is still invalidated at verification time.
|
||||
});
|
||||
const retry = (): void => {
|
||||
void projects.revalidate();
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
data-freshness={projects.freshness}
|
||||
className="flex min-h-screen flex-col px-4 py-6 sm:px-6"
|
||||
>
|
||||
<header className="mb-6 border-b px-1 pb-3">
|
||||
<h1 className="text-2xl font-semibold">Projects</h1>
|
||||
</header>
|
||||
|
||||
{projects.freshness === 'stale' && projects.snapshot ? (
|
||||
<div className="mb-6">
|
||||
<StaleDataNotice label={projects.snapshot} onRetry={retry} />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{projects.freshness === 'unknown' ? (
|
||||
<p className="py-8 text-center text-sm text-text-muted">Loading projects...</p>
|
||||
) : projects.freshness === 'unavailable' ? (
|
||||
<UnavailableDataNotice
|
||||
title="Projects"
|
||||
detail={describeFailure(projects.failure)}
|
||||
onRetry={retry}
|
||||
/>
|
||||
) : projects.data !== null && projects.data.length === 0 ? (
|
||||
<div className="py-12 text-center">
|
||||
<h2 className="text-lg font-medium text-text-secondary">No projects yet</h2>
|
||||
<p className="mt-1 text-sm text-text-muted">
|
||||
Projects will appear here when created via the gateway API
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{(projects.data ?? []).map((project) => (
|
||||
<ProjectCard
|
||||
key={project.id}
|
||||
project={project}
|
||||
onClick={(selectedProject) => navigate(`/projects/${selectedProject.id}`)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useState, type FormEvent, type ReactElement } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { signUp } from '@/lib/auth-client';
|
||||
|
||||
export function RegisterPage(): ReactElement {
|
||||
const navigate = useNavigate();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>): Promise<void> {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
|
||||
const form = new FormData(event.currentTarget);
|
||||
const name = String(form.get('name') ?? '');
|
||||
const email = String(form.get('email') ?? '');
|
||||
const password = String(form.get('password') ?? '');
|
||||
|
||||
try {
|
||||
const result = await signUp.email({ name, email, password });
|
||||
|
||||
if (result.error) {
|
||||
setError(result.error.message ?? 'Registration failed');
|
||||
return;
|
||||
}
|
||||
|
||||
navigate('/chat', { replace: true });
|
||||
} catch (caught: unknown) {
|
||||
setError(caught instanceof Error ? caught.message : 'Registration failed');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold">Create account</h1>
|
||||
<p className="mt-1 text-sm text-text-secondary">Get started with Mosaic</p>
|
||||
|
||||
{error ? (
|
||||
<div
|
||||
role="alert"
|
||||
className="mt-4 rounded-lg border border-error/30 bg-error/10 px-4 py-3 text-sm text-error"
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<form className="mt-6 space-y-4" onSubmit={handleSubmit}>
|
||||
<div>
|
||||
<label htmlFor="name" className="block text-sm font-medium text-text-secondary">
|
||||
Name
|
||||
</label>
|
||||
<input
|
||||
id="name"
|
||||
name="name"
|
||||
type="text"
|
||||
autoComplete="name"
|
||||
required
|
||||
disabled={loading}
|
||||
className="mt-1 block w-full rounded-lg border border-surface-border bg-surface-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:opacity-50"
|
||||
placeholder="Your name"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-text-secondary">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
disabled={loading}
|
||||
className="mt-1 block w-full rounded-lg border border-surface-border bg-surface-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:opacity-50"
|
||||
placeholder="[email protected]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-text-secondary">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
required
|
||||
disabled={loading}
|
||||
className="mt-1 block w-full rounded-lg border border-surface-border bg-surface-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:opacity-50"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full rounded-lg bg-blue-600 px-4 py-2.5 text-sm font-medium text-white transition-colors hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-surface-card disabled:opacity-50"
|
||||
>
|
||||
{loading ? 'Creating account...' : 'Create account'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p className="mt-4 text-center text-sm text-text-muted">
|
||||
Already have an account?{' '}
|
||||
<Link to="/login" className="text-blue-400 hover:text-blue-300">
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { createMemoryRouter, RouterProvider, type RouteObject } from 'react-router-dom';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { useSessionMock } = vi.hoisted(() => ({
|
||||
useSessionMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/auth-client', () => ({
|
||||
useSession: useSessionMock,
|
||||
}));
|
||||
|
||||
import { ThemeProvider } from '@/providers/theme-provider';
|
||||
import { routes } from '@/routes';
|
||||
|
||||
function Boom(): never {
|
||||
throw new Error('resource route render blew up');
|
||||
}
|
||||
|
||||
function replaceRouteElementWithBoom(nodes: RouteObject[], path: string): RouteObject[] {
|
||||
return nodes.map((node) => {
|
||||
const cloned: RouteObject = { ...node };
|
||||
if (cloned.path === path) {
|
||||
cloned.element = <Boom />;
|
||||
}
|
||||
if (cloned.children) {
|
||||
cloned.children = replaceRouteElementWithBoom(cloned.children, path);
|
||||
}
|
||||
return cloned;
|
||||
});
|
||||
}
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
document.body.replaceChildren();
|
||||
root = null;
|
||||
useSessionMock.mockReset();
|
||||
});
|
||||
|
||||
describe('resource route error boundaries', () => {
|
||||
it.each(['/projects', '/projects/:id', '/tasks'])(
|
||||
'renders a recoverable fallback when %s throws during route render',
|
||||
async (path) => {
|
||||
useSessionMock.mockReturnValue({ data: { user: { id: 'user-1' } }, isPending: false });
|
||||
|
||||
const initialEntry = path === '/projects/:id' ? '/projects/project-1' : path;
|
||||
const router = createMemoryRouter(replaceRouteElementWithBoom(routes, path), {
|
||||
initialEntries: [initialEntry],
|
||||
});
|
||||
|
||||
container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
|
||||
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
try {
|
||||
await act(async () => {
|
||||
root?.render(
|
||||
<ThemeProvider>
|
||||
<RouterProvider router={router} />
|
||||
</ThemeProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalled();
|
||||
} finally {
|
||||
consoleErrorSpy.mockRestore();
|
||||
}
|
||||
|
||||
expect(container.textContent).not.toBe('');
|
||||
expect(container.querySelector('[role="alert"]')).toBeTruthy();
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { ReactElement } from 'react';
|
||||
import { useRouteError } from 'react-router-dom';
|
||||
|
||||
interface ResourceRouteErrorBoundaryProps {
|
||||
message: string;
|
||||
href: string;
|
||||
linkLabel: string;
|
||||
}
|
||||
|
||||
function ResourceRouteErrorBoundary({
|
||||
message,
|
||||
href,
|
||||
linkLabel,
|
||||
}: ResourceRouteErrorBoundaryProps): ReactElement {
|
||||
useRouteError();
|
||||
|
||||
return (
|
||||
<div role="alert" className="flex min-h-screen flex-col items-center justify-center gap-3 p-8">
|
||||
<p className="text-sm font-medium">{message}</p>
|
||||
<a href={href} className="text-sm underline">
|
||||
{linkLabel}
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProjectsRouteErrorBoundary(): ReactElement {
|
||||
return (
|
||||
<ResourceRouteErrorBoundary
|
||||
message="Something went wrong loading projects."
|
||||
href="/projects"
|
||||
linkLabel="Reload projects"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProjectDetailRouteErrorBoundary(): ReactElement {
|
||||
return (
|
||||
<ResourceRouteErrorBoundary
|
||||
message="Something went wrong loading this project."
|
||||
href="/projects"
|
||||
linkLabel="Back to projects"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function TasksRouteErrorBoundary(): ReactElement {
|
||||
return (
|
||||
<ResourceRouteErrorBoundary
|
||||
message="Something went wrong loading tasks."
|
||||
href="/tasks"
|
||||
linkLabel="Reload tasks"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { createMemoryRouter, RouterProvider, type RouteObject } from 'react-router-dom';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { apiMock, useSessionMock, updateUserMock } = vi.hoisted(() => ({
|
||||
apiMock: vi.fn(),
|
||||
useSessionMock: vi.fn(),
|
||||
updateUserMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
api: apiMock,
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/auth-client', () => ({
|
||||
useSession: useSessionMock,
|
||||
authClient: { updateUser: updateUserMock },
|
||||
}));
|
||||
|
||||
import { SettingsPage } from './settings';
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
document.body.replaceChildren();
|
||||
root = null;
|
||||
apiMock.mockReset();
|
||||
useSessionMock.mockReset();
|
||||
updateUserMock.mockReset();
|
||||
});
|
||||
|
||||
async function renderSettingsPage(): Promise<void> {
|
||||
const routes: RouteObject[] = [{ path: '/settings', element: <SettingsPage /> }];
|
||||
const router = createMemoryRouter(routes, { initialEntries: ['/settings'] });
|
||||
container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root?.render(<RouterProvider router={router} />);
|
||||
});
|
||||
}
|
||||
|
||||
function clickButtonByText(text: string): Promise<void> {
|
||||
const button = [...container.querySelectorAll('button')].find((candidate) =>
|
||||
candidate.textContent?.includes(text),
|
||||
);
|
||||
if (!button) {
|
||||
throw new Error(`Button containing "${text}" not found`);
|
||||
}
|
||||
return act(async () => {
|
||||
button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
}
|
||||
|
||||
const session = {
|
||||
user: { id: 'u-1', name: 'Test User', email: '[email protected]', image: null },
|
||||
};
|
||||
|
||||
describe('SettingsPage profile tab', () => {
|
||||
it('renders the profile form from the session and saves via authClient', async () => {
|
||||
useSessionMock.mockReturnValue({ data: session, isPending: false });
|
||||
updateUserMock.mockResolvedValue({});
|
||||
|
||||
await renderSettingsPage();
|
||||
|
||||
const nameInput = container.querySelector<HTMLInputElement>('#profile-name');
|
||||
const emailInput = container.querySelector<HTMLInputElement>('#profile-email');
|
||||
expect(nameInput?.value).toBe('Test User');
|
||||
expect(emailInput?.value).toBe('[email protected]');
|
||||
expect(emailInput?.disabled).toBe(true);
|
||||
|
||||
await clickButtonByText('Save changes');
|
||||
|
||||
expect(updateUserMock).toHaveBeenCalledWith({ name: 'Test User', image: null });
|
||||
expect(container.textContent).toContain('Saved!');
|
||||
});
|
||||
|
||||
it('surfaces an update failure without clearing the form', async () => {
|
||||
useSessionMock.mockReturnValue({ data: session, isPending: false });
|
||||
updateUserMock.mockResolvedValue({ error: { message: 'name rejected' } });
|
||||
|
||||
await renderSettingsPage();
|
||||
await clickButtonByText('Save changes');
|
||||
|
||||
expect(container.textContent).toContain('name rejected');
|
||||
expect(container.querySelector<HTMLInputElement>('#profile-name')?.value).toBe('Test User');
|
||||
});
|
||||
});
|
||||
|
||||
describe('SettingsPage appearance tab', () => {
|
||||
it('loads preferences and posts each changed preference on save', async () => {
|
||||
useSessionMock.mockReturnValue({ data: session, isPending: false });
|
||||
apiMock.mockImplementation((path: string) =>
|
||||
path.startsWith('/api/memory/preferences?')
|
||||
? Promise.resolve([{ key: 'ui.theme', value: 'dark', category: 'appearance' }])
|
||||
: Promise.resolve({}),
|
||||
);
|
||||
|
||||
await renderSettingsPage();
|
||||
await clickButtonByText('Appearance');
|
||||
|
||||
expect(apiMock).toHaveBeenCalledWith('/api/memory/preferences?category=appearance');
|
||||
|
||||
await clickButtonByText('Save changes');
|
||||
|
||||
expect(apiMock).toHaveBeenCalledWith('/api/memory/preferences', {
|
||||
method: 'POST',
|
||||
body: { key: 'ui.theme', value: 'dark', category: 'appearance', source: 'user' },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('SettingsPage providers tab', () => {
|
||||
it('loads LLM and SSO providers and runs a connection test', async () => {
|
||||
useSessionMock.mockReturnValue({ data: session, isPending: false });
|
||||
apiMock.mockImplementation((path: string, opts?: { method?: string }) => {
|
||||
if (path === '/api/providers' && opts === undefined) {
|
||||
return Promise.resolve([
|
||||
{
|
||||
id: 'ollama',
|
||||
name: 'Ollama',
|
||||
available: true,
|
||||
models: [
|
||||
{
|
||||
id: 'llama3.2',
|
||||
provider: 'ollama',
|
||||
name: 'Llama 3.2',
|
||||
reasoning: false,
|
||||
contextWindow: 128_000,
|
||||
maxTokens: 4096,
|
||||
inputTypes: ['text'],
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
}
|
||||
if (path === '/api/sso/providers') {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
if (path === '/api/providers/test') {
|
||||
return Promise.resolve({ providerId: 'ollama', reachable: true, latencyMs: 12 });
|
||||
}
|
||||
return Promise.resolve([]);
|
||||
});
|
||||
|
||||
await renderSettingsPage();
|
||||
await clickButtonByText('Providers');
|
||||
|
||||
expect(container.textContent).toContain('Ollama');
|
||||
expect(container.textContent).toContain('1 model');
|
||||
|
||||
await clickButtonByText('Test');
|
||||
|
||||
expect(apiMock).toHaveBeenCalledWith('/api/providers/test', {
|
||||
method: 'POST',
|
||||
body: { providerId: 'ollama' },
|
||||
});
|
||||
expect(container.textContent).toContain('Reachable');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,836 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { api } from '@/lib/api';
|
||||
import { authClient, useSession } from '@/lib/auth-client';
|
||||
import type { SsoProviderDiscovery } from '@/lib/sso';
|
||||
import { SsoProviderSection } from '@/components/settings/sso-provider-section';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface ModelInfo {
|
||||
id: string;
|
||||
provider: string;
|
||||
name: string;
|
||||
reasoning: boolean;
|
||||
contextWindow: number;
|
||||
maxTokens: number;
|
||||
inputTypes: ('text' | 'image')[];
|
||||
cost: { input: number; output: number; cacheRead: number; cacheWrite: number };
|
||||
}
|
||||
|
||||
interface ProviderInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
available: boolean;
|
||||
models: ModelInfo[];
|
||||
}
|
||||
|
||||
interface TestConnectionResult {
|
||||
providerId: string;
|
||||
reachable: boolean;
|
||||
latencyMs?: number;
|
||||
error?: string;
|
||||
discoveredModels?: string[];
|
||||
}
|
||||
|
||||
type TestState = 'idle' | 'testing' | 'success' | 'error';
|
||||
|
||||
interface ProviderTestStatus {
|
||||
state: TestState;
|
||||
result?: TestConnectionResult;
|
||||
}
|
||||
|
||||
interface Preference {
|
||||
key: string;
|
||||
value: unknown;
|
||||
category: string;
|
||||
}
|
||||
|
||||
type Theme = 'light' | 'dark' | 'system';
|
||||
type SaveState = 'idle' | 'saving' | 'saved' | 'error';
|
||||
type Tab = 'profile' | 'appearance' | 'notifications' | 'providers';
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function prefValue<T>(prefs: Preference[], key: string, fallback: T): T {
|
||||
const p = prefs.find((x) => x.key === key);
|
||||
if (p === undefined) return fallback;
|
||||
return p.value as T;
|
||||
}
|
||||
|
||||
// The reset must not outlive the tab: an uncleared setTimeout fires into a
|
||||
// torn-down environment (unmount, or jsdom teardown under vitest).
|
||||
function useSavedBadgeReset(saveState: SaveState, setSaveState: (s: SaveState) => void): void {
|
||||
useEffect(() => {
|
||||
if (saveState !== 'saved') return undefined;
|
||||
const timer = setTimeout(() => setSaveState('idle'), 2000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [saveState, setSaveState]);
|
||||
}
|
||||
|
||||
// ─── Main Page ────────────────────────────────────────────────────────────────
|
||||
|
||||
export function SettingsPage(): React.ReactElement {
|
||||
const { data: session } = useSession();
|
||||
const [activeTab, setActiveTab] = useState<Tab>('profile');
|
||||
|
||||
const tabs: { id: Tab; label: string }[] = [
|
||||
{ id: 'profile', label: 'Profile' },
|
||||
{ id: 'appearance', label: 'Appearance' },
|
||||
{ id: 'notifications', label: 'Notifications' },
|
||||
{ id: 'providers', label: 'Providers' },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl space-y-6">
|
||||
<h1 className="text-2xl font-semibold">Settings</h1>
|
||||
|
||||
{/* Tab bar */}
|
||||
<div className="flex gap-1 border-b border-surface-border">
|
||||
{tabs.map((tab) => (
|
||||
<button
|
||||
key={tab.id}
|
||||
type="button"
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
className={`px-4 py-2 text-sm font-medium transition-colors ${
|
||||
activeTab === tab.id
|
||||
? 'border-b-2 border-accent text-accent'
|
||||
: 'text-text-secondary hover:text-text-primary'
|
||||
}`}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{activeTab === 'profile' && <ProfileTab session={session} />}
|
||||
{activeTab === 'appearance' && <AppearanceTab />}
|
||||
{activeTab === 'notifications' && <NotificationsTab />}
|
||||
{activeTab === 'providers' && <ProvidersTab />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Profile Tab ──────────────────────────────────────────────────────────────
|
||||
|
||||
function ProfileTab({
|
||||
session,
|
||||
}: {
|
||||
session: { user: { id: string; name: string; email: string; image?: string | null } } | null;
|
||||
}): React.ReactElement {
|
||||
const [name, setName] = useState(session?.user.name ?? '');
|
||||
const [image, setImage] = useState(session?.user.image ?? '');
|
||||
const [saveState, setSaveState] = useState<SaveState>('idle');
|
||||
const [errorMsg, setErrorMsg] = useState('');
|
||||
useSavedBadgeReset(saveState, setSaveState);
|
||||
|
||||
// Sync from session when it loads
|
||||
useEffect(() => {
|
||||
if (session?.user) {
|
||||
setName(session.user.name ?? '');
|
||||
setImage(session.user.image ?? '');
|
||||
}
|
||||
}, [session]);
|
||||
|
||||
const handleSave = async (): Promise<void> => {
|
||||
setSaveState('saving');
|
||||
setErrorMsg('');
|
||||
try {
|
||||
const result = await authClient.updateUser({ name, image: image || null });
|
||||
if (result.error) {
|
||||
setErrorMsg(result.error.message ?? 'Failed to update profile');
|
||||
setSaveState('error');
|
||||
return;
|
||||
}
|
||||
setSaveState('saved');
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to update profile';
|
||||
setErrorMsg(message);
|
||||
setSaveState('error');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-lg font-medium text-text-secondary">Profile</h2>
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-6 space-y-4">
|
||||
<FormField label="Display Name" id="profile-name">
|
||||
<input
|
||||
id="profile-name"
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Your name"
|
||||
className="mt-1 block w-full rounded-lg border border-surface-border bg-surface-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none focus:ring-1 focus:ring-accent"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="Email" id="profile-email">
|
||||
<input
|
||||
id="profile-email"
|
||||
type="email"
|
||||
value={session?.user.email ?? ''}
|
||||
disabled
|
||||
className="mt-1 block w-full rounded-lg border border-surface-border bg-surface-elevated px-3 py-2 text-sm text-text-muted opacity-60 cursor-not-allowed"
|
||||
/>
|
||||
<p className="mt-1 text-xs text-text-muted">Email cannot be changed here.</p>
|
||||
</FormField>
|
||||
|
||||
<FormField label="Avatar URL" id="profile-image">
|
||||
<input
|
||||
id="profile-image"
|
||||
type="url"
|
||||
value={image}
|
||||
onChange={(e) => setImage(e.target.value)}
|
||||
placeholder="https://example.com/avatar.png"
|
||||
className="mt-1 block w-full rounded-lg border border-surface-border bg-surface-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none focus:ring-1 focus:ring-accent"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<div className="flex items-center gap-3 pt-2">
|
||||
<SaveButton state={saveState} onClick={handleSave} />
|
||||
{saveState === 'error' && errorMsg && <p className="text-sm text-error">{errorMsg}</p>}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Appearance Tab ───────────────────────────────────────────────────────────
|
||||
|
||||
function AppearanceTab(): React.ReactElement {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [theme, setTheme] = useState<Theme>('system');
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
|
||||
const [defaultModel, setDefaultModel] = useState('');
|
||||
const [saveState, setSaveState] = useState<SaveState>('idle');
|
||||
const [errorMsg, setErrorMsg] = useState('');
|
||||
useSavedBadgeReset(saveState, setSaveState);
|
||||
|
||||
useEffect(() => {
|
||||
api<Preference[]>('/api/memory/preferences?category=appearance')
|
||||
.catch(() => [] as Preference[])
|
||||
.then((p) => {
|
||||
setTheme(prefValue<Theme>(p, 'ui.theme', 'system'));
|
||||
setSidebarCollapsed(prefValue<boolean>(p, 'ui.sidebar_collapsed', false));
|
||||
setDefaultModel(prefValue<string>(p, 'ui.default_model', ''));
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const handleSave = async (): Promise<void> => {
|
||||
setSaveState('saving');
|
||||
setErrorMsg('');
|
||||
try {
|
||||
await Promise.all([
|
||||
api('/api/memory/preferences', {
|
||||
method: 'POST',
|
||||
body: { key: 'ui.theme', value: theme, category: 'appearance', source: 'user' },
|
||||
}),
|
||||
api('/api/memory/preferences', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
key: 'ui.sidebar_collapsed',
|
||||
value: sidebarCollapsed,
|
||||
category: 'appearance',
|
||||
source: 'user',
|
||||
},
|
||||
}),
|
||||
...(defaultModel
|
||||
? [
|
||||
api('/api/memory/preferences', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
key: 'ui.default_model',
|
||||
value: defaultModel,
|
||||
category: 'appearance',
|
||||
source: 'user',
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
]);
|
||||
setSaveState('saved');
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to save preferences';
|
||||
setErrorMsg(message);
|
||||
setSaveState('error');
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<section>
|
||||
<h2 className="mb-4 text-lg font-medium text-text-secondary">Appearance</h2>
|
||||
<p className="text-sm text-text-muted">Loading preferences...</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-lg font-medium text-text-secondary">Appearance</h2>
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-6 space-y-6">
|
||||
{/* Theme */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-primary mb-2">Theme</label>
|
||||
<div className="flex gap-3">
|
||||
{(['system', 'light', 'dark'] as Theme[]).map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
type="button"
|
||||
onClick={() => setTheme(t)}
|
||||
className={`rounded-lg border px-4 py-2 text-sm capitalize transition-colors ${
|
||||
theme === t
|
||||
? 'border-accent bg-accent/10 text-accent'
|
||||
: 'border-surface-border bg-surface-elevated text-text-secondary hover:border-accent/50'
|
||||
}`}
|
||||
>
|
||||
{t}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Sidebar collapsed default */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-text-primary">Collapse sidebar by default</p>
|
||||
<p className="text-xs text-text-muted">Start with sidebar collapsed on page load</p>
|
||||
</div>
|
||||
<Toggle checked={sidebarCollapsed} onChange={setSidebarCollapsed} />
|
||||
</div>
|
||||
|
||||
{/* Default model */}
|
||||
<FormField label="Default Model" id="default-model">
|
||||
<input
|
||||
id="default-model"
|
||||
type="text"
|
||||
value={defaultModel}
|
||||
onChange={(e) => setDefaultModel(e.target.value)}
|
||||
placeholder="e.g. ollama/llama3.2"
|
||||
className="mt-1 block w-full rounded-lg border border-surface-border bg-surface-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none focus:ring-1 focus:ring-accent"
|
||||
/>
|
||||
<p className="mt-1 text-xs text-text-muted">
|
||||
Model ID to pre-select for new conversations.
|
||||
</p>
|
||||
</FormField>
|
||||
|
||||
<div className="flex items-center gap-3 pt-2">
|
||||
<SaveButton state={saveState} onClick={handleSave} />
|
||||
{saveState === 'error' && errorMsg && <p className="text-sm text-error">{errorMsg}</p>}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Notifications Tab ────────────────────────────────────────────────────────
|
||||
|
||||
function NotificationsTab(): React.ReactElement {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [emailAgentComplete, setEmailAgentComplete] = useState(false);
|
||||
const [emailMentions, setEmailMentions] = useState(true);
|
||||
const [emailDigest, setEmailDigest] = useState(false);
|
||||
const [saveState, setSaveState] = useState<SaveState>('idle');
|
||||
const [errorMsg, setErrorMsg] = useState('');
|
||||
useSavedBadgeReset(saveState, setSaveState);
|
||||
|
||||
useEffect(() => {
|
||||
api<Preference[]>('/api/memory/preferences?category=communication')
|
||||
.catch(() => [] as Preference[])
|
||||
.then((p) => {
|
||||
setEmailAgentComplete(prefValue<boolean>(p, 'notify.email_agent_complete', false));
|
||||
setEmailMentions(prefValue<boolean>(p, 'notify.email_mentions', true));
|
||||
setEmailDigest(prefValue<boolean>(p, 'notify.email_digest', false));
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const handleSave = async (): Promise<void> => {
|
||||
setSaveState('saving');
|
||||
setErrorMsg('');
|
||||
try {
|
||||
await Promise.all([
|
||||
api('/api/memory/preferences', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
key: 'notify.email_agent_complete',
|
||||
value: emailAgentComplete,
|
||||
category: 'communication',
|
||||
source: 'user',
|
||||
},
|
||||
}),
|
||||
api('/api/memory/preferences', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
key: 'notify.email_mentions',
|
||||
value: emailMentions,
|
||||
category: 'communication',
|
||||
source: 'user',
|
||||
},
|
||||
}),
|
||||
api('/api/memory/preferences', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
key: 'notify.email_digest',
|
||||
value: emailDigest,
|
||||
category: 'communication',
|
||||
source: 'user',
|
||||
},
|
||||
}),
|
||||
]);
|
||||
setSaveState('saved');
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to save preferences';
|
||||
setErrorMsg(message);
|
||||
setSaveState('error');
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<section>
|
||||
<h2 className="mb-4 text-lg font-medium text-text-secondary">Notifications</h2>
|
||||
<p className="text-sm text-text-muted">Loading preferences...</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-lg font-medium text-text-secondary">Notifications</h2>
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-6 space-y-6">
|
||||
<p className="text-xs text-text-muted">Configure when you receive email notifications.</p>
|
||||
|
||||
<NotifyRow
|
||||
label="Agent task completed"
|
||||
description="Email when an agent finishes a task"
|
||||
checked={emailAgentComplete}
|
||||
onChange={setEmailAgentComplete}
|
||||
/>
|
||||
<NotifyRow
|
||||
label="Mentions"
|
||||
description="Email when you are mentioned in a conversation"
|
||||
checked={emailMentions}
|
||||
onChange={setEmailMentions}
|
||||
/>
|
||||
<NotifyRow
|
||||
label="Weekly digest"
|
||||
description="Weekly summary of activity"
|
||||
checked={emailDigest}
|
||||
onChange={setEmailDigest}
|
||||
/>
|
||||
|
||||
<div className="flex items-center gap-3 pt-2">
|
||||
<SaveButton state={saveState} onClick={handleSave} />
|
||||
{saveState === 'error' && errorMsg && <p className="text-sm text-error">{errorMsg}</p>}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Providers Tab ────────────────────────────────────────────────────────────
|
||||
|
||||
function ProvidersTab(): React.ReactElement {
|
||||
const [providers, setProviders] = useState<ProviderInfo[]>([]);
|
||||
const [ssoProviders, setSsoProviders] = useState<SsoProviderDiscovery[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [ssoLoading, setSsoLoading] = useState(true);
|
||||
const [testStatuses, setTestStatuses] = useState<Record<string, ProviderTestStatus>>({});
|
||||
|
||||
useEffect(() => {
|
||||
api<ProviderInfo[]>('/api/providers')
|
||||
.catch(() => [] as ProviderInfo[])
|
||||
.then((p) => setProviders(p))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
api<SsoProviderDiscovery[]>('/api/sso/providers')
|
||||
.catch(() => [] as SsoProviderDiscovery[])
|
||||
.then((providers) => setSsoProviders(providers))
|
||||
.finally(() => setSsoLoading(false));
|
||||
}, []);
|
||||
|
||||
const testConnection = useCallback(async (providerId: string): Promise<void> => {
|
||||
setTestStatuses((prev) => ({
|
||||
...prev,
|
||||
[providerId]: { state: 'testing' },
|
||||
}));
|
||||
try {
|
||||
const result = await api<TestConnectionResult>('/api/providers/test', {
|
||||
method: 'POST',
|
||||
body: { providerId },
|
||||
});
|
||||
setTestStatuses((prev) => ({
|
||||
...prev,
|
||||
[providerId]: { state: result.reachable ? 'success' : 'error', result },
|
||||
}));
|
||||
} catch {
|
||||
setTestStatuses((prev) => ({
|
||||
...prev,
|
||||
[providerId]: {
|
||||
state: 'error',
|
||||
result: { providerId, reachable: false, error: 'Request failed' },
|
||||
},
|
||||
}));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const defaultModel: ModelInfo | undefined = providers
|
||||
.flatMap((p) => p.models)
|
||||
.find((m) => providers.find((p) => p.id === m.provider)?.available);
|
||||
|
||||
return (
|
||||
<section className="space-y-6">
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-lg font-medium text-text-secondary">SSO Providers</h2>
|
||||
<SsoProviderSection providers={ssoProviders} loading={ssoLoading} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-lg font-medium text-text-secondary">LLM Providers</h2>
|
||||
{loading ? (
|
||||
<p className="text-sm text-text-muted">Loading providers...</p>
|
||||
) : providers.length === 0 ? (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-4">
|
||||
<p className="text-sm text-text-muted">
|
||||
No providers configured. Set{' '}
|
||||
<code className="rounded bg-surface-elevated px-1 py-0.5 text-xs">
|
||||
OLLAMA_BASE_URL
|
||||
</code>{' '}
|
||||
or{' '}
|
||||
<code className="rounded bg-surface-elevated px-1 py-0.5 text-xs">
|
||||
MOSAIC_CUSTOM_PROVIDERS
|
||||
</code>{' '}
|
||||
to add providers.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{providers.map((provider) => (
|
||||
<ProviderCard
|
||||
key={provider.id}
|
||||
provider={provider}
|
||||
defaultModel={defaultModel}
|
||||
testStatus={testStatuses[provider.id] ?? { state: 'idle' }}
|
||||
onTest={() => void testConnection(provider.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Shared UI Components ─────────────────────────────────────────────────────
|
||||
|
||||
function FormField({
|
||||
label,
|
||||
id,
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
id: string;
|
||||
children: React.ReactNode;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<div>
|
||||
<label htmlFor={id} className="block text-sm font-medium text-text-primary">
|
||||
{label}
|
||||
</label>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Toggle({
|
||||
checked,
|
||||
onChange,
|
||||
}: {
|
||||
checked: boolean;
|
||||
onChange: (v: boolean) => void;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={checked}
|
||||
onClick={() => onChange(!checked)}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-accent focus:ring-offset-2 focus:ring-offset-surface-card ${
|
||||
checked ? 'bg-accent' : 'bg-surface-border'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
|
||||
checked ? 'translate-x-6' : 'translate-x-1'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function NotifyRow({
|
||||
label,
|
||||
description,
|
||||
checked,
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
description: string;
|
||||
checked: boolean;
|
||||
onChange: (v: boolean) => void;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-text-primary">{label}</p>
|
||||
<p className="text-xs text-text-muted">{description}</p>
|
||||
</div>
|
||||
<Toggle checked={checked} onChange={onChange} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SaveButton({
|
||||
state,
|
||||
onClick,
|
||||
}: {
|
||||
state: SaveState;
|
||||
onClick: () => void;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={state === 'saving'}
|
||||
className="rounded-lg bg-accent px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-accent/90 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{state === 'saving' ? 'Saving...' : state === 'saved' ? 'Saved!' : 'Save changes'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Provider Card (from original page) ──────────────────────────────────────
|
||||
|
||||
interface ProviderCardProps {
|
||||
provider: ProviderInfo;
|
||||
defaultModel: ModelInfo | undefined;
|
||||
testStatus: ProviderTestStatus;
|
||||
onTest: () => void;
|
||||
}
|
||||
|
||||
function ProviderCard({
|
||||
provider,
|
||||
defaultModel,
|
||||
testStatus,
|
||||
onTest,
|
||||
}: ProviderCardProps): React.ReactElement {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card">
|
||||
{/* Header row */}
|
||||
<div className="flex items-center justify-between px-4 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<ProviderAvatar id={provider.id} />
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-text-primary">{provider.name}</span>
|
||||
<ProviderStatusBadge available={provider.available} />
|
||||
</div>
|
||||
<p className="text-xs text-text-muted">
|
||||
{provider.models.length} model{provider.models.length !== 1 ? 's' : ''}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<TestConnectionButton status={testStatus} onTest={onTest} />
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpanded((v) => !v)}
|
||||
className="rounded px-2 py-1 text-xs text-text-muted transition-colors hover:bg-surface-elevated hover:text-text-primary"
|
||||
aria-expanded={expanded}
|
||||
aria-label={expanded ? 'Collapse models' : 'Expand models'}
|
||||
>
|
||||
{expanded ? '▲ Hide' : '▼ Models'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Test result banner */}
|
||||
{testStatus.state !== 'idle' && testStatus.state !== 'testing' && testStatus.result && (
|
||||
<TestResultBanner result={testStatus.result} />
|
||||
)}
|
||||
|
||||
{/* Model list */}
|
||||
{expanded && (
|
||||
<div className="border-t border-surface-border">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr className="bg-surface-elevated text-left text-xs text-text-muted">
|
||||
<th className="px-4 py-2 font-medium">Model</th>
|
||||
<th className="hidden px-4 py-2 font-medium md:table-cell">Capabilities</th>
|
||||
<th className="hidden px-4 py-2 font-medium md:table-cell">Context</th>
|
||||
<th className="hidden px-4 py-2 font-medium md:table-cell">Cost (in/out)</th>
|
||||
<th className="px-4 py-2 font-medium">Default</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{provider.models.map((model) => (
|
||||
<ModelRow
|
||||
key={model.id}
|
||||
model={model}
|
||||
isDefault={
|
||||
defaultModel?.id === model.id && defaultModel?.provider === model.provider
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ModelRowProps {
|
||||
model: ModelInfo;
|
||||
isDefault: boolean;
|
||||
}
|
||||
|
||||
function ModelRow({ model, isDefault }: ModelRowProps): React.ReactElement {
|
||||
return (
|
||||
<tr className="border-t border-surface-border">
|
||||
<td className="px-4 py-2">
|
||||
<span className="text-sm text-text-primary">{model.name}</span>
|
||||
</td>
|
||||
<td className="hidden px-4 py-2 md:table-cell">
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<CapabilityBadge label="chat" />
|
||||
{model.reasoning && <CapabilityBadge label="reasoning" color="purple" />}
|
||||
{model.inputTypes.includes('image') && <CapabilityBadge label="vision" color="blue" />}
|
||||
</div>
|
||||
</td>
|
||||
<td className="hidden px-4 py-2 text-xs text-text-muted md:table-cell">
|
||||
{formatContext(model.contextWindow)}
|
||||
</td>
|
||||
<td className="hidden px-4 py-2 text-xs text-text-muted md:table-cell">
|
||||
{model.cost.input === 0 && model.cost.output === 0
|
||||
? 'free'
|
||||
: `$${model.cost.input} / $${model.cost.output}`}
|
||||
</td>
|
||||
<td className="px-4 py-2 text-center">
|
||||
{isDefault && (
|
||||
<span
|
||||
className="inline-block rounded-full bg-accent/20 px-2 py-0.5 text-xs font-medium text-accent"
|
||||
title="Default model used for new sessions"
|
||||
>
|
||||
default
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
function ProviderAvatar({ id }: { id: string }): React.ReactElement {
|
||||
const letter = id.charAt(0).toUpperCase();
|
||||
return (
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-surface-elevated text-sm font-semibold text-text-secondary">
|
||||
{letter}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProviderStatusBadge({ available }: { available: boolean }): React.ReactElement {
|
||||
return (
|
||||
<span
|
||||
className={`rounded-full px-2 py-0.5 text-xs font-medium ${
|
||||
available ? 'bg-success/20 text-success' : 'bg-surface-elevated text-text-muted'
|
||||
}`}
|
||||
>
|
||||
{available ? 'Active' : 'Inactive'}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
interface TestConnectionButtonProps {
|
||||
status: ProviderTestStatus;
|
||||
onTest: () => void;
|
||||
}
|
||||
|
||||
function TestConnectionButton({ status, onTest }: TestConnectionButtonProps): React.ReactElement {
|
||||
const isTesting = status.state === 'testing';
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onTest}
|
||||
disabled={isTesting}
|
||||
className="rounded px-2 py-1 text-xs transition-colors hover:bg-surface-elevated disabled:cursor-not-allowed disabled:opacity-50"
|
||||
title="Test connection"
|
||||
>
|
||||
{isTesting ? (
|
||||
<span className="text-text-muted">Testing…</span>
|
||||
) : status.state === 'success' ? (
|
||||
<span className="text-success">✓ Reachable</span>
|
||||
) : status.state === 'error' ? (
|
||||
<span className="text-error">✗ Unreachable</span>
|
||||
) : (
|
||||
<span className="text-text-muted">Test</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function TestResultBanner({ result }: { result: TestConnectionResult }): React.ReactElement {
|
||||
return (
|
||||
<div
|
||||
className={`px-4 py-2 text-xs ${
|
||||
result.reachable ? 'bg-success/10 text-success' : 'bg-error/10 text-error'
|
||||
}`}
|
||||
>
|
||||
{result.reachable ? (
|
||||
<>
|
||||
Connected
|
||||
{result.latencyMs !== undefined && (
|
||||
<span className="ml-1 opacity-70">({result.latencyMs}ms)</span>
|
||||
)}
|
||||
{result.discoveredModels && result.discoveredModels.length > 0 && (
|
||||
<span className="ml-2 opacity-70">
|
||||
— {result.discoveredModels.length} model
|
||||
{result.discoveredModels.length !== 1 ? 's' : ''} discovered
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>Connection failed{result.error ? `: ${result.error}` : ''}</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CapabilityBadge({
|
||||
label,
|
||||
color = 'default',
|
||||
}: {
|
||||
label: string;
|
||||
color?: 'default' | 'purple' | 'blue';
|
||||
}): React.ReactElement {
|
||||
const colorClass =
|
||||
color === 'purple'
|
||||
? 'bg-purple-500/20 text-purple-400'
|
||||
: color === 'blue'
|
||||
? 'bg-blue-500/20 text-blue-400'
|
||||
: 'bg-surface-elevated text-text-muted';
|
||||
return <span className={`rounded px-1.5 py-0.5 text-xs ${colorClass}`}>{label}</span>;
|
||||
}
|
||||
|
||||
function formatContext(tokens: number): string {
|
||||
if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;
|
||||
if (tokens >= 1_000) return `${Math.round(tokens / 1_000)}k`;
|
||||
return String(tokens);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { createMemoryRouter, RouterProvider } from 'react-router-dom';
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { apiMock, oauth2Mock } = vi.hoisted(() => ({
|
||||
apiMock: vi.fn(),
|
||||
oauth2Mock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
api: apiMock,
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/auth-client', () => ({
|
||||
signIn: { oauth2: oauth2Mock },
|
||||
}));
|
||||
|
||||
import { SsoCallbackPage } from './sso-callback';
|
||||
|
||||
const mountedRoots: Root[] = [];
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
apiMock.mockResolvedValue([
|
||||
{
|
||||
id: 'authentik',
|
||||
name: 'Authentik',
|
||||
protocols: ['oidc'],
|
||||
configured: true,
|
||||
loginMode: 'oidc',
|
||||
callbackPath: '/api/auth/oauth2/callback/authentik',
|
||||
teamSync: { enabled: false, claim: null },
|
||||
samlFallback: { configured: false, loginUrl: null },
|
||||
warnings: [],
|
||||
},
|
||||
]);
|
||||
oauth2Mock.mockResolvedValue({ data: null, error: null });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
for (const root of mountedRoots.splice(0)) {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
}
|
||||
document.body.replaceChildren();
|
||||
apiMock.mockReset();
|
||||
oauth2Mock.mockReset();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
});
|
||||
|
||||
describe('SsoCallbackPage', () => {
|
||||
it('rejects a control-character callback that normalizes to an external origin', async () => {
|
||||
const router = createMemoryRouter(
|
||||
[
|
||||
{
|
||||
path: '/auth/provider/:provider',
|
||||
element: <SsoCallbackPage />,
|
||||
},
|
||||
],
|
||||
{
|
||||
initialEntries: ['/auth/provider/authentik?callbackURL=%2F%0A%2F%2Fevil.example'],
|
||||
},
|
||||
);
|
||||
const container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
const root = createRoot(container);
|
||||
mountedRoots.push(root);
|
||||
|
||||
await act(async () => {
|
||||
root.render(<RouterProvider router={router} />);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
});
|
||||
|
||||
expect(oauth2Mock).toHaveBeenCalledWith({
|
||||
providerId: 'authentik',
|
||||
callbackURL: '/chat',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useEffect, useState, type ReactElement } from 'react';
|
||||
import { Link, useParams, useSearchParams } from 'react-router-dom';
|
||||
import { api } from '@/lib/api';
|
||||
import { resolveAuthCallbackURL } from '@/lib/auth-redirect';
|
||||
import { signIn } from '@/lib/auth-client';
|
||||
import type { SsoProviderDiscovery } from '@/lib/sso';
|
||||
|
||||
export function SsoCallbackPage(): ReactElement {
|
||||
const { provider: providerId = '' } = useParams<'provider'>();
|
||||
const [searchParams] = useSearchParams();
|
||||
const requestedCallbackURL = searchParams.get('callbackURL');
|
||||
const [providerName, setProviderName] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
async function redirectToProvider(): Promise<void> {
|
||||
try {
|
||||
const callbackURL = resolveAuthCallbackURL(requestedCallbackURL, window.location.origin);
|
||||
const providers = await api<SsoProviderDiscovery[]>('/api/sso/providers');
|
||||
if (cancelled) return;
|
||||
|
||||
const provider = providers.find((candidate) => candidate.id === providerId);
|
||||
if (!provider) {
|
||||
setError('Unknown SSO provider.');
|
||||
return;
|
||||
}
|
||||
|
||||
setProviderName(provider.name);
|
||||
if (!provider.configured) {
|
||||
setError(`${provider.name} is not enabled in this deployment.`);
|
||||
return;
|
||||
}
|
||||
if (provider.loginMode !== 'oidc') {
|
||||
setError(`${provider.name} is not available for OIDC sign in.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await signIn.oauth2({
|
||||
providerId: provider.id,
|
||||
callbackURL,
|
||||
});
|
||||
|
||||
if (!cancelled && result?.error) {
|
||||
setError(result.error.message ?? `${provider.name} sign in failed.`);
|
||||
}
|
||||
} catch (caught: unknown) {
|
||||
if (!cancelled) {
|
||||
setError(caught instanceof Error ? caught.message : 'Unable to start single sign-on.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void redirectToProvider();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [providerId, requestedCallbackURL]);
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex min-h-[50vh] max-w-md flex-col justify-center">
|
||||
<h1 className="text-2xl font-semibold text-text-primary">Single sign-on</h1>
|
||||
<p className="mt-2 text-sm text-text-secondary">
|
||||
{providerName
|
||||
? `Redirecting you to ${providerName}...`
|
||||
: 'Preparing your sign-in request...'}
|
||||
</p>
|
||||
|
||||
{error ? (
|
||||
<div
|
||||
role="alert"
|
||||
className="mt-6 rounded-lg border border-error/30 bg-error/10 px-4 py-3 text-sm text-error"
|
||||
>
|
||||
<p>{error}</p>
|
||||
<Link
|
||||
to="/login"
|
||||
className="mt-3 inline-block font-medium text-blue-400 hover:text-blue-300"
|
||||
>
|
||||
Return to login
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<div className="mt-6 rounded-lg border border-surface-border bg-surface-elevated px-4 py-3 text-sm text-text-secondary">
|
||||
If the redirect does not start automatically, return to the login page and try again.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { createMemoryRouter, RouterProvider, type RouteObject } from 'react-router-dom';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { taskFixtures } from './page-fixtures';
|
||||
import { acceptSnapshot, DEFAULT_FRESHNESS_POLICY } from '@/lib/freshness/model';
|
||||
import { writeSnapshotCache } from '@/lib/freshness/snapshot-cache';
|
||||
import { validateTaskCollection } from '@/lib/freshness/validators';
|
||||
|
||||
const { apiMock } = vi.hoisted(() => ({
|
||||
apiMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
api: apiMock,
|
||||
}));
|
||||
|
||||
import { TasksPage } from './tasks';
|
||||
|
||||
interface Deferred<T> {
|
||||
promise: Promise<T>;
|
||||
resolve: (value: T) => void;
|
||||
}
|
||||
|
||||
function createDeferred<T>(): Deferred<T> {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((res) => {
|
||||
resolve = res;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
document.body.replaceChildren();
|
||||
root = null;
|
||||
apiMock.mockReset();
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
async function renderTasksPage(): Promise<void> {
|
||||
const routes: RouteObject[] = [{ path: '/tasks', element: <TasksPage /> }];
|
||||
const router = createMemoryRouter(routes, { initialEntries: ['/tasks'] });
|
||||
container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root?.render(<RouterProvider router={router} />);
|
||||
});
|
||||
}
|
||||
|
||||
function clickButtonByText(text: string): void {
|
||||
const button = [...container.querySelectorAll('button')].find((candidate) =>
|
||||
candidate.textContent?.includes(text),
|
||||
);
|
||||
if (!button) {
|
||||
throw new Error(`Button containing "${text}" not found`);
|
||||
}
|
||||
button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
}
|
||||
|
||||
/** Flush pending promise callbacks inside the act environment. */
|
||||
async function flushAct(): Promise<void> {
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
|
||||
describe('TasksPage', () => {
|
||||
it('shows a visible loading state before the tasks request settles', async () => {
|
||||
const deferred = createDeferred<typeof taskFixtures>();
|
||||
apiMock.mockReturnValueOnce(deferred.promise);
|
||||
|
||||
await renderTasksPage();
|
||||
|
||||
expect(container.textContent).toContain('Loading tasks...');
|
||||
|
||||
await act(async () => {
|
||||
deferred.resolve(taskFixtures);
|
||||
await deferred.promise;
|
||||
});
|
||||
});
|
||||
|
||||
it('starts in kanban view, toggles to list view, and opens the read-only modal from cards and rows', async () => {
|
||||
apiMock.mockResolvedValueOnce(taskFixtures);
|
||||
|
||||
await renderTasksPage();
|
||||
|
||||
expect(container.textContent).toContain('Not Started');
|
||||
expect(container.textContent).toContain('In Progress');
|
||||
expect(container.textContent).toContain('Blocked');
|
||||
|
||||
const kanbanCard = [...container.querySelectorAll('button')].find((candidate) =>
|
||||
candidate.textContent?.includes('Route /projects/:id'),
|
||||
);
|
||||
expect(kanbanCard).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
kanbanCard?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(container.querySelector('[role="dialog"]')).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
container
|
||||
.querySelector('button[aria-label="Close task details"]')
|
||||
?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(container.querySelector('[role="dialog"]')).toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('List');
|
||||
});
|
||||
|
||||
const row = [...container.querySelectorAll('tr')].find((candidate) =>
|
||||
candidate.textContent?.includes('Route /tasks'),
|
||||
);
|
||||
expect(row).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
row?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(container.querySelector('[role="dialog"]')).toBeTruthy();
|
||||
expect(container.textContent).toContain('Wire list and kanban modal interactions');
|
||||
});
|
||||
|
||||
it('renders a failed fetch as an explicit unavailable state, never an empty healthy board', async () => {
|
||||
apiMock.mockRejectedValueOnce(new Error('Tasks request failed'));
|
||||
|
||||
await renderTasksPage();
|
||||
|
||||
const alert = container.querySelector('[role="alert"]');
|
||||
expect(alert).toBeTruthy();
|
||||
expect(alert?.textContent).toContain('Tasks request failed');
|
||||
expect(alert?.textContent).toContain('not an empty result');
|
||||
|
||||
// Negative controls: no board, no healthy empty-state markers, and the
|
||||
// surface is marked unavailable rather than current.
|
||||
expect(container.textContent).not.toContain('Not Started');
|
||||
expect(container.textContent).not.toContain('No tasks');
|
||||
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||
'unavailable',
|
||||
);
|
||||
});
|
||||
|
||||
it('recovers to a current board after retrying a failed fetch', async () => {
|
||||
apiMock
|
||||
.mockRejectedValueOnce(new Error('Tasks request failed'))
|
||||
.mockResolvedValueOnce(taskFixtures);
|
||||
|
||||
await renderTasksPage();
|
||||
expect(container.querySelector('[role="alert"]')).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Retry');
|
||||
});
|
||||
await flushAct();
|
||||
|
||||
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||||
expect(container.textContent).toContain('Not Started');
|
||||
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||
'current',
|
||||
);
|
||||
});
|
||||
|
||||
it('labels restored last-known data as stale with source, version, and age until verified', async () => {
|
||||
// Seed a last-known snapshot fetched five minutes ago; the page must
|
||||
// render it only under an explicit staleness label while the fetch is
|
||||
// still in flight.
|
||||
const restored = acceptSnapshot({
|
||||
value: taskFixtures,
|
||||
validate: validateTaskCollection,
|
||||
previous: null,
|
||||
policy: DEFAULT_FRESHNESS_POLICY,
|
||||
source: 'gateway:/api/tasks',
|
||||
now: Date.now() - 5 * 60_000,
|
||||
});
|
||||
if (restored.outcome !== 'accepted') throw new Error('fixture setup failed');
|
||||
writeSnapshotCache('tasks', restored.snapshot);
|
||||
|
||||
const deferred = createDeferred<typeof taskFixtures>();
|
||||
apiMock.mockReturnValueOnce(deferred.promise);
|
||||
|
||||
await renderTasksPage();
|
||||
|
||||
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||
'stale',
|
||||
);
|
||||
const banner = container.querySelector('[role="status"]');
|
||||
expect(banner?.textContent).toContain('last-known');
|
||||
expect(banner?.textContent).toContain('may be out of date');
|
||||
expect(banner?.textContent).toContain('gateway:/api/tasks');
|
||||
expect(banner?.textContent).toContain('snapshot v1');
|
||||
expect(banner?.textContent).toContain('5m ago');
|
||||
|
||||
// Last-known data still renders as situational awareness under the label.
|
||||
expect(container.textContent).toContain('Route /tasks');
|
||||
expect(container.textContent).not.toContain('Loading tasks...');
|
||||
|
||||
// Verification lands: the banner clears and the surface becomes current.
|
||||
await act(async () => {
|
||||
deferred.resolve(taskFixtures);
|
||||
await deferred.promise;
|
||||
});
|
||||
|
||||
expect(container.querySelector('[role="status"]')).toBeNull();
|
||||
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||
'current',
|
||||
);
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user