Spaces:
Running
Running
Deploy WorkPilot demo (part 3)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- web/README.mdAdded+52
- web/playwright.config.tsAdded+50
- web/playwright.staging.config.tsAdded+19
- web/src/app/(app)/analytics/page.tsxAdded+9
- web/src/app/(app)/chat/page.tsxAdded+9
- web/src/app/(app)/cod/page.tsxAdded+9
- web/src/app/(app)/inbox/page.tsxAdded+9
- web/src/app/(app)/integrations/page.tsxAdded+9
- web/src/app/(app)/knowledge/page.tsxAdded+9
- web/src/app/(app)/layout.tsxAdded+13
- web/src/app/(app)/memory/page.tsxAdded+9
- web/src/app/(app)/orders/[number]/page.tsxAdded+10
- web/src/app/(app)/orders/page.tsxAdded+9
- web/src/app/(app)/rules/page.tsxAdded+9
- web/src/app/(app)/runs/[id]/page.tsxAdded+10
- web/src/app/(app)/runs/page.tsxAdded+9
- web/src/app/(app)/settings/page.tsxAdded+9
- web/src/app/(app)/workflows/[id]/page.tsxAdded+10
- web/src/app/(app)/workflows/page.tsxAdded+9
- web/src/app/(auth)/login/page.tsxAdded+14
- web/src/app/(auth)/signup/page.tsxAdded+14
- web/src/app/api/session/[action]/route.tsAdded+77
- web/src/app/favicon.icoAdded
- web/src/app/globals.cssAdded+180
- web/src/app/layout.tsxAdded+47
- web/src/app/page.tsxAdded+5
- web/src/components/analytics/analytics-view.tsxAdded+156
- web/src/components/analytics/operations-health.test.tsxAdded+144
- web/src/components/analytics/operations-health.tsxAdded+225
- web/src/components/chat/chat-view.tsxAdded+174
- web/src/components/chat/gen-ui.tsxAdded+194
- web/src/components/commerce/cod-view.tsxAdded+81
- web/src/components/commerce/order-detail.tsxAdded+129
- web/src/components/commerce/orders-view.tsxAdded+191
- web/src/components/commerce/risk-badge.tsxAdded+32
- web/src/components/ext/integrations-view.tsxAdded+564
- web/src/components/ext/rules-view.tsxAdded+239
- web/src/components/ext/types.tsAdded+92
- web/src/components/inbox/approval-card.tsxAdded+329
- web/src/components/inbox/diff-view.tsxAdded+198
- web/src/components/inbox/edit-args-form.tsxAdded+226
- web/src/components/inbox/inbox-view.tsxAdded+227
- web/src/components/inbox/inbox.test.tsxAdded+247
- web/src/components/inbox/provenance-badge.tsxAdded+53
- web/src/components/inbox/stepup.tsxAdded+195
- web/src/components/inbox/undo-countdown.tsxAdded+77
- web/src/components/knowledge/knowledge-view.tsxAdded+247
- web/src/components/knowledge/knowledge.test.tsxAdded+115
- web/src/components/knowledge/memory-view.tsxAdded+170
- web/src/components/knowledge/types.tsAdded+49
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152# WorkPilot web dashboard
Next.js 16 (App Router, TypeScript strict), Tailwind CSS 4, shadcn/ui (Radix), light/dark themes,
English and Urdu (Nastaliq, right-to-left).
| Screen | What it does |
|---|---|
| `/inbox` | Agent Inbox: pending approvals with wait time, a structured before → after diff, exact arguments with a provenance badge per value, live facts from the system of record, policy rule, required role and step-up; approve, edit (form from the tool's argument schema; the tool is fixed), reject, respond; bulk approve with per-item exclusion; undo countdown for queued sends (`send_after`, Phase 7) |
| `/runs`, `/runs/[id]` | Runs list and a live run timeline over SSE (trigger, plan, every gateway decision, outcome) |
| `/chat` | Natural-language requests; results render as generative components (order table, risk card, status card) picked from `actions[].tool` / `data` |
| `/orders`, `/cod` | Orders and COD views against the e-commerce pack (`/packs/ecommerce/*`); an empty state until it is installed |
| `/analytics` | Auto-resolution rate, approval rate and latency, gateway decisions, denial reasons, cost |
| `/settings` | Policy thresholds and approval rules (owner), kill switches, team and roles |
## Run
```bash
# API (repo root): see the main README quick start, then
python -m core.serve # http://127.0.0.1:8000, CORS allows :3000 by default
cd web
npm install
npm run dev # http://localhost:3000
```
`NEXT_PUBLIC_API_URL` (browser → API, default `http://127.0.0.1:8000`) and `WP_API_URL`
(Next.js server → API for the session routes, defaults to the same) configure the API address.
Set `WP_CORS_ORIGINS` on the API to the web origin in other environments.
## Auth tokens
- **Access token** (15 min): memory only (`src/lib/session.ts`), sent as `Authorization: Bearer`.
- **Refresh token** (14 days): an `httpOnly`, `SameSite=Strict` cookie scoped to `/api/session`,
set by a small Next.js route handler (`src/app/api/session/[action]/route.ts`) that proxies
login, signup, refresh, logout and tenant switch. Browser JavaScript never reads it; a reload
silently exchanges it for a new access token. Session calls also require an
`X-Requested-With` header (CSRF).
- **Step-up token** (5 min, from `POST /auth/stepup` with a TOTP code): memory only, sent as
`X-Stepup-Token` on approvals that need it.
Trade-off: an XSS can still *use* the session while the tab is open, but cannot steal the
long-lived token; and the app needs a Node runtime for the session routes (no static export).
## Checks
```bash
npm run lint && npm run typecheck && npm test && npm run build
npm run e2e # Playwright: boots tests/e2e/server.py (real API, fresh embedded Postgres,
# demo pack, scripted LLM) and a production build on :3100
```
On Windows the e2e config uses `../.venv/Scripts/python.exe`; set `WP_PYTHON` to override.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950import path from "node:path";
import { defineConfig, devices } from "@playwright/test";
// End-to-end tests against a REAL API (tests/e2e/server.py: fresh embedded Postgres, demo pack,
// scripted LLM) and a production build of the web app pointed at it.
const API_PORT = Number(process.env.E2E_API_PORT ?? 8765);
const WEB_PORT = Number(process.env.E2E_WEB_PORT ?? 3100);
const API = `http://127.0.0.1:${API_PORT}`;
const WEB = `http://127.0.0.1:${WEB_PORT}`;
const PYTHON =
process.env.WP_PYTHON ??
path.resolve(
__dirname,
process.platform === "win32" ? "../.venv/Scripts/python.exe" : "../.venv/bin/python",
);
const SERVER = path.resolve(__dirname, "../tests/e2e/server.py");
export default defineConfig({
testDir: "./e2e",
timeout: 60_000,
expect: { timeout: 15_000 },
fullyParallel: false,
workers: 1,
retries: process.env.CI ? 1 : 0,
reporter: process.env.CI ? [["list"], ["html", { open: "never" }]] : "list",
use: {
baseURL: WEB,
trace: "retain-on-failure",
...devices["Desktop Chrome"],
},
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
webServer: [
{
command: `"${PYTHON}" "${SERVER}" --port ${API_PORT} --web-origin ${WEB}`,
url: `${API}/healthz`,
timeout: 180_000,
reuseExistingServer: false,
stdout: "pipe",
},
{
command: `npm run build && npx next start -p ${WEB_PORT} -H 127.0.0.1`,
url: `${WEB}/login`,
timeout: 400_000,
reuseExistingServer: false,
env: { NEXT_PUBLIC_API_URL: API, WP_API_URL: API, NEXT_TELEMETRY_DISABLED: "1" },
},
],
metadata: { api: API },
});12345678910111213141516171819import { defineConfig, devices } from "@playwright/test";
// Phase 18: end-to-end checks against a DEPLOYED environment (cd.yml, after the staging
// deploy). Unlike playwright.config.ts it starts no servers and needs no test-only API routes:
// it signs in with the public demo tenant (seeded by `python -m core.cli seed-demo`).
// E2E_BASE_URL=https://staging.example.com E2E_EMAIL=... E2E_PASSWORD=... \
// npx playwright test -c playwright.staging.config.ts
const BASE = process.env.E2E_BASE_URL ?? "http://127.0.0.1:3000";
export default defineConfig({
testDir: "./e2e-staging",
timeout: 90_000,
expect: { timeout: 20_000 },
workers: 1,
retries: process.env.CI ? 2 : 0,
reporter: process.env.CI ? [["list"], ["html", { open: "never" }]] : "list",
use: { baseURL: BASE, trace: "retain-on-failure", ...devices["Desktop Chrome"] },
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
});123456789import type { Metadata } from "next";
import { AnalyticsView } from "@/components/analytics/analytics-view";
export const metadata: Metadata = { title: "Analytics" };
export default function AnalyticsPage() {
return <AnalyticsView />;
}123456789import type { Metadata } from "next";
import { ChatView } from "@/components/chat/chat-view";
export const metadata: Metadata = { title: "Chat" };
export default function ChatPage() {
return <ChatView />;
}123456789import type { Metadata } from "next";
import { CodView } from "@/components/commerce/cod-view";
export const metadata: Metadata = { title: "COD" };
export default function CodPage() {
return <CodView />;
}123456789import type { Metadata } from "next";
import { InboxView } from "@/components/inbox/inbox-view";
export const metadata: Metadata = { title: "Inbox" };
export default function InboxPage() {
return <InboxView />;
}123456789import type { Metadata } from "next";
import { IntegrationsView } from "@/components/ext/integrations-view";
export const metadata: Metadata = { title: "Integrations & tools" };
export default function IntegrationsPage() {
return <IntegrationsView />;
}123456789import type { Metadata } from "next";
import { KnowledgeView } from "@/components/knowledge/knowledge-view";
export const metadata: Metadata = { title: "Knowledge" };
export default function KnowledgePage() {
return <KnowledgeView />;
}12345678910111213import { Suspense } from "react";
import { AppGate, FullPageLoading } from "@/components/shell/app-gate";
// Everything behind sign-in renders on the client (tokens live in browser memory), so the
// static shell is just a loading state and the rest streams in.
export default function AppLayout({ children }: LayoutProps<"/">) {
return (
<Suspense fallback={<FullPageLoading />}>
<AppGate>{children}</AppGate>
</Suspense>
);
}123456789import type { Metadata } from "next";
import { MemoryView } from "@/components/knowledge/memory-view";
export const metadata: Metadata = { title: "Memory" };
export default function MemoryPage() {
return <MemoryView />;
}12345678910"use client";
import { useParams } from "next/navigation";
import { OrderDetailView } from "@/components/commerce/order-detail";
export default function OrderPage() {
const { number } = useParams<{ number: string }>();
return <OrderDetailView key={number} number={decodeURIComponent(number)} />;
}123456789import type { Metadata } from "next";
import { OrdersView } from "@/components/commerce/orders-view";
export const metadata: Metadata = { title: "Orders" };
export default function OrdersPage() {
return <OrdersView />;
}123456789import type { Metadata } from "next";
import { RulesView } from "@/components/ext/rules-view";
export const metadata: Metadata = { title: "Rules" };
export default function RulesPage() {
return <RulesView />;
}12345678910"use client";
import { useParams } from "next/navigation";
import { RunDetail } from "@/components/runs/run-detail";
export default function RunPage() {
const { id } = useParams<{ id: string }>();
return <RunDetail key={id} runId={id} />;
}123456789import type { Metadata } from "next";
import { RunsList } from "@/components/runs/runs-list";
export const metadata: Metadata = { title: "Runs" };
export default function RunsPage() {
return <RunsList />;
}123456789import type { Metadata } from "next";
import { SettingsView } from "@/components/settings/settings-view";
export const metadata: Metadata = { title: "Settings" };
export default function SettingsPage() {
return <SettingsView />;
}12345678910"use client";
import { useParams } from "next/navigation";
import { WorkflowDetailView } from "@/components/workflows/workflow-detail";
export default function WorkflowPage() {
const { id } = useParams<{ id: string }>();
return <WorkflowDetailView key={id} id={id} />;
}123456789import type { Metadata } from "next";
import { WorkflowsView } from "@/components/workflows/workflows-view";
export const metadata: Metadata = { title: "Workflows" };
export default function WorkflowsPage() {
return <WorkflowsView />;
}1234567891011121314import type { Metadata } from "next";
import { Suspense } from "react";
import { AuthForm } from "@/components/shell/auth-form";
export const metadata: Metadata = { title: "Sign in" };
export default function LoginPage() {
return (
<Suspense>
<AuthForm mode="login" />
</Suspense>
);
}1234567891011121314import type { Metadata } from "next";
import { Suspense } from "react";
import { AuthForm } from "@/components/shell/auth-form";
export const metadata: Metadata = { title: "Create workspace" };
export default function SignupPage() {
return (
<Suspense>
<AuthForm mode="signup" />
</Suspense>
);
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677// Session BFF: the only place the refresh token exists outside the API. It is kept in an
// httpOnly, SameSite=Strict cookie scoped to /api/session, so browser JS never reads it.
import { NextResponse, type NextRequest } from "next/server";
const BACKEND = (
process.env.WP_API_URL ??
process.env.NEXT_PUBLIC_API_URL ??
"http://127.0.0.1:8000"
).replace(/\/$/, "");
const COOKIE = "wp_refresh";
const MAX_AGE = 14 * 24 * 60 * 60;
type Action = "login" | "signup" | "refresh" | "logout" | "switch";
const ACTIONS: Record<Action, string | null> = {
login: "/auth/login",
signup: "/auth/signup",
refresh: "/auth/refresh",
switch: "/me/tenant",
logout: null,
};
function withCookie(res: NextResponse, req: NextRequest, token: string | null): NextResponse {
res.cookies.set({
name: COOKIE,
value: token ?? "",
httpOnly: true,
sameSite: "strict",
secure: req.nextUrl.protocol === "https:",
path: "/api/session",
maxAge: token ? MAX_AGE : 0,
});
res.headers.set("Cache-Control", "no-store");
return res;
}
export async function POST(
req: NextRequest,
{ params }: { params: Promise<{ action: string }> },
): Promise<NextResponse> {
const { action } = await params;
if (!(action in ACTIONS)) return NextResponse.json({ detail: "not found" }, { status: 404 });
// CSRF: require a header a cross-site form cannot set (SameSite=Strict is the first line).
if (req.headers.get("x-requested-with") !== "workpilot") {
return NextResponse.json({ detail: "forbidden" }, { status: 403 });
}
if (action === "logout") return withCookie(NextResponse.json({ ok: true }), req, null);
const headers: Record<string, string> = { "Content-Type": "application/json" };
let body: string | undefined;
if (action === "refresh") {
const token = req.cookies.get(COOKIE)?.value;
if (!token) return NextResponse.json({ detail: "no session" }, { status: 401 });
body = JSON.stringify({ refresh_token: token });
} else {
body = await req.text();
if (action === "switch") headers.Authorization = req.headers.get("authorization") ?? "";
}
let upstream: Response;
try {
upstream = await fetch(`${BACKEND}${ACTIONS[action as Action]}`, {
method: "POST",
headers,
body,
cache: "no-store",
});
} catch {
return NextResponse.json({ detail: "API unreachable" }, { status: 502 });
}
const data = (await upstream.json().catch(() => ({}))) as Record<string, unknown>;
if (!upstream.ok) {
const res = NextResponse.json(data, { status: upstream.status });
return action === "refresh" ? withCookie(res, req, null) : res;
}
const res = NextResponse.json({ access_token: data.access_token, tenant_id: data.tenant_id });
return withCookie(res, req, String(data.refresh_token));
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
--font-mono: var(--font-geist-mono), ui-monospace, monospace;
--font-heading: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
--font-urdu: var(--font-nastaliq), var(--font-geist-sans), serif;
--color-success: var(--success);
--color-success-soft: var(--success-soft);
--color-warning: var(--warning);
--color-warning-soft: var(--warning-soft);
--color-info: var(--info);
--color-info-soft: var(--info-soft);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) * 0.6);
--radius-md: calc(var(--radius) * 0.8);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) * 1.4);
--radius-2xl: calc(var(--radius) * 1.8);
--radius-3xl: calc(var(--radius) * 2.2);
--radius-4xl: calc(var(--radius) * 2.6);
}
:root {
/* Calm, cool neutrals with a deep teal accent: an operations tool, not a marketing page. */
--background: oklch(0.985 0.002 247);
--foreground: oklch(0.21 0.014 256);
--card: oklch(1 0 0);
--card-foreground: oklch(0.21 0.014 256);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.21 0.014 256);
--primary: oklch(0.46 0.083 182);
--primary-foreground: oklch(0.985 0.005 182);
--secondary: oklch(0.962 0.005 247);
--secondary-foreground: oklch(0.27 0.016 256);
--muted: oklch(0.962 0.005 247);
--muted-foreground: oklch(0.51 0.017 256);
--accent: oklch(0.955 0.012 182);
--accent-foreground: oklch(0.3 0.05 182);
--destructive: oklch(0.56 0.19 25);
--border: oklch(0.913 0.007 247);
--input: oklch(0.9 0.008 247);
--ring: oklch(0.6 0.08 182);
--success: oklch(0.52 0.12 155);
--success-soft: oklch(0.95 0.04 155);
--warning: oklch(0.6 0.13 65);
--warning-soft: oklch(0.965 0.05 85);
--info: oklch(0.52 0.12 250);
--info-soft: oklch(0.955 0.025 250);
--chart-1: oklch(0.46 0.083 182);
--chart-2: oklch(0.6 0.13 65);
--chart-3: oklch(0.56 0.19 25);
--chart-4: oklch(0.52 0.12 250);
--chart-5: oklch(0.7 0.02 256);
--radius: 0.5rem;
--sidebar: oklch(0.975 0.003 247);
--sidebar-foreground: oklch(0.27 0.016 256);
--sidebar-primary: oklch(0.46 0.083 182);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.94 0.008 247);
--sidebar-accent-foreground: oklch(0.21 0.014 256);
--sidebar-border: oklch(0.913 0.007 247);
--sidebar-ring: oklch(0.6 0.08 182);
}
.dark {
--background: oklch(0.165 0.01 256);
--foreground: oklch(0.95 0.004 247);
--card: oklch(0.2 0.011 256);
--card-foreground: oklch(0.95 0.004 247);
--popover: oklch(0.21 0.012 256);
--popover-foreground: oklch(0.95 0.004 247);
--primary: oklch(0.74 0.1 180);
--primary-foreground: oklch(0.2 0.03 182);
--secondary: oklch(0.26 0.012 256);
--secondary-foreground: oklch(0.95 0.004 247);
--muted: oklch(0.25 0.011 256);
--muted-foreground: oklch(0.7 0.013 256);
--accent: oklch(0.27 0.03 182);
--accent-foreground: oklch(0.92 0.03 182);
--destructive: oklch(0.68 0.17 24);
--border: oklch(1 0 0 / 9%);
--input: oklch(1 0 0 / 14%);
--ring: oklch(0.6 0.08 182);
--success: oklch(0.74 0.13 155);
--success-soft: oklch(0.3 0.05 155);
--warning: oklch(0.8 0.13 75);
--warning-soft: oklch(0.31 0.05 70);
--info: oklch(0.74 0.11 250);
--info-soft: oklch(0.3 0.05 250);
--chart-1: oklch(0.74 0.1 180);
--chart-2: oklch(0.8 0.13 75);
--chart-3: oklch(0.68 0.17 24);
--chart-4: oklch(0.74 0.11 250);
--chart-5: oklch(0.5 0.02 256);
--sidebar: oklch(0.185 0.011 256);
--sidebar-foreground: oklch(0.9 0.006 247);
--sidebar-primary: oklch(0.74 0.1 180);
--sidebar-primary-foreground: oklch(0.2 0.03 182);
--sidebar-accent: oklch(0.25 0.012 256);
--sidebar-accent-foreground: oklch(0.95 0.004 247);
--sidebar-border: oklch(1 0 0 / 8%);
--sidebar-ring: oklch(0.6 0.08 182);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
button:not(:disabled), [role="button"]:not(:disabled) {
cursor: pointer;
}
html {
@apply font-sans;
}
}
/* Urdu: Nastaliq is tall and slanted; give it room. Code, ids and amounts stay LTR. */
html[lang="ur"] body {
font-family: var(--font-urdu);
line-height: 2;
}
html[lang="ur"] [dir="ltr"],
html[lang="ur"] .tabular {
font-family: var(--font-geist-sans), sans-serif;
line-height: 1.5;
}
html[lang="ur"] .font-mono,
html[lang="ur"] code {
font-family: var(--font-mono);
line-height: 1.5;
}
.tabular {
font-variant-numeric: tabular-nums;
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647import type { Metadata, Viewport } from "next";
import { Geist, Geist_Mono, Noto_Nastaliq_Urdu } from "next/font/google";
import { Providers } from "@/components/providers";
import { localeBootScript } from "@/lib/i18n/boot";
import "./globals.css";
const geistSans = Geist({ variable: "--font-geist-sans", subsets: ["latin"] });
const geistMono = Geist_Mono({ variable: "--font-geist-mono", subsets: ["latin"] });
// Urdu is set in Nastaliq, the script Pakistani readers expect (Naskh reads as Arabic).
const nastaliq = Noto_Nastaliq_Urdu({
variable: "--font-nastaliq",
subsets: ["arabic"],
weight: ["400", "600", "700"],
preload: false,
});
export const metadata: Metadata = {
title: { default: "WorkPilot", template: "%s · WorkPilot" },
description: "Safe AI operations for small businesses: an agent inbox, live runs and policies.",
};
export const viewport: Viewport = {
themeColor: [
{ media: "(prefers-color-scheme: light)", color: "#fbfcfd" },
{ media: "(prefers-color-scheme: dark)", color: "#16181d" },
],
};
export default function RootLayout({ children }: LayoutProps<"/">) {
return (
<html
lang="en"
dir="ltr"
suppressHydrationWarning
className={`${geistSans.variable} ${geistMono.variable} ${nastaliq.variable} h-full antialiased`}
>
<head>
<script dangerouslySetInnerHTML={{ __html: localeBootScript }} />
</head>
<body className="min-h-full">
<Providers>{children}</Providers>
</body>
</html>
);
}12345import { redirect } from "next/navigation";
export default function Home() {
redirect("/inbox");
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"use client";
import { useState } from "react";
import { OperationsHealth } from "@/components/analytics/operations-health";
import { RunStatusBadge } from "@/components/runs/status-badge";
import { ErrorState, PageHeader, StatTile } from "@/components/shell/page";
import { Skeleton } from "@/components/ui/skeleton";
import { formatDuration, formatNumber, formatPct } from "@/lib/format";
import { useI18n } from "@/lib/i18n";
import type { AnalyticsSummary } from "@/lib/types";
import { useApi } from "@/lib/use-api";
const STATUS_ORDER = ["completed", "waiting_approval", "running", "rejected", "failed", "unsupported"];
const STATUS_COLOR: Record<string, string> = {
completed: "var(--chart-1)",
waiting_approval: "var(--chart-2)",
running: "var(--chart-4)",
rejected: "var(--chart-3)",
failed: "var(--destructive)",
unsupported: "var(--chart-5)",
};
function Bars({ entries }: { entries: [string, number][] }) {
const max = Math.max(1, ...entries.map(([, n]) => n));
return (
<ul className="space-y-2">
{entries.map(([k, n]) => (
<li key={k} className="grid grid-cols-[9rem_1fr_3rem] items-center gap-3 text-sm">
<RunStatusBadge status={k} className="justify-self-start" />
<div className="h-2 rounded-full bg-muted">
<div
className="h-full rounded-full"
style={{ width: `${(n / max) * 100}%`, background: STATUS_COLOR[k] ?? "var(--chart-5)" }}
/>
</div>
<span className="tabular text-end text-muted-foreground">{formatNumber(n)}</span>
</li>
))}
</ul>
);
}
function DailyChart({ daily }: { daily: AnalyticsSummary["daily"] }) {
const { t } = useI18n();
const totals = daily.map((d) =>
Object.entries(d).reduce((s, [k, v]) => (k === "date" ? s : s + Number(v)), 0),
);
const max = Math.max(1, ...totals);
if (!daily.length) return <p className="text-sm text-muted-foreground">—</p>;
return (
<div className="flex h-40 items-end gap-1" role="img" aria-label={t("analytics.daily")} dir="ltr">
{daily.map((d, i) => (
<div key={d.date} className="group flex h-full flex-1 flex-col justify-end" title={`${d.date}: ${totals[i]}`}>
<div className="flex flex-col-reverse overflow-hidden rounded-t-sm" style={{ height: `${(totals[i] / max) * 100}%` }}>
{STATUS_ORDER.filter((s) => Number(d[s] ?? 0) > 0).map((s) => (
<div key={s} style={{ flexGrow: Number(d[s]), background: STATUS_COLOR[s] }} />
))}
</div>
<span className="mt-1 truncate text-center text-[10px] text-muted-foreground">{d.date.slice(5)}</span>
</div>
))}
</div>
);
}
export function AnalyticsView() {
const { t } = useI18n();
const [days, setDays] = useState(30);
const a = useApi<AnalyticsSummary>("/analytics/summary", { query: { days }, pollMs: 60_000 });
const d = a.data;
return (
<div className="space-y-5">
<PageHeader
title={t("analytics.title")}
subtitle={t("analytics.subtitle")}
actions={
<select
aria-label={t("analytics.period", { n: days })}
className="h-8 rounded-md border bg-background px-2 text-sm"
value={days}
onChange={(e) => setDays(Number(e.target.value))}
>
{[7, 30, 90].map((n) => (
<option key={n} value={n}>
{t("analytics.period", { n })}
</option>
))}
</select>
}
/>
{a.error && !d ? (
<ErrorState error={a.error} onRetry={a.reload} />
) : !d ? (
<Skeleton className="h-64 w-full" />
) : (
<>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4" data-testid="analytics-tiles">
<StatTile label={t("analytics.runs")} value={formatNumber(d.runs.total)} />
<StatTile
label={t("analytics.autoResolution")}
value={formatPct(d.auto_resolution_rate)}
hint={t("analytics.autoResolutionHint")}
/>
<StatTile
label={t("analytics.approvalRate")}
value={formatPct(d.approvals.approval_rate)}
hint={`${d.approvals.approved} / ${d.approvals.approved + d.approvals.rejected}`}
/>
<StatTile
label={t("analytics.latency")}
value={d.median_approval_latency_s === null ? "—" : formatDuration(d.median_approval_latency_s)}
/>
<StatTile label={t("analytics.toolCalls")} value={formatNumber(d.tool_calls.total)} />
<StatTile
label={t("analytics.cost")}
value={`$${d.cost_usd.toFixed(2)}`}
hint={d.cost_per_run_usd !== null ? `$${d.cost_per_run_usd.toFixed(3)} ${t("analytics.costPerRun")}` : undefined}
/>
<StatTile label={t("analytics.approvals")} value={formatNumber(d.approvals.pending)} hint={t("runs.statuses.pending")} />
</div>
<div className="grid gap-4 lg:grid-cols-2">
<section className="rounded-lg border bg-card p-4">
<h2 className="mb-3 text-sm font-semibold">{t("analytics.daily")}</h2>
<DailyChart daily={d.daily} />
</section>
<section className="rounded-lg border bg-card p-4">
<h2 className="mb-3 text-sm font-semibold">{t("analytics.runsByStatus")}</h2>
<Bars entries={Object.entries(d.runs.by_status).sort((x, y) => y[1] - x[1])} />
</section>
<section className="rounded-lg border bg-card p-4">
<h2 className="mb-3 text-sm font-semibold">{t("analytics.decisions")}</h2>
<Bars entries={Object.entries(d.tool_calls.by_decision).sort((x, y) => y[1] - x[1])} />
</section>
<section className="rounded-lg border bg-card p-4">
<h2 className="mb-3 text-sm font-semibold">{t("analytics.denials")}</h2>
{d.top_denial_reasons.length === 0 ? (
<p className="text-sm text-muted-foreground">{t("analytics.noDenials")}</p>
) : (
<ol className="space-y-2 text-sm">
{d.top_denial_reasons.map((r) => (
<li key={r.reason} className="flex gap-3">
<span className="tabular w-8 shrink-0 text-end font-medium">{r.count}</span>
<span className="text-muted-foreground">{r.reason}</span>
</li>
))}
</ol>
)}
</section>
</div>
</>
)}
<OperationsHealth days={days} />
</div>
);
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144import { screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, describe, expect, it, vi } from "vitest";
import { OperationsHealth } from "@/components/analytics/operations-health";
import { setAccessToken } from "@/lib/session";
import type { OperationsHealth as OpsHealth } from "@/lib/types";
import { mockFetch } from "@/test/fixtures";
import { renderUi } from "@/test/render";
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
usePathname: () => "/analytics",
}));
afterEach(() => {
vi.unstubAllGlobals();
setAccessToken(null);
});
function ops(over: Partial<OpsHealth> = {}): OpsHealth {
return {
days: 7,
runs: { total: 12, failed: 2, by_status: { completed: 10, failed: 2 } },
run_error_rate: 0.1667,
tool_calls: { total: 40, failed: 3, denied: 5, by_decision: { executed: 30 } },
tool_error_rate: 0.075,
approval_latency_s: { p50: 120, p95: 3600, decided: 8 },
denials: {
by_category: { policy: 3, quota: 2 },
top_reasons: [{ reason: "quota: tool calls per minute exceeded", count: 2, category: "quota" }],
},
quota_trips: 2,
circuit_breaker_trips: 0,
injection_signals: 1,
cost: {
total_usd: 0.42,
per_run_usd: 0.035,
daily: [{ date: "2026-12-05", cost_usd: 0.42, runs: 12 }],
prices_verified: false,
},
errors_daily: [{ date: "2026-12-05", calls: 40, failed_or_denied: 8 }],
alerts: [
{
id: "al-1",
kind: "circuit_breaker",
severity: "warning",
message: "3 circuit-breaker trips in the last 60 min",
status: "open",
detail: {},
created_at: "2026-12-05T10:00:00+00:00",
},
],
...over,
};
}
describe("OperationsHealth", () => {
it("renders tiles, denials, cost and alerts", async () => {
const { calls } = mockFetch({ "GET /analytics/operations": () => ops() });
renderUi(<OperationsHealth days={30} />);
expect(await screen.findByText("Operations health")).toBeInTheDocument();
await screen.findByTestId("ops-tiles");
expect(screen.getByTestId("ops-run-error-rate")).toHaveTextContent("16.7%");
expect(screen.getByTestId("ops-tool-error-rate")).toHaveTextContent("7.5%");
expect(screen.getByTestId("ops-latency-p50")).toHaveTextContent("2m");
expect(screen.getByTestId("ops-latency-p95")).toHaveTextContent("1h");
expect(screen.getByTestId("ops-quota-trips")).toHaveTextContent("2");
expect(screen.getByTestId("ops-breaker-trips")).toHaveTextContent("0");
expect(screen.getByTestId("ops-injection-signals")).toHaveTextContent("1");
expect(screen.getByTestId("ops-cost")).toHaveTextContent("$0.42");
expect(screen.getByTestId("ops-cost")).toHaveTextContent("$0.035");
expect(screen.getByTestId("ops-prices-unverified")).toHaveTextContent("Prices unverified");
const cats = screen.getByTestId("ops-denial-categories");
expect(within(cats).getByText("Policy")).toBeInTheDocument();
expect(screen.getByText("quota: tool calls per minute exceeded")).toBeInTheDocument();
expect(screen.getByTestId("ops-cost-daily")).toHaveTextContent("12-05");
const alert = screen.getByTestId("ops-alert");
expect(within(alert).getByText("Warning")).toBeInTheDocument();
expect(within(alert).getByText("3 circuit-breaker trips in the last 60 min")).toBeInTheDocument();
const get = calls.find((c) => c.path === "/analytics/operations");
expect(get).toBeDefined();
});
it("clamps days to 90", async () => {
const seen: string[] = [];
mockFetch({
"GET /analytics/operations": (url) => {
seen.push(url.searchParams.get("days") ?? "");
return ops();
},
});
renderUi(<OperationsHealth days={365} />);
await screen.findByTestId("ops-tiles");
expect(seen[0]).toBe("90");
});
it("shows an em dash for null rates and latencies, and empty states", async () => {
mockFetch({
"GET /analytics/operations": () =>
ops({
run_error_rate: null,
tool_error_rate: null,
approval_latency_s: { p50: null, p95: null, decided: 0 },
denials: { by_category: {}, top_reasons: [] },
cost: { total_usd: 0, per_run_usd: null, daily: [], prices_verified: true },
alerts: [],
}),
});
renderUi(<OperationsHealth days={7} />);
await screen.findByTestId("ops-tiles");
for (const id of ["ops-run-error-rate", "ops-tool-error-rate", "ops-latency-p50", "ops-latency-p95"]) {
expect(screen.getByTestId(id)).toHaveTextContent("—");
}
expect(screen.queryByTestId("ops-prices-unverified")).not.toBeInTheDocument();
expect(screen.getByText("No denials in this period.")).toBeInTheDocument();
expect(screen.getByText("No alerts. Everything looks healthy.")).toBeInTheDocument();
});
it("acknowledges an open alert and refreshes", async () => {
let acked = false;
const { calls } = mockFetch({
"GET /analytics/operations": () =>
acked
? ops({ alerts: [{ ...ops().alerts[0], status: "acknowledged" }] })
: ops(),
"POST /alerts/al-1/ack": () => {
acked = true;
return { ...ops().alerts[0], status: "acknowledged" };
},
});
renderUi(<OperationsHealth days={7} />);
await userEvent.click(await screen.findByRole("button", { name: "Acknowledge" }));
await waitFor(() =>
expect(calls.some((c) => c.method === "POST" && c.path === "/alerts/al-1/ack")).toBe(true),
);
expect(await screen.findByText("Acknowledged")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Acknowledge" })).not.toBeInTheDocument();
});
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225"use client";
import { useState } from "react";
import { toast } from "sonner";
import { ErrorState, StatTile } from "@/components/shell/page";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { api, ApiError } from "@/lib/api";
import { formatDateTime, formatDuration, formatNumber, formatPct, humanize } from "@/lib/format";
import { useI18n, type MessageKey } from "@/lib/i18n";
import type { OperationsHealth as OpsHealth, OpsAlert } from "@/lib/types";
import { useApi } from "@/lib/use-api";
const EMPTY = "—";
function usd(n: number | null | undefined, digits = 2): string {
return n === null || n === undefined ? EMPTY : `$${n.toFixed(digits)}`;
}
function duration(s: number | null | undefined): string {
return s === null || s === undefined ? EMPTY : formatDuration(s);
}
const SEVERITY_VARIANT: Record<string, "destructive" | "secondary" | "outline"> = {
critical: "destructive",
warning: "secondary",
info: "outline",
};
function AlertRow({ alert, onAcked }: { alert: OpsAlert; onAcked: () => void }) {
const { t, locale } = useI18n();
const [busy, setBusy] = useState(false);
const sevKey = `analytics.ops.severity.${alert.severity}` as MessageKey;
const sevLabel = t(sevKey);
const ack = async () => {
setBusy(true);
try {
await api<OpsAlert>(`/alerts/${encodeURIComponent(alert.id)}/ack`, { method: "POST" });
toast.success(t("analytics.ops.ackDone"));
onAcked();
} catch (err) {
toast.error(
err instanceof ApiError
? err.status === 403
? t("errors.forbidden")
: err.detail
: t("common.error"),
);
} finally {
setBusy(false);
}
};
return (
<li className="flex flex-wrap items-center gap-3 py-2 text-sm" data-testid="ops-alert">
<Badge variant={SEVERITY_VARIANT[alert.severity] ?? "outline"}>
{sevLabel === sevKey ? humanize(alert.severity) : sevLabel}
</Badge>
<span className="min-w-0 flex-1">{alert.message}</span>
<time className="tabular text-xs text-muted-foreground" dateTime={alert.created_at}>
{formatDateTime(alert.created_at, locale)}
</time>
{alert.status === "open" ? (
<Button size="sm" variant="outline" disabled={busy} onClick={() => void ack()}>
{t("analytics.ops.acknowledge")}
</Button>
) : (
<span className="text-xs text-muted-foreground">{t("analytics.ops.acknowledged")}</span>
)}
</li>
);
}
function CostDaily({ daily }: { daily: OpsHealth["cost"]["daily"] }) {
const { t } = useI18n();
if (!daily.length) return <p className="text-sm text-muted-foreground">{t("analytics.ops.noCost")}</p>;
const max = Math.max(0.000001, ...daily.map((d) => d.cost_usd));
return (
<ul className="space-y-2" data-testid="ops-cost-daily">
{daily.map((d) => (
<li key={d.date} className="grid grid-cols-[5rem_1fr_5rem] items-center gap-3 text-sm">
<span className="tabular text-muted-foreground" title={t("analytics.ops.runsCount", { n: d.runs })}>
{d.date.slice(5)}
</span>
<div className="h-2 rounded-full bg-muted">
<div
className="h-full rounded-full"
style={{ width: `${(d.cost_usd / max) * 100}%`, background: "var(--chart-1)" }}
/>
</div>
<span className="tabular text-end">{usd(d.cost_usd, 3)}</span>
</li>
))}
</ul>
);
}
export function OperationsHealth({ days }: { days: number }) {
const { t } = useI18n();
const clamped = Math.min(90, Math.max(1, Math.round(days)));
const o = useApi<OpsHealth>("/analytics/operations", { query: { days: clamped }, pollMs: 60_000 });
const d = o.data;
const categories = d ? Object.entries(d.denials.by_category).sort((x, y) => y[1] - x[1]) : [];
return (
<section className="space-y-4" aria-labelledby="ops-health-title" data-testid="ops-health">
<h2 id="ops-health-title" className="text-lg font-semibold tracking-tight">
{t("analytics.ops.title")}
</h2>
{o.error && !d ? (
<ErrorState error={o.error} onRetry={o.reload} />
) : !d ? (
<Skeleton className="h-48 w-full" />
) : (
<>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4" data-testid="ops-tiles">
<StatTile
testId="ops-run-error-rate"
label={t("analytics.ops.runErrorRate")}
value={formatPct(d.run_error_rate, 1)}
hint={t("analytics.ops.runErrorHint", { failed: d.runs.failed, total: d.runs.total })}
/>
<StatTile
testId="ops-tool-error-rate"
label={t("analytics.ops.toolErrorRate")}
value={formatPct(d.tool_error_rate, 1)}
hint={t("analytics.ops.toolErrorHint", {
failed: d.tool_calls.failed,
denied: d.tool_calls.denied,
total: d.tool_calls.total,
})}
/>
<StatTile
testId="ops-latency-p50"
label={t("analytics.ops.latencyP50")}
value={duration(d.approval_latency_s.p50)}
hint={t("analytics.ops.latencyHint", { n: d.approval_latency_s.decided })}
/>
<StatTile
testId="ops-latency-p95"
label={t("analytics.ops.latencyP95")}
value={duration(d.approval_latency_s.p95)}
/>
<StatTile testId="ops-quota-trips" label={t("analytics.ops.quotaTrips")} value={formatNumber(d.quota_trips)} />
<StatTile
testId="ops-breaker-trips"
label={t("analytics.ops.breakerTrips")}
value={formatNumber(d.circuit_breaker_trips)}
/>
<StatTile
testId="ops-injection-signals"
label={t("analytics.ops.injectionSignals")}
value={formatNumber(d.injection_signals)}
/>
<StatTile
testId="ops-cost"
label={t("analytics.ops.costTotal")}
value={usd(d.cost.total_usd)}
hint={
<>
{t("analytics.ops.costPerRun")}: {usd(d.cost.per_run_usd, 3)}
{!d.cost.prices_verified && (
<span className="ms-1 text-amber-600 dark:text-amber-400" data-testid="ops-prices-unverified">
· {t("analytics.ops.pricesUnverified")}
</span>
)}
</>
}
/>
</div>
<div className="grid gap-4 lg:grid-cols-2">
<section className="rounded-lg border bg-card p-4">
<h3 className="mb-3 text-sm font-semibold">{t("analytics.ops.denialsByCategory")}</h3>
{categories.length === 0 && d.denials.top_reasons.length === 0 ? (
<p className="text-sm text-muted-foreground">{t("analytics.ops.noDenials")}</p>
) : (
<>
<ul className="space-y-1 text-sm" data-testid="ops-denial-categories">
{categories.map(([cat, n]) => (
<li key={cat} className="flex justify-between gap-3">
<span>{humanize(cat)}</span>
<span className="tabular font-medium">{formatNumber(n)}</span>
</li>
))}
</ul>
{d.denials.top_reasons.length > 0 && (
<>
<h4 className="mb-2 mt-4 text-xs font-medium text-muted-foreground">
{t("analytics.ops.topReasons")}
</h4>
<ol className="space-y-2 text-sm">
{d.denials.top_reasons.map((r) => (
<li key={`${r.category}:${r.reason}`} className="flex gap-3">
<span className="tabular w-8 shrink-0 text-end font-medium">{r.count}</span>
<span className="text-muted-foreground">{r.reason}</span>
</li>
))}
</ol>
</>
)}
</>
)}
</section>
<section className="rounded-lg border bg-card p-4">
<h3 className="mb-3 text-sm font-semibold">{t("analytics.ops.costDaily")}</h3>
<CostDaily daily={d.cost.daily} />
</section>
</div>
<section className="rounded-lg border bg-card p-4">
<h3 className="mb-1 text-sm font-semibold">{t("analytics.ops.alerts")}</h3>
{d.alerts.length === 0 ? (
<p className="text-sm text-muted-foreground">{t("analytics.ops.noAlerts")}</p>
) : (
<ul className="divide-y" data-testid="ops-alerts">
{d.alerts.map((a) => (
<AlertRow key={a.id} alert={a} onAcked={o.reload} />
))}
</ul>
)}
</section>
</>
)}
</section>
);
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174"use client";
import { ArrowUpIcon, BotIcon, InboxIcon, Loader2Icon, UserIcon } from "lucide-react";
import Link from "next/link";
import { useEffect, useRef, useState, type FormEvent } from "react";
import { ActionResult } from "@/components/chat/gen-ui";
import { RunStatusBadge } from "@/components/runs/status-badge";
import { PageHeader } from "@/components/shell/page";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { api, ApiError } from "@/lib/api";
import { useI18n } from "@/lib/i18n";
import type { ChatResult } from "@/lib/types";
import { TERMINAL, useRunStream } from "@/lib/use-run-stream";
interface Turn {
id: string;
text: string;
result?: ChatResult;
error?: string;
}
/** Follows a run that paused for approval, so the answer updates when someone approves it. */
function LiveOutcome({ result }: { result: ChatResult }) {
const { t } = useI18n();
const { timeline } = useRunStream(result.run_id);
const status = timeline?.run.status ?? result.status;
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-2 rounded-md border border-warning/40 bg-warning-soft/50 px-3 py-2 text-sm">
<InboxIcon className="size-4 text-warning" aria-hidden />
<span>{status === "waiting_approval" ? t("chat.needsApproval") : null}</span>
<RunStatusBadge status={status} />
{status === "waiting_approval" && (
<Button size="xs" variant="outline" asChild className="ms-auto">
<Link href="/inbox">{t("chat.openInbox")}</Link>
</Button>
)}
</div>
{TERMINAL.has(status) && timeline?.run.output && <p>{timeline.run.output}</p>}
</div>
);
}
function Answer({ r }: { r: ChatResult }) {
const { t } = useI18n();
const shown = r.actions.filter((a) => a.data || a.status !== "executed");
return (
<div className="space-y-3" data-testid="chat-answer">
{r.output && <p className="whitespace-pre-wrap">{r.output}</p>}
{r.error && <p className="text-destructive">{r.error}</p>}
{shown.map((a, i) => (
<ActionResult key={`${a.step}-${i}`} action={a} />
))}
{r.status === "waiting_approval" && <LiveOutcome result={r} />}
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<RunStatusBadge status={r.status} />
<Link href={`/runs/${r.run_id}`} className="underline-offset-4 hover:underline">
{t("inbox.viewRun")}
</Link>
</div>
</div>
);
}
export function ChatView() {
const { t, m } = useI18n();
const [turns, setTurns] = useState<Turn[]>([]);
const [text, setText] = useState("");
const [busy, setBusy] = useState(false);
const endRef = useRef<HTMLDivElement>(null);
useEffect(() => {
endRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });
}, [turns, busy]);
const send = async (message: string) => {
const msg = message.trim();
if (!msg || busy) return;
const id = crypto.randomUUID();
setTurns((ts) => [...ts, { id, text: msg }]);
setText("");
setBusy(true);
try {
const result = await api<ChatResult>("/chat", { method: "POST", body: { message: msg } });
setTurns((ts) => ts.map((x) => (x.id === id ? { ...x, result } : x)));
} catch (e) {
const error = e instanceof ApiError ? e.detail : t("errors.network");
setTurns((ts) => ts.map((x) => (x.id === id ? { ...x, error } : x)));
} finally {
setBusy(false);
}
};
const submit = (e: FormEvent) => {
e.preventDefault();
void send(text);
};
return (
<div className="flex h-[calc(100dvh-8.5rem)] flex-col gap-4">
<PageHeader title={t("chat.title")} subtitle={t("chat.subtitle")} />
<div className="flex-1 space-y-5 overflow-y-auto rounded-lg border bg-card p-4" aria-live="polite">
{turns.length === 0 && (
<div className="flex h-full flex-col items-center justify-center gap-3 text-center">
<BotIcon className="size-6 text-muted-foreground" aria-hidden />
<p className="text-sm text-muted-foreground">{t("chat.empty")}</p>
<div className="flex flex-wrap justify-center gap-2">
{m.chat.suggestions.map((s) => (
<Button key={s} variant="outline" size="sm" onClick={() => send(s)}>
{s}
</Button>
))}
</div>
</div>
)}
{turns.map((turn) => (
<div key={turn.id} className="space-y-3">
<div className="flex items-start gap-2.5">
<span className="grid size-7 shrink-0 place-items-center rounded-full bg-muted" aria-hidden>
<UserIcon className="size-3.5" />
</span>
<p className="pt-1">{turn.text}</p>
</div>
<div className="flex items-start gap-2.5">
<span
className="grid size-7 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground"
aria-hidden
>
<BotIcon className="size-3.5" />
</span>
<div className="min-w-0 flex-1 pt-1">
{turn.result ? (
<Answer r={turn.result} />
) : turn.error ? (
<p className="text-destructive" role="alert">
{turn.error}
</p>
) : (
<p className="flex items-center gap-2 text-muted-foreground">
<Loader2Icon className="size-4 animate-spin" aria-hidden />
{t("chat.thinking")}
</p>
)}
</div>
</div>
</div>
))}
<div ref={endRef} />
</div>
<form onSubmit={submit} className="flex items-end gap-2">
<Textarea
value={text}
onChange={(e) => setText(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
void send(text);
}
}}
placeholder={t("chat.placeholder")}
rows={2}
maxLength={4000}
className="min-h-11 resize-none"
aria-label={t("chat.placeholder")}
/>
<Button type="submit" size="icon-lg" disabled={!text.trim() || busy} aria-label={t("chat.send")}>
<ArrowUpIcon aria-hidden />
</Button>
</form>
</div>
);
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194"use client";
import { GaugeIcon, PackageIcon, TruckIcon } from "lucide-react";
import { RiskBadge } from "@/components/commerce/risk-badge";
import { RunStatusBadge } from "@/components/runs/status-badge";
import { formatMoney, formatValue, humanize, toolLabel } from "@/lib/format";
import { useI18n } from "@/lib/i18n";
import type { RiskBand, RunAction } from "@/lib/types";
type Rec = Record<string, unknown>;
const isRec = (v: unknown): v is Rec => typeof v === "object" && v !== null && !Array.isArray(v);
export type GenKind = "order_table" | "risk_card" | "status_card" | "generic";
/** Pick a component for one tool result, from the tool name first and the data shape second. */
export function pickComponent(action: Pick<RunAction, "tool" | "data">): GenKind {
const tool = action.tool.toLowerCase();
const d = action.data;
if (!d) return "generic";
const list = Array.isArray(d.items) ? d.items : Array.isArray(d.orders) ? d.orders : null;
if (/(list|search|find)_orders|orders$/.test(tool) || (list && list.every(isRec))) {
if (list) return "order_table";
}
if (/risk|score/.test(tool) || ("band" in d && "score" in d) || isRec(d.risk)) return "risk_card";
if (("number" in d || "order_number" in d) && "status" in d) return "status_card";
return "generic";
}
export function OrderTable({ rows }: { rows: Rec[] }) {
const { t, locale } = useI18n();
return (
<div className="overflow-x-auto rounded-md border" data-testid="gen-order-table">
<table className="w-full text-sm">
<thead className="bg-muted/60 text-xs text-muted-foreground">
<tr>
<th className="px-3 py-1.5 text-start font-medium">{t("orders.number")}</th>
<th className="px-3 py-1.5 text-start font-medium">{t("orders.customer")}</th>
<th className="px-3 py-1.5 text-end font-medium">{t("orders.total")}</th>
<th className="px-3 py-1.5 text-start font-medium">{t("orders.status")}</th>
<th className="px-3 py-1.5 text-start font-medium">{t("orders.risk")}</th>
</tr>
</thead>
<tbody>
{rows.slice(0, 20).map((r, i) => {
const risk = isRec(r.risk) ? r.risk : null;
return (
<tr key={String(r.number ?? i)} className="border-t">
<td className="px-3 py-1.5 font-mono text-xs" dir="ltr">
{String(r.number ?? r.order_number ?? "—")}
</td>
<td className="px-3 py-1.5">{String(r.customer_name ?? r.customer ?? "—")}</td>
<td className="tabular px-3 py-1.5 text-end" dir="ltr">
{typeof r.total === "number" ? formatMoney(r.total, locale) : "—"}
</td>
<td className="px-3 py-1.5">{String(r.status ?? "—")}</td>
<td className="px-3 py-1.5">
{risk?.band ? <RiskBand band={risk.band as RiskBand} /> : "—"}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
function RiskBand({ band }: { band: RiskBand }) {
return <RiskBadge band={band} />;
}
export function RiskCard({ data }: { data: Rec }) {
const { t } = useI18n();
const r = isRec(data.risk) ? data.risk : data;
const score = typeof r.score === "number" ? r.score : null;
const band = (r.band as RiskBand | undefined) ?? "medium";
const reasons = Array.isArray(r.reasons) ? r.reasons.map(String) : [];
return (
<div className="space-y-3 rounded-md border p-3" data-testid="gen-risk-card">
<div className="flex items-center gap-2">
<GaugeIcon className="size-4 text-muted-foreground" aria-hidden />
<span className="font-medium">{t("orders.risk")}</span>
{typeof data.number === "string" && (
<code className="font-mono text-xs text-muted-foreground" dir="ltr">
{data.number}
</code>
)}
<span className="ms-auto">
<RiskBadge band={band} />
</span>
</div>
{score !== null && (
<div className="space-y-1">
<div className="tabular text-2xl font-semibold" dir="ltr">
{score <= 1 ? Math.round(score * 100) : Math.round(score)}
<span className="text-sm font-normal text-muted-foreground"> / 100</span>
</div>
<div className="h-1.5 rounded-full bg-muted">
<div
className="h-full rounded-full bg-primary"
style={{ width: `${Math.min(100, score <= 1 ? score * 100 : score)}%` }}
/>
</div>
</div>
)}
{reasons.length > 0 && (
<ul className="list-disc space-y-0.5 ps-5 text-sm text-muted-foreground">
{reasons.map((x) => (
<li key={x}>{x}</li>
))}
</ul>
)}
</div>
);
}
export function StatusCard({ data }: { data: Rec }) {
const { locale } = useI18n();
const number = String(data.number ?? data.order_number ?? "");
const skip = new Set(["number", "order_number", "status", "customer_name"]);
return (
<div className="space-y-2 rounded-md border p-3" data-testid="gen-status-card">
<div className="flex items-center gap-2">
<PackageIcon className="size-4 text-muted-foreground" aria-hidden />
<code className="font-mono text-sm font-medium" dir="ltr">
{number}
</code>
{typeof data.customer_name === "string" && (
<span className="text-sm text-muted-foreground">{data.customer_name}</span>
)}
<span className="ms-auto">
<RunStatusBadge status={String(data.status)} />
</span>
</div>
<dl className="grid grid-cols-2 gap-x-4 gap-y-1 text-sm sm:grid-cols-3">
{Object.entries(data)
.filter(([k, v]) => !skip.has(k) && !isRec(v) && !Array.isArray(v))
.map(([k, v]) => (
<div key={k}>
<dt className="text-xs text-muted-foreground">{humanize(k)}</dt>
<dd className="tabular" dir="ltr">
{formatValue(k, v, locale)}
</dd>
</div>
))}
</dl>
{isRec(data.courier) && (
<p className="flex items-center gap-1.5 text-xs text-muted-foreground">
<TruckIcon className="size-3.5" aria-hidden />
{String(data.courier.name ?? "")} · {String(data.courier.status ?? "")}
</p>
)}
</div>
);
}
export function GenericCard({ action }: { action: RunAction }) {
const { locale } = useI18n();
return (
<div className="space-y-1 rounded-md border p-3 text-sm" data-testid="gen-generic">
<div className="flex items-center gap-2">
<span className="font-medium">{toolLabel(action.tool)}</span>
<RunStatusBadge status={action.status} />
</div>
{action.reason && <p className="text-muted-foreground">{action.reason}</p>}
{action.data && (
<dl className="grid grid-cols-2 gap-x-4 gap-y-0.5">
{Object.entries(action.data).map(([k, v]) => (
<div key={k} className="contents">
<dt className="text-muted-foreground">{humanize(k)}</dt>
<dd className="tabular break-all" dir="ltr">
{formatValue(k, v, locale)}
</dd>
</div>
))}
</dl>
)}
</div>
);
}
export function ActionResult({ action }: { action: RunAction }) {
const kind = pickComponent(action);
const d = action.data ?? {};
if (kind === "order_table") {
const rows = (Array.isArray(d.items) ? d.items : d.orders) as Rec[];
return <OrderTable rows={rows} />;
}
if (kind === "risk_card") return <RiskCard data={d} />;
if (kind === "status_card") return <StatusCard data={d} />;
return <GenericCard action={action} />;
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"use client";
import { BanknoteIcon } from "lucide-react";
import { isPackMissing, OrdersTable } from "@/components/commerce/orders-view";
import { EmptyState, ErrorState, PageHeader, StatTile } from "@/components/shell/page";
import { Skeleton } from "@/components/ui/skeleton";
import { formatMoney, formatNumber, formatPct } from "@/lib/format";
import { useI18n } from "@/lib/i18n";
import type { CodSummary, RiskBand } from "@/lib/types";
import { useApi } from "@/lib/use-api";
import { cn } from "@/lib/utils";
const BAND_BAR: Record<RiskBand, string> = {
low: "bg-success",
medium: "bg-warning",
high: "bg-destructive",
};
export function CodView() {
const { t, m, locale } = useI18n();
const s = useApi<CodSummary>("/packs/ecommerce/cod/summary", { pollMs: 30_000 });
let body;
if (s.error && isPackMissing(s.error)) {
body = <EmptyState icon={BanknoteIcon} title={t("common.notAvailable")} hint={t("cod.unavailable")} />;
} else if (s.error && !s.data) {
body = <ErrorState error={s.error} onRetry={s.reload} />;
} else if (!s.data) {
body = <Skeleton className="h-40 w-full" />;
} else {
const d = s.data;
const bandTotal = d.by_band.low + d.by_band.medium + d.by_band.high;
body = (
<div className="space-y-5">
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4" data-testid="cod-summary">
<StatTile label={t("cod.pending")} value={formatNumber(d.pending_confirmation)} />
<StatTile label={t("cod.confirmed")} value={formatNumber(d.confirmed)} />
<StatTile label={t("cod.rto")} value={formatPct(d.rto_rate, 1)} />
<StatTile label={t("cod.outstanding")} value={formatMoney(d.cod_outstanding, locale)} />
</div>
<section className="rounded-lg border bg-card p-4">
<h2 className="mb-3 text-sm font-semibold">{t("cod.byBand")}</h2>
<div className="flex h-3 overflow-hidden rounded-full bg-muted" role="img" aria-label={t("cod.byBand")}>
{(["low", "medium", "high"] as const).map((b) =>
d.by_band[b] ? (
<div
key={b}
className={cn("h-full", BAND_BAR[b])}
style={{ width: `${(d.by_band[b] / Math.max(1, bandTotal)) * 100}%` }}
/>
) : null,
)}
</div>
<dl className="mt-3 flex flex-wrap gap-6 text-sm">
{(["low", "medium", "high"] as const).map((b) => (
<div key={b} className="flex items-center gap-2">
<span className={cn("size-2 rounded-full", BAND_BAR[b])} aria-hidden />
<dt className="text-muted-foreground">{m.orders.bands[b]}</dt>
<dd className="tabular font-medium">{formatNumber(d.by_band[b])}</dd>
</div>
))}
</dl>
</section>
<section className="space-y-2">
<h2 className="text-sm font-semibold">{t("cod.queue")}</h2>
<OrdersTable
testId="cod-queue"
query={{ payment_method: "cod", status: "pending", limit: 50, offset: 0 }}
/>
</section>
</div>
);
}
return (
<div className="space-y-5">
<PageHeader title={t("cod.title")} subtitle={t("cod.subtitle")} />
{body}
</div>
);
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129"use client";
import { ArrowLeftIcon, PackageIcon } from "lucide-react";
import Link from "next/link";
import { isPackMissing } from "@/components/commerce/orders-view";
import { RiskBadge } from "@/components/commerce/risk-badge";
import { RunStatusBadge } from "@/components/runs/status-badge";
import { EmptyState, ErrorState } from "@/components/shell/page";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { formatDateTime, formatMoney, formatValue, humanize } from "@/lib/format";
import { useI18n } from "@/lib/i18n";
import type { OrderDetail as Detail } from "@/lib/types";
import { useApi } from "@/lib/use-api";
function Records({ title, rows }: { title: string; rows: Record<string, unknown>[] | undefined }) {
const { locale } = useI18n();
if (!rows?.length) return null;
return (
<section className="rounded-lg border bg-card p-4">
<h2 className="mb-2 text-sm font-semibold">{title}</h2>
<ul className="divide-y">
{rows.map((r, i) => (
<li key={i} className="flex flex-wrap gap-x-4 gap-y-1 py-2 text-sm">
{Object.entries(r)
.filter(([, v]) => typeof v !== "object" || v === null)
.map(([k, v]) => (
<span key={k}>
<span className="text-muted-foreground">{humanize(k)}: </span>
<span dir="auto">{formatValue(k, v, locale)}</span>
</span>
))}
</li>
))}
</ul>
</section>
);
}
export function OrderDetailView({ number }: { number: string }) {
const { t, locale } = useI18n();
const order = useApi<Detail>(`/packs/ecommerce/orders/${encodeURIComponent(number)}`);
const back = (
<Button variant="ghost" size="sm" asChild className="-ms-2">
<Link href="/orders">
<ArrowLeftIcon className="rtl:rotate-180" aria-hidden />
{t("orders.title")}
</Link>
</Button>
);
if (order.error && isPackMissing(order.error) && !order.data) {
return (
<div className="space-y-4">
{back}
<EmptyState icon={PackageIcon} title={t("common.notAvailable")} hint={t("orders.unavailable")} />
</div>
);
}
if (order.error && !order.data) return <ErrorState error={order.error} onRetry={order.reload} />;
if (!order.data) return <Skeleton className="h-80 w-full" />;
const o = order.data;
return (
<div className="space-y-5">
{back}
<div className="flex flex-wrap items-center gap-3">
<h1 className="font-mono text-xl font-semibold" dir="ltr">
{o.number}
</h1>
<RunStatusBadge status={o.status} />
{o.risk && <RiskBadge band={o.risk.band} score={o.risk.score} />}
<span className="tabular ms-auto text-lg font-semibold" dir="ltr">
{formatMoney(o.total, locale)}
</span>
</div>
<div className="grid gap-4 md:grid-cols-3">
<section className="rounded-lg border bg-card p-4 text-sm">
<h2 className="mb-2 font-semibold">{t("orders.customerInfo")}</h2>
<p>{o.customer_name}</p>
<p className="text-muted-foreground">{o.city}</p>
{o.customer &&
Object.entries(o.customer)
.filter(([k, v]) => !["name", "id"].includes(k) && (typeof v !== "object" || v === null))
.map(([k, v]) => (
<p key={k} className="text-muted-foreground">
{humanize(k)}: <span dir="auto">{formatValue(k, v, locale)}</span>
</p>
))}
</section>
<section className="rounded-lg border bg-card p-4 text-sm">
<h2 className="mb-2 font-semibold">{t("orders.payment")}</h2>
<p className="uppercase">{o.payment_method}</p>
<p className="text-muted-foreground">
{t("orders.confirmation")}: {o.confirmation_status ?? "—"}
</p>
<p className="text-muted-foreground">{formatDateTime(o.created_at, locale)}</p>
</section>
<section className="rounded-lg border bg-card p-4 text-sm">
<h2 className="mb-2 font-semibold">{t("orders.courier")}</h2>
{o.courier ? (
<>
<p>{o.courier.name}</p>
<p className="font-mono text-xs" dir="ltr">
{o.courier.tracking}
</p>
<p className="text-muted-foreground">{o.courier.status}</p>
</>
) : (
<p className="text-muted-foreground">—</p>
)}
</section>
</div>
{o.risk && o.risk.reasons.length > 0 && (
<section className="rounded-lg border bg-card p-4">
<h2 className="mb-2 text-sm font-semibold">{t("orders.reasons")}</h2>
<ul className="list-disc space-y-0.5 ps-5 text-sm text-muted-foreground">
{o.risk.reasons.map((r) => (
<li key={r}>{r}</li>
))}
</ul>
</section>
)}
<Records title={t("orders.items")} rows={o.items as Record<string, unknown>[] | undefined} />
<Records title={t("orders.shipments")} rows={o.shipments} />
<Records title={t("orders.messages")} rows={o.messages} />
<Records title={t("orders.tickets")} rows={o.tickets} />
</div>
);
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191"use client";
import { PackageIcon, SearchIcon } from "lucide-react";
import Link from "next/link";
import { useDeferredValue, useState } from "react";
import { RiskBadge } from "@/components/commerce/risk-badge";
import { RunStatusBadge } from "@/components/runs/status-badge";
import { EmptyState, ErrorState, PageHeader } from "@/components/shell/page";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ApiError } from "@/lib/api";
import { formatDateTime, formatMoney } from "@/lib/format";
import { useI18n } from "@/lib/i18n";
import type { OrderRow, Page } from "@/lib/types";
import { useApi } from "@/lib/use-api";
const PAGE = 50;
/** The e-commerce pack (Phase 6) serves these routes; until it is installed they 404. */
export function isPackMissing(e: unknown): boolean {
return e instanceof ApiError && (e.status === 404 || e.status === 405);
}
function Filter({
label,
value,
onChange,
options,
}: {
label: string;
value: string;
onChange: (v: string) => void;
options: { value: string; label: string }[];
}) {
return (
<label className="flex items-center gap-2 text-sm">
<span className="text-muted-foreground">{label}</span>
<select
className="h-8 rounded-md border bg-background px-2 text-sm"
value={value}
onChange={(e) => onChange(e.target.value)}
>
{options.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
</label>
);
}
export function OrdersTable({
query,
testId = "orders-table",
}: {
query: Record<string, string | number>;
testId?: string;
}) {
const { t, locale } = useI18n();
const orders = useApi<Page<OrderRow>>("/packs/ecommerce/orders", { query, pollMs: 30_000 });
if (orders.error && isPackMissing(orders.error)) {
return <EmptyState icon={PackageIcon} title={t("common.notAvailable")} hint={t("orders.unavailable")} />;
}
if (orders.error && !orders.data) return <ErrorState error={orders.error} onRetry={orders.reload} />;
if (orders.loading && !orders.data) return <Skeleton className="h-72 w-full" />;
if (!orders.data?.items.length) return <EmptyState icon={PackageIcon} title={t("orders.empty")} />;
return (
<div className="overflow-hidden rounded-lg border bg-card">
<Table data-testid={testId}>
<TableHeader>
<TableRow>
<TableHead>{t("orders.number")}</TableHead>
<TableHead>{t("orders.customer")}</TableHead>
<TableHead className="text-end">{t("orders.total")}</TableHead>
<TableHead>{t("orders.status")}</TableHead>
<TableHead>{t("orders.risk")}</TableHead>
<TableHead className="hidden lg:table-cell">{t("orders.confirmation")}</TableHead>
<TableHead className="hidden lg:table-cell">{t("orders.courier")}</TableHead>
<TableHead className="hidden xl:table-cell">{t("orders.created")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{orders.data.items.map((o) => (
<TableRow key={o.number} className="relative">
<TableCell>
<Link
href={`/orders/${encodeURIComponent(o.number)}`}
className="font-mono text-xs font-medium after:absolute after:inset-0 hover:underline"
dir="ltr"
>
{o.number}
</Link>
</TableCell>
<TableCell>
<div>{o.customer_name}</div>
<div className="text-xs text-muted-foreground">{o.city}</div>
</TableCell>
<TableCell className="tabular text-end" dir="ltr">
{formatMoney(o.total, locale)}
<div className="text-[11px] text-muted-foreground uppercase">{o.payment_method}</div>
</TableCell>
<TableCell>
<RunStatusBadge status={o.status} />
</TableCell>
<TableCell>{o.risk ? <RiskBadge band={o.risk.band} score={o.risk.score} /> : "—"}</TableCell>
<TableCell className="hidden text-muted-foreground lg:table-cell">
{o.confirmation_status ?? "—"}
</TableCell>
<TableCell className="hidden text-muted-foreground lg:table-cell">
{o.courier ? `${o.courier.name} · ${o.courier.status}` : "—"}
</TableCell>
<TableCell className="tabular hidden text-muted-foreground xl:table-cell">
{formatDateTime(o.created_at, locale)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
{orders.data.total > orders.data.items.length && (
<p className="border-t px-4 py-2 text-xs text-muted-foreground">
{orders.data.items.length} {t("common.of")} {orders.data.total}
</p>
)}
</div>
);
}
export function OrdersView() {
const { t, m } = useI18n();
const [q, setQ] = useState("");
const query = useDeferredValue(q);
const [status, setStatus] = useState("");
const [payment, setPayment] = useState("");
const [band, setBand] = useState("");
const [offset, setOffset] = useState(0);
const all = { value: "", label: t("common.all") };
return (
<div className="space-y-5">
<PageHeader title={t("orders.title")} subtitle={t("orders.subtitle")} />
<div className="flex flex-wrap items-center gap-3">
<div className="relative w-full max-w-xs">
<SearchIcon className="absolute start-2.5 top-2 size-4 text-muted-foreground" aria-hidden />
<Input
className="ps-8"
placeholder={t("orders.searchPlaceholder")}
aria-label={t("common.search")}
value={q}
onChange={(e) => {
setQ(e.target.value);
setOffset(0);
}}
/>
</div>
<Filter
label={t("orders.status")}
value={status}
onChange={setStatus}
options={[all, ...["pending", "confirmed", "shipped", "delivered", "cancelled", "returned"].map((v) => ({ value: v, label: (m.runs.statuses as Record<string, string>)[v] ?? v }))]}
/>
<Filter
label={t("orders.payment")}
value={payment}
onChange={setPayment}
options={[all, { value: "cod", label: "COD" }, { value: "prepaid", label: t("orders.prepaid") }]}
/>
<Filter
label={t("orders.risk")}
value={band}
onChange={setBand}
options={[all, ...(["low", "medium", "high"] as const).map((v) => ({ value: v, label: m.orders.bands[v] }))]}
/>
</div>
<OrdersTable
query={{ q: query, status, payment_method: payment, risk_band: band, limit: PAGE, offset }}
/>
<div className="flex justify-end gap-2">
<Button variant="outline" size="sm" disabled={offset === 0} onClick={() => setOffset(Math.max(0, offset - PAGE))}>
{t("common.previous")}
</Button>
<Button variant="outline" size="sm" onClick={() => setOffset(offset + PAGE)}>
{t("common.next")}
</Button>
</div>
</div>
);
}1234567891011121314151617181920212223242526272829303132"use client";
import { useI18n } from "@/lib/i18n";
import type { RiskBand } from "@/lib/types";
import { cn } from "@/lib/utils";
const TONE: Record<RiskBand, string> = {
low: "border-success/30 bg-success-soft text-success",
medium: "border-warning/40 bg-warning-soft text-warning",
high: "border-destructive/30 bg-destructive/10 text-destructive",
};
export function RiskBadge({ band, score }: { band: RiskBand; score?: number }) {
const { m } = useI18n();
return (
<span
data-band={band}
className={cn(
"inline-flex h-5 items-center gap-1 rounded-full border px-2 text-[11px] font-medium whitespace-nowrap",
TONE[band] ?? TONE.medium,
)}
>
<span className="size-1.5 rounded-full bg-current" aria-hidden />
{m.orders.bands[band] ?? band}
{score !== undefined && (
<span className="tabular opacity-80" dir="ltr">
{score <= 1 ? Math.round(score * 100) : Math.round(score)}
</span>
)}
</span>
);
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564"use client";
import { PlugIcon, RefreshCwIcon, ShieldAlertIcon } from "lucide-react";
import { useState, type FormEvent, type ReactNode } from "react";
import { toast } from "sonner";
import { EmptyState, ErrorState, PageHeader } from "@/components/shell/page";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { api, ApiError } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { useI18n } from "@/lib/i18n";
import { useApi } from "@/lib/use-api";
import { cn } from "@/lib/utils";
import type {
Connector,
GatewayOutcomeOut,
ImportReport,
McpChange,
McpConnection,
TenantTool,
ToolMode,
} from "./types";
const TIER_STYLE = [
"bg-success-soft text-success",
"bg-muted text-foreground",
"bg-warning-soft text-warning",
"bg-destructive/10 text-destructive",
];
export function TierBadge({ tier, testId }: { tier: number; testId?: string }) {
return (
<span
className={cn("tabular rounded px-1.5 py-0.5 text-xs font-semibold", TIER_STYLE[tier] ?? TIER_STYLE[3])}
data-testid={testId}
>
T{tier}
</span>
);
}
function errText(err: unknown, fallback: string): string {
if (err instanceof ApiError) {
const d = (err.body as { detail?: unknown } | undefined)?.detail;
if (d && typeof d === "object" && "message" in d) return String((d as { message: string }).message);
return err.detail;
}
return fallback;
}
function Field({ label, hint, children }: { label: string; hint?: string; children: ReactNode }) {
return (
<div className="space-y-1.5">
<label className="block space-y-1.5">
<span className="text-sm leading-none font-medium">{label}</span>
{children}
</label>
{hint && <p className="text-xs text-muted-foreground">{hint}</p>}
</div>
);
}
// ---------------------------------------------------------------------------- tools
function ToolRow({ tool, owner, onChanged }: { tool: TenantTool; owner: boolean; onChanged: () => void }) {
const { t } = useI18n();
const [tier, setTier] = useState<number>(tool.confirmed_tier ?? tool.suggested_tier);
const [mode, setMode] = useState<ToolMode>(tool.mode === "live" ? "live" : "test");
const [ack, setAck] = useState(false);
const [busy, setBusy] = useState(false);
const [argsText, setArgsText] = useState("{}");
const [preview, setPreview] = useState<GatewayOutcomeOut | null>(null);
const confirm = async () => {
setBusy(true);
try {
await api(`/ext/tools/${encodeURIComponent(tool.name)}/confirm`, {
method: "POST",
body: { tier, mode, acknowledge_risk: ack },
});
toast.success(t("integrations.confirmed"));
onChanged();
} catch (err) {
toast.error(errText(err, t("common.error")));
} finally {
setBusy(false);
}
};
const toggle = async (enabled: boolean) => {
try {
await api(`/ext/tools/${encodeURIComponent(tool.name)}/settings`, { method: "POST", body: { enabled } });
onChanged();
} catch (err) {
toast.error(errText(err, t("common.error")));
}
};
const dryRun = async () => {
let args: unknown;
try {
args = JSON.parse(argsText);
} catch {
toast.error(t("integrations.invalidJson"));
return;
}
try {
setPreview(
await api<GatewayOutcomeOut>(`/ext/tools/${encodeURIComponent(tool.name)}/test`, {
method: "POST",
body: { args },
}),
);
} catch (err) {
toast.error(errText(err, t("common.error")));
}
};
return (
<li className="space-y-3 rounded-lg border bg-card p-4" data-testid="tenant-tool" data-tool={tool.name}>
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0 space-y-1">
<p className="font-mono text-sm font-medium" dir="ltr">
{tool.name}
</p>
<p className="text-sm text-muted-foreground">{tool.description}</p>
</div>
<div className="flex items-center gap-2 text-xs">
<Badge variant="outline">{tool.source}</Badge>
<span className="text-muted-foreground">{t("integrations.suggested")}</span>
<TierBadge tier={tool.suggested_tier} />
<span className="text-muted-foreground">{t("integrations.tier")}</span>
<TierBadge tier={tool.effective_tier} testId="effective-tier" />
<Badge variant={tool.mode === "live" ? "default" : "secondary"} data-testid="tool-mode">
{tool.mode === "live" ? t("integrations.live") : t("integrations.test")}
</Badge>
{tool.confirmed_tier === null && <Badge variant="secondary">{t("integrations.unconfirmed")}</Badge>}
</div>
</div>
{tool.blocked_reason && (
<p className="flex items-center gap-2 rounded-md bg-warning-soft px-3 py-2 text-sm text-warning" role="status">
<ShieldAlertIcon className="size-4 shrink-0" aria-hidden />
{tool.pending ? t("integrations.changed") : tool.blocked_reason}
</p>
)}
{tool.pending && (
<div className="grid gap-2 text-sm md:grid-cols-2" data-testid="pending-change">
<div className="rounded-md border p-2">
<p className="text-xs text-muted-foreground">{t("integrations.before")}</p>
<p>{tool.description}</p>
</div>
<div className="rounded-md border border-warning/40 p-2">
<p className="text-xs text-muted-foreground">{t("integrations.after")}</p>
<p>{tool.pending.description}</p>
</div>
</div>
)}
<div className="flex flex-wrap items-end gap-3">
{owner && (
<>
<Field label={t("integrations.tier")}>
<select
className="h-8 rounded-md border bg-background px-2 text-sm"
value={tier}
onChange={(e) => setTier(Number(e.target.value))}
aria-label={`${t("integrations.tier")} ${tool.name}`}
>
{[0, 1, 2, 3].map((n) => (
<option key={n} value={n}>
T{n}
</option>
))}
</select>
</Field>
<Field label={t("integrations.mode")}>
<select
className="h-8 rounded-md border bg-background px-2 text-sm"
value={mode}
onChange={(e) => setMode(e.target.value as ToolMode)}
aria-label={`${t("integrations.mode")} ${tool.name}`}
>
<option value="test">{t("integrations.test")}</option>
<option value="live">{t("integrations.live")}</option>
</select>
</Field>
{tier < tool.suggested_tier && (
<label className="flex items-center gap-2 text-xs">
<input type="checkbox" checked={ack} onChange={(e) => setAck(e.target.checked)} />
{t("integrations.lowerTier")}
</label>
)}
<Button size="sm" onClick={confirm} disabled={busy || (tier < tool.suggested_tier && !ack)}>
{t("integrations.confirm")}
</Button>
<label className="ms-auto flex items-center gap-2 text-sm">
<Switch
checked={tool.enabled}
onCheckedChange={(v) => void toggle(v)}
aria-label={`${t("integrations.enabled")} ${tool.name}`}
/>
{tool.enabled ? t("integrations.enabled") : t("integrations.disabled")}
</label>
</>
)}
</div>
<details className="text-sm">
<summary className="cursor-pointer text-muted-foreground">{t("integrations.tryIt")}</summary>
<div className="mt-2 space-y-2">
<Textarea
dir="ltr"
className="font-mono text-xs"
rows={3}
value={argsText}
onChange={(e) => setArgsText(e.target.value)}
aria-label={`${t("integrations.args")} ${tool.name}`}
/>
<Button size="sm" variant="outline" onClick={dryRun}>
{t("integrations.runDryRun")}
</Button>
{preview && (
<pre
dir="ltr"
className="max-h-64 overflow-auto rounded-md bg-muted p-2 text-xs"
data-testid="dry-run-preview"
>
{JSON.stringify({ status: preview.status, reason: preview.reason, data: preview.result?.data }, null, 2)}
</pre>
)}
</div>
</details>
</li>
);
}
function ToolsTab({ owner }: { owner: boolean }) {
const { t } = useI18n();
const tools = useApi<TenantTool[]>("/ext/tools");
if (tools.error) return <ErrorState error={tools.error} onRetry={tools.reload} />;
if (!tools.data) return <Skeleton className="h-32 w-full" />;
if (tools.data.length === 0)
return <EmptyState icon={PlugIcon} title={t("integrations.noTools")} hint={t("integrations.noToolsHint")} />;
return (
<ul className="space-y-3" data-testid="tenant-tools">
{tools.data.map((tool) => (
<ToolRow key={`${tool.name}:${tool.definition_hash}:${tool.updated_at}`} tool={tool} owner={owner} onChanged={tools.reload} />
))}
</ul>
);
}
// --------------------------------------------------------------------------- import
function ImportTab({ onDone }: { onDone: () => void }) {
const { t } = useI18n();
const [form, setForm] = useState({ name: "", spec: "", url: "", base_url: "", sandbox_base_url: "", secret_ref: "", sandbox_secret_ref: "" });
const [busy, setBusy] = useState(false);
const set = (k: keyof typeof form) => (e: { target: { value: string } }) => setForm({ ...form, [k]: e.target.value });
const submit = async (e: FormEvent) => {
e.preventDefault();
setBusy(true);
const body = Object.fromEntries(Object.entries(form).filter(([, v]) => v.trim() !== ""));
try {
const r = await api<{ report: ImportReport }>("/ext/openapi/import", { method: "POST", body });
toast.success(t("integrations.imported", { n: r.report.created.length + r.report.changed.length }));
onDone();
} catch (err) {
toast.error(errText(err, t("common.error")));
} finally {
setBusy(false);
}
};
return (
<form onSubmit={submit} className="grid gap-4 rounded-lg border bg-card p-4 md:grid-cols-2" data-testid="import-form">
<Field label={t("integrations.name")} hint={t("integrations.nameHint")}>
<Input dir="ltr" value={form.name} onChange={set("name")} required pattern="[a-z][a-z0-9_]{1,39}" />
</Field>
<Field label={t("integrations.specUrl")}>
<Input dir="ltr" type="url" value={form.url} onChange={set("url")} />
</Field>
<div className="md:col-span-2">
<Field label={t("integrations.spec")}>
<Textarea dir="ltr" className="font-mono text-xs" rows={8} value={form.spec} onChange={set("spec")} />
</Field>
</div>
<Field label={t("integrations.baseUrl")}>
<Input dir="ltr" value={form.base_url} onChange={set("base_url")} />
</Field>
<Field label={t("integrations.sandboxUrl")}>
<Input dir="ltr" value={form.sandbox_base_url} onChange={set("sandbox_base_url")} />
</Field>
<Field label={t("integrations.secretRef")} hint={t("integrations.secretRefHint")}>
<Input dir="ltr" value={form.secret_ref} onChange={set("secret_ref")} autoComplete="off" />
</Field>
<Field label={t("integrations.sandboxSecretRef")}>
<Input dir="ltr" value={form.sandbox_secret_ref} onChange={set("sandbox_secret_ref")} autoComplete="off" />
</Field>
<div className="md:col-span-2">
<Button type="submit" disabled={busy}>
{t("integrations.importButton")}
</Button>
</div>
</form>
);
}
// ------------------------------------------------------------------------------ MCP
function McpTab({ owner }: { owner: boolean }) {
const { t, m } = useI18n();
const conns = useApi<McpConnection[]>("/ext/mcp");
const [form, setForm] = useState({ name: "", url: "", auth_type: "none", secret_ref: "" });
const [changes, setChanges] = useState<McpChange[]>([]);
const connect = async (e: FormEvent) => {
e.preventDefault();
try {
const r = await api<{ report: ImportReport }>("/ext/mcp", {
method: "POST",
body: { ...form, secret_ref: form.secret_ref || null },
});
toast.success(t("integrations.connected", { n: r.report.created.length }));
conns.reload();
} catch (err) {
toast.error(errText(err, t("common.error")));
}
};
const refresh = async (name: string) => {
try {
const r = await api<{ changes: McpChange[] }>(`/ext/mcp/${encodeURIComponent(name)}/refresh`, { method: "POST" });
setChanges(r.changes);
toast.success(t("integrations.refreshed"));
conns.reload();
} catch (err) {
toast.error(errText(err, t("common.error")));
}
};
return (
<div className="space-y-4">
{conns.error && <ErrorState error={conns.error} onRetry={conns.reload} />}
{conns.data?.length === 0 && <p className="text-sm text-muted-foreground">{t("integrations.noMcp")}</p>}
<ul className="space-y-2">
{conns.data?.map((c) => (
<li key={c.id} className="flex flex-wrap items-center gap-3 rounded-lg border bg-card p-3 text-sm" data-testid="mcp-connection">
<span className="font-mono font-medium">{c.name}</span>
<span className="truncate text-muted-foreground" dir="ltr">
{c.url}
</span>
<Badge variant={c.status === "changed" ? "destructive" : "secondary"}>{(m.integrations.mcpStatuses as Record<string, string>)[c.status] ?? c.status}</Badge>
{c.last_diff?.changed?.length ? (
<span className="text-xs text-warning">
{t("integrations.lastDiff")}: {c.last_diff.changed.join(", ")}
</span>
) : null}
{owner && (
<Button size="sm" variant="outline" className="ms-auto" onClick={() => void refresh(c.name)}>
<RefreshCwIcon /> {t("integrations.refresh")}
</Button>
)}
</li>
))}
</ul>
{changes.length > 0 && (
<ul className="space-y-2" data-testid="mcp-changes">
{changes.map((ch) => (
<li key={ch.name} className="rounded-md border border-warning/40 p-3 text-sm">
<p className="font-mono">{ch.name}</p>
<p className="text-xs text-muted-foreground">{t("integrations.before")}: {ch.before.description}</p>
<p className="text-xs">{t("integrations.after")}: {ch.after.description}</p>
</li>
))}
</ul>
)}
{owner && (
<form onSubmit={connect} className="grid gap-4 rounded-lg border bg-card p-4 md:grid-cols-2">
<Field label={t("integrations.name")} hint={t("integrations.nameHint")}>
<Input dir="ltr" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
</Field>
<Field label={t("integrations.url")}>
<Input dir="ltr" type="url" value={form.url} onChange={(e) => setForm({ ...form, url: e.target.value })} required />
</Field>
<Field label={t("integrations.auth")}>
<select
className="h-8 rounded-md border bg-background px-2 text-sm"
value={form.auth_type}
onChange={(e) => setForm({ ...form, auth_type: e.target.value })}
>
<option value="none">{t("integrations.authNone")}</option>
<option value="bearer">{t("integrations.authBearer")}</option>
</select>
</Field>
<Field label={t("integrations.secretRef")} hint={t("integrations.secretRefHint")}>
<Input dir="ltr" value={form.secret_ref} onChange={(e) => setForm({ ...form, secret_ref: e.target.value })} />
</Field>
<div>
<Button type="submit">{t("integrations.connect")}</Button>
</div>
</form>
)}
</div>
);
}
// ----------------------------------------------------------------------- connectors
function toBase64(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const r = new FileReader();
r.onload = () => resolve(String(r.result).split(",", 2)[1] ?? "");
r.onerror = () => reject(r.error);
r.readAsDataURL(file);
});
}
function ConnectorsTab({ owner }: { owner: boolean }) {
const { t } = useI18n();
const list = useApi<Connector[]>("/ext/connectors");
const [form, setForm] = useState({ kind: "table", name: "", config: '{\n "key_column": "sku"\n}', secret_ref: "" });
const create = async (e: FormEvent) => {
e.preventDefault();
let config: unknown;
try {
config = JSON.parse(form.config);
} catch {
toast.error(t("integrations.invalidJson"));
return;
}
try {
await api("/ext/connectors", {
method: "POST",
body: { kind: form.kind, name: form.name, config, secret_ref: form.secret_ref || null },
});
toast.success(t("integrations.created"));
list.reload();
} catch (err) {
toast.error(errText(err, t("common.error")));
}
};
const upload = async (name: string, file: File | undefined) => {
if (!file) return;
try {
const r = await api<{ rows: number }>(`/ext/connectors/${encodeURIComponent(name)}/upload`, {
method: "POST",
body: { filename: file.name, content_base64: await toBase64(file) },
});
toast.success(t("integrations.uploaded", { n: r.rows }));
} catch (err) {
toast.error(errText(err, t("common.error")));
}
};
return (
<div className="space-y-4">
{list.error && <ErrorState error={list.error} onRetry={list.reload} />}
{list.data?.length === 0 && <p className="text-sm text-muted-foreground">{t("integrations.noConnectors")}</p>}
<ul className="space-y-2">
{list.data?.map((c) => (
<li key={c.id} className="flex flex-wrap items-center gap-3 rounded-lg border bg-card p-3 text-sm" data-testid="connector">
<span className="font-mono font-medium">{c.name}</span>
<Badge variant="outline">{c.kind}</Badge>
{owner && c.kind === "table" && (
<label className="ms-auto flex items-center gap-2 text-xs">
{t("integrations.upload")}
<input
type="file"
accept=".csv,.xlsx,text/csv"
onChange={(e) => void upload(c.name, e.target.files?.[0])}
aria-label={`${t("integrations.upload")} ${c.name}`}
/>
</label>
)}
</li>
))}
</ul>
{owner && (
<form onSubmit={create} className="grid gap-4 rounded-lg border bg-card p-4 md:grid-cols-2">
<Field label={t("integrations.kind")}>
<select
className="h-8 rounded-md border bg-background px-2 text-sm"
value={form.kind}
onChange={(e) => setForm({ ...form, kind: e.target.value })}
>
<option value="table">{t("integrations.kinds.table")}</option>
<option value="google_sheets">{t("integrations.kinds.google_sheets")}</option>
<option value="http_action">{t("integrations.kinds.http_action")}</option>
<option value="webhook">{t("integrations.kinds.webhook")}</option>
</select>
</Field>
<Field label={t("integrations.name")} hint={t("integrations.nameHint")}>
<Input dir="ltr" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
</Field>
<div className="md:col-span-2">
<Field label={t("integrations.config")}>
<Textarea dir="ltr" className="font-mono text-xs" rows={6} value={form.config} onChange={(e) => setForm({ ...form, config: e.target.value })} />
</Field>
</div>
<Field label={t("integrations.secretRef")} hint={t("integrations.secretRefHint")}>
<Input dir="ltr" value={form.secret_ref} onChange={(e) => setForm({ ...form, secret_ref: e.target.value })} />
</Field>
<div className="flex items-end">
<Button type="submit">{t("integrations.create")}</Button>
</div>
</form>
)}
</div>
);
}
// ---------------------------------------------------------------------------- page
export function IntegrationsView() {
const { t } = useI18n();
const { hasRole } = useAuth();
const owner = hasRole("owner");
const [tab, setTab] = useState("tools");
const [nonce, setNonce] = useState(0);
return (
<div className="space-y-5">
<PageHeader title={t("integrations.title")} subtitle={t("integrations.subtitle")} />
{!owner && <p className="text-sm text-muted-foreground">{t("integrations.ownerOnly")}</p>}
<Tabs value={tab} onValueChange={setTab}>
<TabsList>
<TabsTrigger value="tools">{t("integrations.tabTools")}</TabsTrigger>
{owner && <TabsTrigger value="import">{t("integrations.tabImport")}</TabsTrigger>}
<TabsTrigger value="mcp">{t("integrations.tabMcp")}</TabsTrigger>
<TabsTrigger value="connectors">{t("integrations.tabConnectors")}</TabsTrigger>
</TabsList>
<TabsContent value="tools">
<ToolsTab key={nonce} owner={owner} />
</TabsContent>
{owner && (
<TabsContent value="import">
<ImportTab
onDone={() => {
setNonce((n) => n + 1);
setTab("tools");
}}
/>
</TabsContent>
)}
<TabsContent value="mcp">
<McpTab owner={owner} />
</TabsContent>
<TabsContent value="connectors">
<ConnectorsTab owner={owner} />
</TabsContent>
</Tabs>
</div>
);
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239"use client";
import { ScaleIcon } from "lucide-react";
import { useState, type FormEvent } from "react";
import { toast } from "sonner";
import { EmptyState, ErrorState, PageHeader } from "@/components/shell/page";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Textarea } from "@/components/ui/textarea";
import { api, ApiError } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { useI18n } from "@/lib/i18n";
import { useApi } from "@/lib/use-api";
import { cn } from "@/lib/utils";
import type { PolicyRuleOut } from "./types";
interface CompileError {
message: string;
errors?: string[];
question?: string | null;
}
function compileError(err: unknown): CompileError | null {
if (!(err instanceof ApiError)) return null;
const d = (err.body as { detail?: unknown } | undefined)?.detail;
if (d && typeof d === "object" && "message" in d) return d as CompileError;
return { message: err.detail };
}
function RuleCard({ rule, children }: { rule: PolicyRuleOut; children?: React.ReactNode }) {
const { t, m } = useI18n();
return (
<article className="space-y-3 rounded-lg border bg-card p-4" data-testid="rule" data-status={rule.status}>
<div className="flex flex-wrap items-center gap-2">
<Badge variant={rule.status === "active" ? "default" : "secondary"}>{(m.nlrules.statuses as Record<string, string>)[rule.status] ?? rule.status}</Badge>
<span className="tabular text-xs text-muted-foreground">{t("nlrules.version", { n: rule.version })}</span>
<span className="text-sm text-muted-foreground">“{rule.text}”</span>
</div>
<p className="text-sm font-medium" data-testid="rule-plain">
{rule.plain}
</p>
{children}
</article>
);
}
function TestsTable({ rule }: { rule: PolicyRuleOut }) {
const { t } = useI18n();
return (
<div className="overflow-x-auto">
<p className="mb-1 text-xs font-medium text-muted-foreground">{t("nlrules.tests")}</p>
<table className="w-full text-sm" data-testid="rule-tests">
<thead className="text-start text-xs text-muted-foreground">
<tr>
<th className="py-1 text-start font-normal">{t("nlrules.call")}</th>
<th className="py-1 text-start font-normal">{t("nlrules.actor")}</th>
<th className="py-1 text-start font-normal">{t("nlrules.outcome")}</th>
</tr>
</thead>
<tbody>
{rule.tests.map((x, i) => (
<tr key={i} className="border-t">
<td className="py-1 font-mono text-xs" dir="ltr">
{x.tool}({Object.entries(x.args).map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(", ")})
</td>
<td className="py-1 text-xs">{x.actor}</td>
<td className={cn("py-1 text-xs", x.matched ? "font-medium text-warning" : "text-muted-foreground")}>
{x.matched ? `${t("nlrules.matched")}: ${x.outcome}` : t("nlrules.notMatched")}
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export function RulesView() {
const { t } = useI18n();
const { hasRole } = useAuth();
const owner = hasRole("owner");
const rules = useApi<PolicyRuleOut[]>("/ext/rules");
const [text, setText] = useState("");
const [draft, setDraft] = useState<PolicyRuleOut | null>(null);
const [problem, setProblem] = useState<CompileError | null>(null);
const [allowPermit, setAllowPermit] = useState(false);
const [busy, setBusy] = useState(false);
const compile = async (e: FormEvent) => {
e.preventDefault();
setBusy(true);
setProblem(null);
setDraft(null);
try {
setDraft(await api<PolicyRuleOut>("/ext/rules/compile", { method: "POST", body: { text } }));
} catch (err) {
setProblem(compileError(err) ?? { message: t("common.error") });
} finally {
setBusy(false);
}
};
const confirm = async () => {
if (!draft) return;
try {
await api(`/ext/rules/${draft.id}/confirm`, { method: "POST", body: { allow_permit: allowPermit } });
toast.success(t("nlrules.confirmed"));
setDraft(null);
setText("");
rules.reload();
} catch (err) {
toast.error(compileError(err)?.message ?? t("common.error"));
}
};
const act = async (rule: PolicyRuleOut, action: "rollback" | "disable") => {
try {
await api(`/ext/rules/${rule.rule_key}/${action}`, { method: "POST" });
toast.success(action === "rollback" ? t("nlrules.rolledBack") : t("nlrules.disabledToast"));
rules.reload();
} catch (err) {
toast.error(compileError(err)?.message ?? t("common.error"));
}
};
const active = rules.data?.filter((r) => r.status === "active") ?? [];
const history = rules.data?.filter((r) => r.status !== "active" && r.status !== "draft") ?? [];
return (
<div className="space-y-6">
<PageHeader title={t("nlrules.title")} subtitle={t("nlrules.subtitle")} />
<form onSubmit={compile} className="space-y-3 rounded-lg border bg-card p-4">
<Textarea
value={text}
onChange={(e) => setText(e.target.value)}
placeholder={t("nlrules.placeholder")}
aria-label={t("nlrules.placeholder")}
rows={2}
minLength={3}
maxLength={500}
required
/>
<Button type="submit" disabled={busy || text.trim().length < 3}>
{t("nlrules.compile")}
</Button>
</form>
{problem && (
<div role="alert" className="rounded-lg border border-warning/40 bg-warning-soft px-4 py-3 text-sm" data-testid="rule-problem">
{problem.question ? (
<>
<p className="font-medium">{t("nlrules.question")}</p>
<p>{problem.question}</p>
</>
) : (
<>
<p className="font-medium">{problem.message}</p>
{problem.errors?.map((e) => (
<p key={e} className="text-xs">
{e}
</p>
))}
</>
)}
</div>
)}
{draft && (
<section aria-label={t("nlrules.draft")} data-testid="rule-draft">
<RuleCard rule={draft}>
<p className="text-xs text-muted-foreground">{t("nlrules.understood")}</p>
<TestsTable rule={draft} />
<details>
<summary className="cursor-pointer text-xs text-muted-foreground">{t("nlrules.policy")}</summary>
<pre dir="ltr" className="mt-2 overflow-x-auto rounded-md bg-muted p-2 text-xs" data-testid="rule-cedar">
{draft.cedar}
</pre>
</details>
{owner ? (
<div className="flex flex-wrap items-center gap-3">
{draft.ast.effect === "permit" && (
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={allowPermit} onChange={(e) => setAllowPermit(e.target.checked)} />
{t("nlrules.allowPermit")}
</label>
)}
<Button onClick={confirm} disabled={draft.ast.effect === "permit" && !allowPermit}>
{t("nlrules.confirm")}
</Button>
</div>
) : (
<p className="text-xs text-muted-foreground">{t("nlrules.ownerOnly")}</p>
)}
</RuleCard>
</section>
)}
<section className="space-y-3">
<h2 className="text-sm font-semibold">{t("nlrules.active")}</h2>
{rules.error && <ErrorState error={rules.error} onRetry={rules.reload} />}
{!rules.data && !rules.error && <Skeleton className="h-24 w-full" />}
{rules.data && active.length === 0 && <EmptyState icon={ScaleIcon} title={t("nlrules.noRules")} />}
{active.map((r) => (
<RuleCard key={r.id} rule={r}>
{owner && (
<div className="flex gap-2">
{r.version > 1 && (
<Button size="sm" variant="outline" onClick={() => void act(r, "rollback")}>
{t("nlrules.rollback")}
</Button>
)}
<Button size="sm" variant="ghost" onClick={() => void act(r, "disable")}>
{t("nlrules.disable")}
</Button>
</div>
)}
</RuleCard>
))}
</section>
{history.length > 0 && (
<section className="space-y-2">
<h2 className="text-sm font-semibold">{t("nlrules.history")}</h2>
<ul className="space-y-1 text-sm text-muted-foreground">
{history.map((r) => (
<li key={r.id}>
<Badge variant="secondary">{r.status}</Badge> {t("nlrules.version", { n: r.version })} — {r.plain}
</li>
))}
</ul>
</section>
)}
</div>
);
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192// API shapes for Phase 16 (runtime extensibility): /ext/* endpoints.
export type ToolMode = "test" | "live";
export interface TenantTool {
id: string;
name: string;
source: "openapi" | "mcp" | "connector" | "http";
source_id: string | null;
kind: string;
description: string;
input_schema: { properties?: Record<string, unknown>; required?: string[] };
suggested_tier: number;
confirmed_tier: number | null;
effective_tier: number;
enabled: boolean;
mode: ToolMode;
secret_ref: string | null;
definition_hash: string;
pinned_hash: string | null;
pending: { description?: string; input_schema?: unknown; definition_hash?: string } | null;
blocked_reason: string | null;
confirmed_at: string | null;
updated_at: string;
config: Record<string, unknown>;
}
export interface ImportReport {
created: string[];
changed: string[];
removed: string[];
unchanged: string[];
}
export interface McpConnection {
id: string;
name: string;
url: string;
auth_type: "none" | "bearer";
secret_ref: string | null;
enabled: boolean;
status: "new" | "ok" | "changed" | "error";
last_refreshed_at: string | null;
last_diff: Partial<ImportReport>;
}
export interface McpChange {
name: string;
pinned_hash: string | null;
new_hash: string | null;
before: { description: string };
after: { description: string };
}
export interface Connector {
id: string;
kind: "google_sheets" | "table" | "webhook" | "http_action";
name: string;
config: Record<string, unknown>;
secret_ref: string | null;
enabled: boolean;
updated_at: string;
}
export interface RuleTest {
tool: string;
args: Record<string, unknown>;
actor: string;
matched: boolean;
outcome: string;
errors: string[];
}
export interface PolicyRuleOut {
id: string;
rule_key: string;
version: number;
status: "draft" | "active" | "superseded" | "rolled_back" | "disabled" | "discarded";
text: string;
plain: string;
cedar: string;
ast: { effect: "require_approval" | "forbid" | "permit"; tools: string[] };
tests: RuleTest[];
created_at: string;
confirmed_at: string | null;
}
export interface GatewayOutcomeOut {
status: string;
reason: string | null;
result: { ok: boolean; data: unknown; error: string | null } | null;
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329"use client";
import {
CheckIcon,
ClockIcon,
KeyRoundIcon,
Loader2Icon,
MessageSquareReplyIcon,
PencilIcon,
ShieldIcon,
XIcon,
} from "lucide-react";
import Link from "next/link";
import { useState, type FormEvent } from "react";
import { toast } from "sonner";
import { ArgsTable, DiffView, FactsList } from "@/components/inbox/diff-view";
import { EditArgsForm } from "@/components/inbox/edit-args-form";
import { useStepUp } from "@/components/inbox/stepup";
import { UndoCountdown } from "@/components/inbox/undo-countdown";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { ApiError } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { decide, type DecideInput } from "@/lib/decide";
import { formatDuration, toolLabel } from "@/lib/format";
import { useI18n } from "@/lib/i18n";
import type { ApprovalItem, DecisionResult, Role } from "@/lib/types";
import { cn } from "@/lib/utils";
import { useNow } from "@/lib/use-now";
export function WaitTime({ item }: { item: Pick<ApprovalItem, "created_at" | "wait_seconds"> }) {
const { t } = useI18n();
const now = useNow(1000);
const created = new Date(item.created_at).getTime();
const secs = Number.isNaN(created) ? item.wait_seconds : (now - created) / 1000;
const tone =
secs > 4 * 3600 ? "text-destructive" : secs > 30 * 60 ? "text-warning" : "text-muted-foreground";
return (
<span className={cn("inline-flex items-center gap-1 text-xs", tone)} data-testid="wait-time">
<ClockIcon className="size-3.5" aria-hidden />
<span className="tabular">{t("inbox.waiting", { time: formatDuration(secs) })}</span>
</span>
);
}
export function KindBadge({ kind }: { kind: string | undefined }) {
const { t } = useI18n();
const k = (kind ?? "review") as "review" | "question" | "notify";
const label = t(`inbox.kind.${k}` as "inbox.kind.review") ?? k;
return (
<Badge variant="outline" className="font-normal">
{label}
</Badge>
);
}
type Mode = null | "edit" | "reject" | "respond";
export function ApprovalCard({
item,
selected,
onSelectedChange,
selectable,
onDecided,
}: {
item: ApprovalItem;
selected?: boolean;
selectable?: boolean;
onSelectedChange?: (v: boolean) => void;
onDecided: (item: ApprovalItem, decision: DecideInput["decision"], r: DecisionResult) => void;
}) {
const { t, m } = useI18n();
const { hasRole } = useAuth();
const requestStepUp = useStepUp();
const [mode, setMode] = useState<Mode>(null);
const [busy, setBusy] = useState<DecideInput["decision"] | null>(null);
const [note, setNote] = useState("");
const canApprove = hasRole(item.required_role);
const roleLabel = m.settings.roles[item.required_role as Role] ?? item.required_role;
const run = async (input: DecideInput) => {
setBusy(input.decision);
try {
const r = await decide(item, input, requestStepUp);
if (!r) return; // step-up cancelled
setMode(null);
setNote("");
onDecided(item, input.decision, r);
} catch (e) {
toast.error(e instanceof ApiError ? e.detail : t("common.error"));
} finally {
setBusy(null);
}
};
const submitNote = (e: FormEvent, decision: "reject" | "respond") => {
e.preventDefault();
void run({ decision, note: note.trim() || undefined });
};
const title = toolLabel(item.tool);
return (
<article
aria-labelledby={`approval-${item.id}-title`}
data-testid="approval-card"
data-approval-id={item.id}
data-tool={item.tool}
className={cn(
"rounded-lg border bg-card shadow-xs transition-colors",
selected && "border-primary/50 ring-1 ring-primary/30",
)}
>
<header className="flex flex-wrap items-start gap-3 border-b px-4 py-3">
{selectable && (
<Checkbox
className="mt-1"
checked={selected}
onCheckedChange={(v) => onSelectedChange?.(v === true)}
aria-label={`${t("inbox.selectAll")}: ${title}`}
data-testid="approval-select"
/>
)}
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<h3 id={`approval-${item.id}-title`} className="text-[15px] font-semibold">
{title}
</h3>
<code dir="ltr" className="font-mono text-xs text-muted-foreground">
{item.tool}
</code>
<KindBadge kind={item.kind} />
{item.risk_tier !== undefined && item.risk_tier !== null && (
<Badge variant="secondary" className="font-normal">
{t("inbox.tier", { n: item.risk_tier })}
</Badge>
)}
</div>
<p className="mt-1 text-sm text-muted-foreground">{item.reason}</p>
</div>
<div className="flex flex-col items-end gap-1">
<WaitTime item={item} />
<div className="flex flex-wrap justify-end gap-1.5">
<Badge variant="outline" className="gap-1 font-normal" data-testid="required-role">
<ShieldIcon aria-hidden />
{t("inbox.requiredRole")}: {roleLabel}
</Badge>
{item.requires_stepup && (
<Badge
className="gap-1 border-warning/40 bg-warning-soft font-normal text-warning"
variant="outline"
data-testid="stepup-required"
>
<KeyRoundIcon aria-hidden />
{t("inbox.stepup")}
</Badge>
)}
</div>
</div>
</header>
<div className="grid gap-5 px-4 py-4 lg:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]">
<div className="min-w-0 space-y-4">
<section className="space-y-2">
<h4 className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
{t("inbox.change")}
</h4>
<DiffView preview={item.preview} />
</section>
<section className="space-y-2">
<h4 className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
{t("inbox.args")}
</h4>
<ArgsTable args={item.args} provenance={item.provenance} />
</section>
</div>
<aside className="min-w-0 space-y-4">
{item.policy_rule && (
<section className="space-y-1">
<h4 className="text-xs font-medium text-muted-foreground">{t("inbox.policyRule")}</h4>
<code
dir="ltr"
className="block rounded bg-muted px-2 py-1 font-mono text-xs break-all"
data-testid="policy-rule"
>
{item.policy_rule}
</code>
</section>
)}
<FactsList facts={item.facts ?? {}} args={item.args} />
<UndoCountdown approvalId={item.id} sendAfter={item.send_after} undoUrl={item.undo_url} />
</aside>
</div>
<footer className="flex flex-wrap items-center gap-2 border-t bg-muted/30 px-4 py-3">
<Button
onClick={() => run({ decision: "approve" })}
disabled={!canApprove || busy !== null}
data-testid="approve"
>
{busy === "approve" ? <Loader2Icon className="animate-spin" /> : <CheckIcon />}
{t("inbox.approve")}
</Button>
<Button
variant="outline"
onClick={() => setMode("edit")}
disabled={!canApprove || busy !== null}
data-testid="edit"
>
<PencilIcon />
{t("inbox.edit")}
</Button>
<Button
variant="outline"
className="text-destructive hover:text-destructive"
onClick={() => setMode("reject")}
disabled={busy !== null}
data-testid="reject"
>
<XIcon />
{t("inbox.reject")}
</Button>
<Button
variant="ghost"
onClick={() => setMode("respond")}
disabled={busy !== null}
data-testid="respond"
>
<MessageSquareReplyIcon />
{t("inbox.respond")}
</Button>
{!canApprove && (
<span className="text-xs text-muted-foreground">
{t("inbox.roleTooLow", { role: roleLabel })}
</span>
)}
{item.run_id && (
<Link
href={`/runs/${item.run_id}`}
className="ms-auto text-xs text-muted-foreground underline-offset-4 hover:underline"
>
{t("inbox.viewRun")}
</Link>
)}
</footer>
<Dialog open={mode === "edit"} onOpenChange={(o) => !o && setMode(null)}>
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">
<DialogHeader>
<DialogTitle>{t("inbox.editTitle")}</DialogTitle>
<DialogDescription>{t("inbox.editHint")}</DialogDescription>
</DialogHeader>
{mode === "edit" && (
<EditArgsForm
tool={item.tool}
args={item.args}
schema={item.args_schema}
provenance={item.provenance}
busy={busy !== null}
onCancel={() => setMode(null)}
onSubmit={(edited) => run({ decision: "edit", edited_args: edited })}
/>
)}
</DialogContent>
</Dialog>
<Dialog
open={mode === "reject" || mode === "respond"}
onOpenChange={(o) => !o && setMode(null)}
>
<DialogContent className="sm:max-w-md">
<form
className="space-y-4"
onSubmit={(e) => submitNote(e, mode === "respond" ? "respond" : "reject")}
>
<DialogHeader>
<DialogTitle>
{mode === "respond" ? t("inbox.respondTitle") : t("inbox.rejectTitle")}
</DialogTitle>
<DialogDescription>
{mode === "respond" ? t("inbox.respondHint") : item.reason}
</DialogDescription>
</DialogHeader>
<div className="space-y-2">
<Label htmlFor={`note-${item.id}`}>
{mode === "respond" ? t("inbox.respond") : t("inbox.rejectReason")}
</Label>
<Textarea
id={`note-${item.id}`}
value={note}
onChange={(e) => setNote(e.target.value)}
placeholder={mode === "respond" ? t("inbox.respondPlaceholder") : ""}
maxLength={2000}
rows={4}
required={mode === "respond"}
autoFocus
/>
</div>
<DialogFooter>
<Button type="button" variant="ghost" onClick={() => setMode(null)}>
{t("common.cancel")}
</Button>
<Button
type="submit"
variant={mode === "reject" ? "destructive" : "default"}
disabled={busy !== null || (mode === "respond" && !note.trim())}
data-testid="confirm-note"
>
{busy && <Loader2Icon className="animate-spin" />}
{mode === "respond" ? t("inbox.respond") : t("inbox.reject")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</article>
);
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198"use client";
import { ArrowRightIcon } from "lucide-react";
import { ProvenanceBadge } from "@/components/inbox/provenance-badge";
import { previewDiff } from "@/lib/diff";
import { formatMoney, formatValue, humanize, isMoneyField } from "@/lib/format";
import { useI18n } from "@/lib/i18n";
import type { Provenance } from "@/lib/types";
import { cn } from "@/lib/utils";
function Value({ field, value, muted }: { field: string; value: unknown; muted?: boolean }) {
const { locale } = useI18n();
return (
<span
dir="ltr"
className={cn(
"tabular break-all",
typeof value === "string" && !isMoneyField(field) ? "font-mono text-[13px]" : "",
muted && "text-muted-foreground",
)}
>
{formatValue(field, value, locale)}
</span>
);
}
/** Structured before → after of the tool's dry run: what will actually change. */
export function DiffView({ preview }: { preview: Record<string, unknown> }) {
const { t } = useI18n();
const { rows, details } = previewDiff(preview);
if (!rows.length && !details.length) {
return <p className="text-sm text-muted-foreground">{t("inbox.noPreview")}</p>;
}
return (
<div className="space-y-3">
{rows.length > 0 && (
<div className="overflow-hidden rounded-md border" data-testid="diff">
<table className="w-full text-sm">
<thead className="bg-muted/60 text-xs text-muted-foreground">
<tr>
<th className="px-3 py-1.5 text-start font-medium">{t("inbox.field")}</th>
<th className="px-3 py-1.5 text-start font-medium">{t("inbox.before")}</th>
<th className="w-6" aria-hidden />
<th className="px-3 py-1.5 text-start font-medium">{t("inbox.after")}</th>
</tr>
</thead>
<tbody>
{rows.map((r) => (
<tr
key={r.field}
data-testid={`diff-${r.field}`}
data-changed={r.changed}
className="border-t"
>
<td className="px-3 py-2 text-muted-foreground">{humanize(r.field)}</td>
<td className="px-3 py-2">
{r.hasBefore ? (
<span className={cn(r.changed && "line-through decoration-destructive/60")}>
<Value field={r.field} value={r.before} muted />
</span>
) : (
<span className="text-muted-foreground">—</span>
)}
</td>
<td className="text-muted-foreground" aria-hidden>
<ArrowRightIcon className="size-3.5 rtl:rotate-180" />
</td>
<td className="px-3 py-2">
<span
className={cn(
"rounded px-1 py-0.5 font-medium",
r.changed && "bg-accent text-accent-foreground",
)}
>
<Value field={r.field} value={r.after} />
</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{details.length > 0 && (
<dl className="grid grid-cols-[minmax(7rem,auto)_1fr] gap-x-4 gap-y-1 text-sm">
{details.map(([k, v]) => (
<div key={k} className="contents">
<dt className="text-muted-foreground">{humanize(k)}</dt>
<dd className="min-w-0 whitespace-pre-wrap">
<Value field={k} value={v} />
</dd>
</div>
))}
</dl>
)}
</div>
);
}
/** The exact arguments the tool will run with, each with where it came from. */
export function ArgsTable({
args,
provenance,
}: {
args: Record<string, unknown>;
provenance: Record<string, Provenance>;
}) {
const { t } = useI18n();
return (
<div className="overflow-hidden rounded-md border" data-testid="args">
<table className="w-full text-sm">
<thead className="bg-muted/60 text-xs text-muted-foreground">
<tr>
<th className="px-3 py-1.5 text-start font-medium">{t("inbox.field")}</th>
<th className="px-3 py-1.5 text-start font-medium">{t("inbox.value")}</th>
<th className="px-3 py-1.5 text-end font-medium">{t("inbox.source")}</th>
</tr>
</thead>
<tbody>
{Object.entries(args).map(([k, v]) => (
<tr
key={k}
className={cn("border-t", provenance[k] === "untrusted" && "bg-warning-soft/40")}
>
<td className="px-3 py-2 align-top font-mono text-[12px] text-muted-foreground" dir="ltr">
{k}
</td>
<td className="px-3 py-2 align-top" data-testid={`arg-${k}`}>
<Value field={k} value={v} />
</td>
<td className="px-3 py-2 text-end align-top">
<ProvenanceBadge value={provenance[k]} field={k} />
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
/** Live facts from the system of record (what the policy compared against). */
export function FactsList({
facts,
args,
}: {
facts: Record<string, unknown>;
args: Record<string, unknown>;
}) {
const { t, locale } = useI18n();
const entries = Object.entries(facts);
if (!entries.length) return null;
const amount = typeof args.amount === "number" ? args.amount : null;
const total = typeof facts.order_total === "number" ? facts.order_total : null;
return (
<div className="rounded-md border border-dashed p-3" data-testid="facts">
<div className="mb-2 flex items-center justify-between gap-2">
<h4 className="text-xs font-medium text-muted-foreground">{t("inbox.facts")}</h4>
<ProvenanceBadge value="trusted" />
</div>
{amount !== null && total !== null && total > 0 && (
<div className="mb-3 space-y-1">
<p className="text-sm" dir="ltr">
<span className="tabular font-medium">
{t("inbox.totalOnOrder", {
amount: formatMoney(amount, locale),
total: formatMoney(total, locale),
})}
</span>
</p>
<div
className="h-1.5 overflow-hidden rounded-full bg-muted"
role="meter"
aria-valuemin={0}
aria-valuemax={total}
aria-valuenow={amount}
>
<div
className={cn("h-full rounded-full", amount > total ? "bg-destructive" : "bg-primary")}
style={{ width: `${Math.min(100, (amount / total) * 100)}%` }}
/>
</div>
</div>
)}
<dl className="grid grid-cols-[minmax(7rem,auto)_1fr] gap-x-4 gap-y-1 text-sm">
{entries.map(([k, v]) => (
<div key={k} className="contents">
<dt className="text-muted-foreground">{humanize(k)}</dt>
<dd data-testid={`fact-${k}`}>
<Value field={k} value={v} />
</dd>
</div>
))}
</dl>
</div>
);
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226"use client";
import { useMemo, useState, type FormEvent } from "react";
import { ProvenanceBadge } from "@/components/inbox/provenance-badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { argsChanges } from "@/lib/diff";
import { formatValue, humanize } from "@/lib/format";
import { translate, useI18n, type MessageKey } from "@/lib/i18n";
import { en } from "@/lib/i18n/messages";
import type { ArgsSchema, JsonSchemaProp, Provenance } from "@/lib/types";
type FieldKind = "integer" | "number" | "boolean" | "string" | "enum" | "json";
function kindOf(prop: JsonSchemaProp | undefined, value: unknown): FieldKind {
const p = prop?.anyOf?.find((x) => x.type && x.type !== "null") ?? prop;
if (p?.enum) return "enum";
if (p?.type === "integer") return "integer";
if (p?.type === "number") return "number";
if (p?.type === "boolean") return "boolean";
if (p?.type === "string") return "string";
if (typeof value === "number") return Number.isInteger(value) ? "integer" : "number";
if (typeof value === "boolean") return "boolean";
if (typeof value === "string") return "string";
return "json";
}
/** Client-side checks mirror the JSON schema; the server validates again (and re-runs policy
* and a dry run) before the edited call is approved. */
export function validateField(
prop: JsonSchemaProp | undefined,
v: unknown,
t: (key: MessageKey, vars?: Record<string, string | number>) => string = (k, vars) => translate(en, k, vars),
): string | null {
const p = prop?.anyOf?.find((x) => x.type && x.type !== "null") ?? prop;
if (!p) return null;
if (typeof v === "number") {
if (Number.isNaN(v)) return t("validation.number");
if (p.type === "integer" && !Number.isInteger(v)) return t("validation.wholeNumber");
if (p.exclusiveMinimum !== undefined && v <= p.exclusiveMinimum)
return t("validation.greaterThan", { n: p.exclusiveMinimum });
if (p.minimum !== undefined && v < p.minimum) return t("validation.atLeast", { n: p.minimum });
if (p.maximum !== undefined && v > p.maximum) return t("validation.atMost", { n: p.maximum });
}
if (typeof v === "string") {
if (p.maxLength !== undefined && v.length > p.maxLength)
return t("validation.maxChars", { n: p.maxLength });
if (p.minLength !== undefined && v.length < p.minLength)
return t("validation.minChars", { n: p.minLength });
if (p.pattern && !new RegExp(p.pattern).test(v)) return t("validation.pattern", { pattern: p.pattern });
}
return null;
}
/** A form generated from the tool's argument schema. The tool itself is fixed: only values
* can change, and the edited call goes back through policy and a dry run. */
export function EditArgsForm({
tool,
args,
schema,
provenance,
busy,
onSubmit,
onCancel,
}: {
tool: string;
args: Record<string, unknown>;
schema: ArgsSchema | undefined;
provenance: Record<string, Provenance>;
busy?: boolean;
onSubmit: (edited: Record<string, unknown>) => void;
onCancel: () => void;
}) {
const { t, locale } = useI18n();
const props = useMemo(() => schema?.properties ?? {}, [schema]);
const fields = useMemo(
() => Array.from(new Set([...Object.keys(props), ...Object.keys(args)])),
[props, args],
);
const [values, setValues] = useState<Record<string, unknown>>(() => ({ ...args }));
const [raw, setRaw] = useState<Record<string, string>>({});
const errors = Object.fromEntries(
fields.map((f) => [f, raw[f] === "__invalid__" ? t("validation.invalidJson") : validateField(props[f], values[f], t)]),
);
const changes = argsChanges(args, values);
const valid = Object.values(errors).every((e) => !e);
const set = (f: string, v: unknown) => setValues((prev) => ({ ...prev, [f]: v }));
const submit = (e: FormEvent) => {
e.preventDefault();
if (valid && changes.length) onSubmit(values);
};
return (
<form onSubmit={submit} className="space-y-4" data-testid="edit-form">
<div className="flex items-center gap-2 rounded-md bg-muted px-3 py-2 text-sm">
<span className="text-muted-foreground">{t("runs.intent")}:</span>
<code dir="ltr" className="font-mono text-[13px]" data-testid="edit-tool">
{tool}
</code>
</div>
{fields.map((f) => {
const prop = props[f];
const kind = kindOf(prop, args[f]);
const id = `edit-${f}`;
const err = errors[f];
return (
<div key={f} className="space-y-1.5">
<div className="flex items-center justify-between gap-2">
<Label htmlFor={id}>{prop?.title ?? humanize(f)}</Label>
<ProvenanceBadge value={provenance[f]} />
</div>
{kind === "boolean" ? (
<Switch
id={id}
checked={Boolean(values[f])}
onCheckedChange={(c) => set(f, c)}
/>
) : kind === "enum" ? (
<select
id={id}
className="h-9 w-full rounded-md border bg-transparent px-2 text-sm"
value={String(values[f] ?? "")}
onChange={(e) => set(f, e.target.value)}
>
{(prop?.enum ?? []).map((o) => (
<option key={String(o)} value={String(o)}>
{String(o)}
</option>
))}
</select>
) : kind === "integer" || kind === "number" ? (
<Input
id={id}
name={f}
dir="ltr"
type="number"
inputMode={kind === "integer" ? "numeric" : "decimal"}
step={kind === "integer" ? 1 : "any"}
value={values[f] === undefined || values[f] === null ? "" : String(values[f])}
onChange={(e) => set(f, e.target.value === "" ? null : Number(e.target.value))}
aria-invalid={Boolean(err)}
className="tabular"
/>
) : kind === "string" && (prop?.maxLength ?? 0) > 200 ? (
<Textarea
id={id}
name={f}
value={String(values[f] ?? "")}
onChange={(e) => set(f, e.target.value)}
aria-invalid={Boolean(err)}
rows={4}
/>
) : kind === "string" ? (
<Input
id={id}
name={f}
value={String(values[f] ?? "")}
onChange={(e) => set(f, e.target.value)}
aria-invalid={Boolean(err)}
/>
) : (
<Textarea
id={id}
name={f}
dir="ltr"
className="font-mono text-xs"
defaultValue={JSON.stringify(args[f], null, 2)}
onChange={(e) => {
try {
set(f, JSON.parse(e.target.value));
setRaw((r) => ({ ...r, [f]: "" }));
} catch {
setRaw((r) => ({ ...r, [f]: "__invalid__" }));
}
}}
/>
)}
{err ? (
<p className="text-xs text-destructive" role="alert">
{err}
</p>
) : prop?.description ? (
<p className="text-xs text-muted-foreground">{prop.description}</p>
) : null}
</div>
);
})}
<div className="rounded-md border p-3">
<p className="mb-1 text-xs font-medium text-muted-foreground">{t("inbox.editChanges")}</p>
{changes.length ? (
<ul className="space-y-0.5 text-sm" data-testid="edit-changes">
{changes.map((c) => (
<li key={c.field} dir="ltr" className="tabular">
<span className="text-muted-foreground">{c.field}: </span>
<span className="line-through decoration-destructive/60">
{formatValue(c.field, c.before, locale)}
</span>
{" → "}
<span className="font-medium">{formatValue(c.field, c.after, locale)}</span>
</li>
))}
</ul>
) : (
<p className="text-sm text-muted-foreground">{t("inbox.noChanges")}</p>
)}
</div>
<div className="flex justify-end gap-2">
<Button type="button" variant="ghost" onClick={onCancel}>
{t("common.cancel")}
</Button>
<Button type="submit" disabled={!valid || !changes.length || busy}>
{t("inbox.approveEdited")}
</Button>
</div>
</form>
);
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227"use client";
import { CheckCheckIcon, InboxIcon, Loader2Icon, RefreshCwIcon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import { ApprovalCard } from "@/components/inbox/approval-card";
import { useStepUp } from "@/components/inbox/stepup";
import { UndoCountdown } from "@/components/inbox/undo-countdown";
import { EmptyState, ErrorState, PageHeader } from "@/components/shell/page";
import { RunStatusBadge } from "@/components/runs/status-badge";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Skeleton } from "@/components/ui/skeleton";
import { ApiError } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { decide } from "@/lib/decide";
import { formatDateTime, toolLabel } from "@/lib/format";
import { useI18n } from "@/lib/i18n";
import type { ApprovalItem, Decision, DecisionResult } from "@/lib/types";
import { useApi } from "@/lib/use-api";
const DONE_KEY: Record<Decision, "inbox.approved" | "inbox.rejected" | "inbox.edited" | "inbox.responded"> = {
approve: "inbox.approved",
reject: "inbox.rejected",
edit: "inbox.edited",
respond: "inbox.responded",
};
export function InboxView() {
const { t, m, locale } = useI18n();
const router = useRouter();
const { hasRole } = useAuth();
const requestStepUp = useStepUp();
const pending = useApi<ApprovalItem[]>("/inbox", { query: { status: "pending" }, pollMs: 10_000 });
const history = useApi<ApprovalItem[]>("/inbox", {
query: { status: "decided", limit: 20 },
pollMs: 15_000,
});
const [hidden, setHidden] = useState<Set<string>>(new Set());
const [selected, setSelected] = useState<Set<string>>(new Set());
const [bulkBusy, setBulkBusy] = useState(false);
const items = useMemo(
() => (pending.data ?? []).filter((i) => !hidden.has(i.id)),
[pending.data, hidden],
);
const eligible = items.filter((i) => hasRole(i.required_role));
const chosen = eligible.filter((i) => selected.has(i.id));
const refresh = () => {
pending.reload();
history.reload();
};
const onDecided = (item: ApprovalItem, decision: Decision, r: DecisionResult) => {
setHidden((s) => new Set(s).add(item.id));
setSelected((s) => {
const n = new Set(s);
n.delete(item.id);
return n;
});
const runStatus = r.run?.status;
toast.success(t(DONE_KEY[decision]), {
description: runStatus
? t("inbox.runResult", {
status: m.runs.statuses[runStatus as keyof typeof m.runs.statuses] ?? runStatus,
})
: toolLabel(item.tool),
action: r.run?.run_id
? { label: t("inbox.viewRun"), onClick: () => router.push(`/runs/${r.run?.run_id}`) }
: undefined,
});
refresh();
};
const toggle = (id: string, v: boolean) =>
setSelected((s) => {
const n = new Set(s);
if (v) n.add(id);
else n.delete(id);
return n;
});
const allChosen = eligible.length > 0 && chosen.length === eligible.length;
const bulkApprove = async () => {
setBulkBusy(true);
let ok = 0;
const failed: string[] = [];
try {
// One step-up covers the batch (the token is valid for a few minutes).
if (chosen.some((i) => i.requires_stepup) && !(await requestStepUp())) return;
for (const item of chosen) {
try {
const r = await decide(item, { decision: "approve" }, requestStepUp);
if (r) {
ok += 1;
setHidden((s) => new Set(s).add(item.id));
}
} catch (e) {
failed.push(`${toolLabel(item.tool)}: ${e instanceof ApiError ? e.detail : t("common.error")}`);
}
}
setSelected(new Set());
if (ok) toast.success(`${t("inbox.approved")} (${ok})`);
if (failed.length) toast.error(failed.join("\n"));
refresh();
} finally {
setBulkBusy(false);
}
};
return (
<div className="space-y-6">
<PageHeader
title={t("inbox.title")}
subtitle={t("inbox.subtitle")}
actions={
<Button variant="outline" size="sm" onClick={refresh} aria-label={t("common.refresh")}>
<RefreshCwIcon />
{t("common.refresh")}
</Button>
}
/>
{items.length > 1 && (
<div
className="sticky top-14 z-10 flex flex-wrap items-center gap-3 rounded-lg border bg-card/95 px-4 py-2 shadow-xs backdrop-blur"
data-testid="bulk-bar"
>
<label className="flex items-center gap-2 text-sm">
<Checkbox
checked={allChosen ? true : chosen.length ? "indeterminate" : false}
onCheckedChange={(v) =>
setSelected(v === true ? new Set(eligible.map((i) => i.id)) : new Set())
}
data-testid="select-all"
/>
{t("inbox.selectAll")}
</label>
<span className="text-sm text-muted-foreground" data-testid="selected-count">
{t("inbox.selected", { n: chosen.length })}
</span>
<Button
size="sm"
className="ms-auto"
onClick={bulkApprove}
disabled={!chosen.length || bulkBusy}
data-testid="bulk-approve"
>
{bulkBusy ? <Loader2Icon className="animate-spin" /> : <CheckCheckIcon />}
{t("inbox.approveSelected", { n: chosen.length })}
</Button>
</div>
)}
<section aria-label={t("inbox.title")} className="space-y-4">
{pending.error && !pending.data ? (
<ErrorState error={pending.error} onRetry={pending.reload} />
) : pending.loading && !pending.data ? (
<div className="space-y-4">
<Skeleton className="h-64 w-full" />
<Skeleton className="h-64 w-full" />
</div>
) : items.length === 0 ? (
<EmptyState icon={InboxIcon} title={t("inbox.empty")} hint={t("inbox.emptyHint")} />
) : (
items.map((item) => (
<ApprovalCard
key={item.id}
item={item}
selectable={items.length > 1 && hasRole(item.required_role)}
selected={selected.has(item.id)}
onSelectedChange={(v) => toggle(item.id, v)}
onDecided={onDecided}
/>
))
)}
</section>
<section className="space-y-3" aria-labelledby="history-title">
<h2 id="history-title" className="text-sm font-semibold">
{t("inbox.history")}
</h2>
{(history.data ?? []).length === 0 ? (
<p className="text-sm text-muted-foreground">{t("inbox.noHistory")}</p>
) : (
<ul className="divide-y rounded-lg border bg-card" data-testid="history">
{(history.data ?? []).map((h) => (
<li key={h.id} className="space-y-2 px-4 py-3">
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">{toolLabel(h.tool)}</span>
<RunStatusBadge status={h.status} />
{h.decision_note && (
<span className="truncate text-muted-foreground">“{h.decision_note}”</span>
)}
<span className="ms-auto text-xs text-muted-foreground">
{formatDateTime(h.decided_at ?? h.created_at, locale)}
</span>
{h.run_id && (
<Link
href={`/runs/${h.run_id}`}
className="text-xs text-muted-foreground underline-offset-4 hover:underline"
>
{t("inbox.viewRun")}
</Link>
)}
</div>
{h.send_after && (
<UndoCountdown
approvalId={h.id}
sendAfter={h.send_after}
undoUrl={h.undo_url}
onUndone={history.reload}
/>
)}
</li>
))}
</ul>
)}
</section>
</div>
);
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ApprovalCard } from "@/components/inbox/approval-card";
import { ArgsTable, DiffView, FactsList } from "@/components/inbox/diff-view";
import { InboxView } from "@/components/inbox/inbox-view";
import { ProvenanceBadge } from "@/components/inbox/provenance-badge";
import { UndoCountdown } from "@/components/inbox/undo-countdown";
import { setAccessToken } from "@/lib/session";
import { cancelItem, mockFetch, refundItem } from "@/test/fixtures";
import { renderUi } from "@/test/render";
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
usePathname: () => "/inbox",
}));
afterEach(() => {
vi.unstubAllGlobals();
vi.useRealTimers();
setAccessToken(null);
});
async function authed() {
// Wait for AuthProvider's silent refresh + /me, so role checks pass.
await waitFor(() => expect(screen.getByTestId("approve")).toBeEnabled());
}
describe("ProvenanceBadge", () => {
it("marks untrusted values distinctly, with an accessible explanation", () => {
mockFetch();
renderUi(
<>
<ProvenanceBadge value="untrusted" field="amount" />
<ProvenanceBadge value="trusted" field="order" />
</>,
);
const u = screen.getByTestId("provenance-amount");
expect(u).toHaveAttribute("data-provenance", "untrusted");
expect(u).toHaveTextContent("Untrusted");
expect(u).toHaveAccessibleName(/untrusted content/i);
expect(screen.getByTestId("provenance-order")).toHaveTextContent("Trusted");
});
it("speaks Urdu", () => {
mockFetch();
renderUi(<ProvenanceBadge value="untrusted" field="amount" />, { locale: "ur" });
expect(screen.getByTestId("provenance-amount")).toHaveTextContent("غیر مصدقہ");
});
});
describe("DiffView / ArgsTable / FactsList", () => {
it("shows before → after with money formatting", () => {
mockFetch();
renderUi(<DiffView preview={refundItem().preview} />);
const row = screen.getByTestId("diff-refunded");
expect(row).toHaveAttribute("data-changed", "true");
expect(row).toHaveTextContent("Rs 0");
expect(row).toHaveTextContent("Rs 20,000");
});
it("lists exact args with a provenance badge per value", () => {
mockFetch();
const item = cancelItem({ provenance: { order_number: "trusted" } });
renderUi(<ArgsTable args={{ ...item.args, note: "x" }} provenance={{ ...item.provenance, note: "untrusted" }} />);
expect(screen.getByTestId("arg-order_number")).toHaveTextContent("ORD-1001");
expect(screen.getByTestId("provenance-order_number")).toHaveAttribute("data-provenance", "trusted");
expect(screen.getByTestId("provenance-note")).toHaveAttribute("data-provenance", "untrusted");
});
it("puts the amount against the order total", () => {
mockFetch();
const item = refundItem();
renderUi(<FactsList facts={item.facts!} args={item.args} />);
expect(screen.getByTestId("facts")).toHaveTextContent("Rs 20,000 of Rs 25,000 order total");
expect(screen.getByRole("meter")).toHaveAttribute("aria-valuenow", "20000");
});
});
describe("ApprovalCard", () => {
it("approves without step-up and reports the run outcome", async () => {
const { calls } = mockFetch({
"POST /approvals/a-cancel/decision": () => ({
approval: cancelItem({ status: "approved" }),
replacement_id: null,
run: { run_id: "r1", status: "completed", output: null },
}),
});
const onDecided = vi.fn();
renderUi(<ApprovalCard item={cancelItem()} onDecided={onDecided} />);
await authed();
await userEvent.click(screen.getByTestId("approve"));
await waitFor(() => expect(onDecided).toHaveBeenCalled());
const call = calls.find((c) => c.path === "/approvals/a-cancel/decision")!;
expect(call.body).toEqual({ decision: "approve" });
expect(call.headers["X-Stepup-Token"]).toBeUndefined();
expect(onDecided.mock.calls[0][1]).toBe("approve");
});
it("asks for step-up before approving a high-value refund and sends the token", async () => {
const { calls } = mockFetch({
"POST /auth/stepup": () => ({ stepup_token: "step-tok" }),
"POST /approvals/a-refund/decision": () => ({
approval: refundItem({ status: "approved" }),
replacement_id: null,
run: null,
}),
});
const onDecided = vi.fn();
renderUi(<ApprovalCard item={refundItem()} onDecided={onDecided} />);
await authed();
expect(screen.getByTestId("stepup-required")).toBeInTheDocument();
await userEvent.click(screen.getByTestId("approve"));
const dialog = await screen.findByTestId("stepup-dialog");
await userEvent.type(within(dialog).getByLabelText("6-digit code"), "123456");
await userEvent.click(within(dialog).getByRole("button", { name: /verify/i }));
await waitFor(() => expect(onDecided).toHaveBeenCalled());
expect(calls.find((c) => c.path === "/auth/stepup")!.body).toEqual({ code: "123456" });
const decision = calls.find((c) => c.path === "/approvals/a-refund/decision")!;
expect(decision.headers["X-Stepup-Token"]).toBe("step-tok");
});
it("edits values (never the tool) and sends edited_args", async () => {
const { calls } = mockFetch({
"POST /auth/stepup": () => ({ stepup_token: "step-tok" }),
"POST /approvals/a-refund/decision": () => ({
approval: refundItem({ status: "edited" }),
replacement_id: "a2",
run: { run_id: "r1", status: "completed", output: "ok" },
}),
});
const onDecided = vi.fn();
renderUi(<ApprovalCard item={refundItem()} onDecided={onDecided} />);
await authed();
await userEvent.click(screen.getByTestId("edit"));
const form = await screen.findByTestId("edit-form");
expect(within(form).getByTestId("edit-tool")).toHaveTextContent("demo.refund_order");
expect(within(form).queryByLabelText(/tool/i)).toBeNull();
const submit = within(form).getByRole("button", { name: "Approve edited call" });
expect(submit).toBeDisabled(); // nothing changed yet
const amount = within(form).getByLabelText("Amount");
fireEvent.change(amount, { target: { value: "0" } });
expect(within(form).getByRole("alert")).toHaveTextContent(/greater than 0/);
expect(submit).toBeDisabled();
fireEvent.change(amount, { target: { value: "15000" } });
expect(within(form).getByTestId("edit-changes")).toHaveTextContent("Rs 20,000 → Rs 15,000");
await userEvent.click(submit);
const dialog = await screen.findByTestId("stepup-dialog");
await userEvent.type(within(dialog).getByLabelText("6-digit code"), "654321");
await userEvent.click(within(dialog).getByRole("button", { name: /verify/i }));
await waitFor(() => expect(onDecided).toHaveBeenCalled());
const decision = calls.find((c) => c.path === "/approvals/a-refund/decision")!;
expect(decision.body).toEqual({
decision: "edit",
edited_args: { order_number: "ORD-1021", amount: 15000, reason: "damaged" },
});
});
it("rejects with a reason", async () => {
const { calls } = mockFetch({
"POST /approvals/a-cancel/decision": () => ({
approval: cancelItem({ status: "rejected" }),
replacement_id: null,
run: null,
}),
});
const onDecided = vi.fn();
renderUi(<ApprovalCard item={cancelItem()} onDecided={onDecided} />);
await authed();
await userEvent.click(screen.getByTestId("reject"));
await userEvent.type(await screen.findByLabelText(/reason/i), "keep it");
await userEvent.click(screen.getByTestId("confirm-note"));
await waitFor(() => expect(onDecided).toHaveBeenCalled());
expect(calls.find((c) => c.path === "/approvals/a-cancel/decision")!.body).toEqual({
decision: "reject",
note: "keep it",
});
});
it("disables approve when the role is too low", async () => {
mockFetch({
"GET /me": () => ({
user: { id: "u", email: "v@x.pk", totp_enrolled: false },
tenant: { id: "t1", name: "S", plan: "free", locale: "en", timezone: "Asia/Karachi" },
role: "viewer",
tenants: [],
}),
});
renderUi(<ApprovalCard item={cancelItem()} onDecided={vi.fn()} />);
await screen.findByText(/Needs the Manager role/);
expect(screen.getByTestId("approve")).toBeDisabled();
expect(screen.getByTestId("reject")).toBeEnabled();
});
});
describe("InboxView bulk approval", () => {
it("approves only the selected items, honouring per-item exclusion", async () => {
const a = cancelItem({ id: "c1", args: { order_number: "ORD-1001" } });
const b = cancelItem({ id: "c2", args: { order_number: "ORD-1032" } });
const c = cancelItem({ id: "c3", args: { order_number: "ORD-1040" } });
const decided: string[] = [];
const routes = {
"GET /inbox": (url: URL) => (url.searchParams.get("status") === "pending" ? [a, b, c].filter((x) => !decided.includes(x.id)) : []),
"GET /approvals": () => [],
} as Record<string, (u: URL) => unknown>;
for (const x of [a, b, c]) {
routes[`POST /approvals/${x.id}/decision`] = () => {
decided.push(x.id);
return { approval: { ...x, status: "approved" }, replacement_id: null, run: null };
};
}
mockFetch(routes);
renderUi(<InboxView />);
await waitFor(() => expect(screen.getAllByTestId("approval-card")).toHaveLength(3));
await waitFor(() => expect(screen.getAllByTestId("approve")[0]).toBeEnabled());
await userEvent.click(screen.getByTestId("select-all"));
expect(screen.getByTestId("selected-count")).toHaveTextContent("3 selected");
await userEvent.click(screen.getAllByTestId("approval-select")[1]); // exclude c2
expect(screen.getByTestId("selected-count")).toHaveTextContent("2 selected");
await userEvent.click(screen.getByTestId("bulk-approve"));
await waitFor(() => expect(decided.sort()).toEqual(["c1", "c3"]));
await waitFor(() => expect(screen.getAllByTestId("approval-card")).toHaveLength(1));
});
});
describe("UndoCountdown", () => {
it("renders nothing without send_after", () => {
mockFetch();
const { container } = renderUi(<UndoCountdown approvalId="x" sendAfter={null} />);
expect(container).toBeEmptyDOMElement();
});
it("counts down and can undo", async () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
const { calls } = mockFetch({ "POST /approvals/x/undo": () => ({ ok: true }) });
renderUi(<UndoCountdown approvalId="x" sendAfter={new Date(Date.now() + 61_000).toISOString()} />);
expect(screen.getByTestId("undo-countdown")).toHaveTextContent(/Sends in 1m \ds/);
await act(async () => {
vi.advanceTimersByTime(30_000);
});
expect(screen.getByTestId("undo-countdown")).toHaveTextContent(/Sends in 3\ds/);
fireEvent.click(screen.getByRole("button", { name: "Undo" }));
await waitFor(() => expect(screen.getByTestId("undo-done")).toBeInTheDocument());
expect(calls.some((c) => c.path === "/approvals/x/undo" && c.method === "POST")).toBe(true);
});
});1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"use client";
import { ShieldCheckIcon, TriangleAlertIcon } from "lucide-react";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useI18n } from "@/lib/i18n";
import type { Provenance } from "@/lib/types";
import { cn } from "@/lib/utils";
/** Where a value came from. Untrusted values were extracted from content an attacker could
* write (OWASP ASI09: human-agent trust exploitation), so they must stand out. */
export function ProvenanceBadge({
value,
field,
className,
}: {
value: Provenance | undefined;
field?: string;
className?: string;
}) {
const { t } = useI18n();
const untrusted = value === "untrusted";
const label = untrusted ? t("inbox.provenance.untrusted") : t("inbox.provenance.trusted");
const hint = untrusted ? t("inbox.provenance.untrustedHint") : t("inbox.provenance.trustedHint");
return (
<Tooltip>
<TooltipTrigger asChild>
<span
tabIndex={0}
role="status"
aria-label={`${label}: ${hint}`}
data-testid={field ? `provenance-${field}` : undefined}
data-provenance={untrusted ? "untrusted" : "trusted"}
className={cn(
"inline-flex h-5 shrink-0 items-center gap-1 rounded-full border px-1.5 text-[11px] font-medium leading-none whitespace-nowrap outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
untrusted
? "border-warning/40 bg-warning-soft text-warning"
: "border-success/30 bg-success-soft text-success",
className,
)}
>
{untrusted ? (
<TriangleAlertIcon className="size-3" aria-hidden />
) : (
<ShieldCheckIcon className="size-3" aria-hidden />
)}
{label}
</span>
</TooltipTrigger>
<TooltipContent className="max-w-64">{hint}</TooltipContent>
</Tooltip>
);
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195"use client";
import { KeyRoundIcon, Loader2Icon } from "lucide-react";
import {
createContext,
useCallback,
useContext,
useRef,
useState,
type FormEvent,
type ReactNode,
} from "react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { api } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { useI18n } from "@/lib/i18n";
import { getStepupToken, setStepupToken } from "@/lib/session";
type Request = () => Promise<boolean>;
const StepUpContext = createContext<Request | null>(null);
/** Provides ``requestStepUp()``: resolves true once a fresh step-up token is in memory. */
export function StepUpProvider({ children }: { children: ReactNode }) {
const [open, setOpen] = useState(false);
const resolver = useRef<((ok: boolean) => void) | null>(null);
const request = useCallback<Request>(() => {
if (getStepupToken()) return Promise.resolve(true);
return new Promise<boolean>((resolve) => {
resolver.current = resolve;
setOpen(true);
});
}, []);
const finish = (ok: boolean) => {
setOpen(false);
resolver.current?.(ok);
resolver.current = null;
};
return (
<StepUpContext.Provider value={request}>
{children}
<StepUpDialog open={open} onDone={finish} />
</StepUpContext.Provider>
);
}
export function useStepUp(): Request {
const v = useContext(StepUpContext);
if (!v) throw new Error("useStepUp outside StepUpProvider");
return v;
}
function StepUpDialog({ open, onDone }: { open: boolean; onDone: (ok: boolean) => void }) {
const { t } = useI18n();
const { me, reload } = useAuth();
const [code, setCode] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [secret, setSecret] = useState<string | null>(null);
const reset = () => {
setCode("");
setError(null);
setSecret(null);
};
const submit = async (e: FormEvent) => {
e.preventDefault();
setBusy(true);
setError(null);
try {
const r = await api<{ stepup_token: string }>("/auth/stepup", {
method: "POST",
body: { code },
});
setStepupToken(r.stepup_token);
reset();
onDone(true);
if (secret) void reload();
} catch {
setError(t("stepup.invalid"));
} finally {
setBusy(false);
}
};
const enroll = async () => {
setBusy(true);
try {
const r = await api<{ secret: string }>("/auth/totp/enroll", { method: "POST" });
setSecret(r.secret);
} finally {
setBusy(false);
}
};
return (
<Dialog
open={open}
onOpenChange={(o) => {
if (!o) {
reset();
onDone(false);
}
}}
>
<DialogContent className="sm:max-w-md" data-testid="stepup-dialog">
<form onSubmit={submit} className="space-y-4">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<KeyRoundIcon className="size-4 text-primary" aria-hidden />
{t("stepup.title")}
</DialogTitle>
<DialogDescription>{t("stepup.description")}</DialogDescription>
</DialogHeader>
{me && !me.user.totp_enrolled && (
<div className="space-y-2 rounded-md border border-dashed p-3 text-sm">
<p className="font-medium">{t("stepup.enrollTitle")}</p>
<p className="text-muted-foreground">{t("stepup.enrollDescription")}</p>
{secret ? (
<div className="space-y-1">
<Label>{t("stepup.secret")}</Label>
<code
dir="ltr"
data-testid="totp-secret"
className="block rounded bg-muted px-2 py-1 font-mono text-sm tracking-wider select-all"
>
{secret}
</code>
</div>
) : (
<Button type="button" variant="outline" size="sm" onClick={enroll} disabled={busy}>
{t("stepup.enroll")}
</Button>
)}
</div>
)}
<div className="space-y-2">
<Label htmlFor="stepup-code">{t("stepup.code")}</Label>
<Input
id="stepup-code"
dir="ltr"
inputMode="numeric"
autoComplete="one-time-code"
pattern="\d{6}"
maxLength={6}
autoFocus
value={code}
onChange={(e) => setCode(e.target.value.replace(/\D/g, "").slice(0, 6))}
className="tabular text-center text-lg tracking-[0.4em]"
aria-invalid={Boolean(error)}
aria-describedby={error ? "stepup-error" : undefined}
/>
{error && (
<p id="stepup-error" role="alert" className="text-sm text-destructive">
{error}
</p>
)}
</div>
<DialogFooter>
<Button
type="button"
variant="ghost"
onClick={() => {
reset();
onDone(false);
}}
>
{t("common.cancel")}
</Button>
<Button type="submit" disabled={code.length !== 6 || busy}>
{busy && <Loader2Icon className="animate-spin" aria-hidden />}
{t("stepup.verify")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"use client";
import { TimerIcon, Undo2Icon } from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { api } from "@/lib/api";
import { formatDuration } from "@/lib/format";
import { useI18n } from "@/lib/i18n";
import { useNow } from "@/lib/use-now";
/** Queued T2 sends (Phase 7) wait out an undo window before they go. Shows the time left and
* lets the operator cancel. Renders nothing for items without ``send_after``. */
export function UndoCountdown({
approvalId,
sendAfter,
undoUrl,
onUndone,
}: {
approvalId: string;
sendAfter: string | null | undefined;
undoUrl?: string | null;
onUndone?: () => void;
}) {
const { t } = useI18n();
const now = useNow(1000);
const [state, setState] = useState<"idle" | "busy" | "undone" | "error">("idle");
if (!sendAfter) return null;
const due = new Date(sendAfter).getTime();
if (Number.isNaN(due)) return null;
const left = Math.ceil((due - now) / 1000);
if (state === "undone") {
return (
<p className="text-sm text-muted-foreground" data-testid="undo-done" role="status">
{t("inbox.undone")}
</p>
);
}
if (left <= 0) {
return (
<p className="text-sm text-muted-foreground" data-testid="undo-sent">
{t("inbox.sent")}
</p>
);
}
const undo = async () => {
setState("busy");
try {
await api(undoUrl ?? `/approvals/${approvalId}/undo`, { method: "POST" });
setState("undone");
onUndone?.();
} catch {
setState("error");
}
};
return (
<div
className="flex items-center justify-between gap-3 rounded-md border border-info/30 bg-info-soft px-3 py-2"
data-testid="undo-countdown"
>
<span className="flex items-center gap-2 text-sm text-info" aria-live="polite">
<TimerIcon className="size-4" aria-hidden />
<span className="tabular">{t("inbox.undoIn", { time: formatDuration(left) })}</span>
</span>
<Button size="sm" variant="outline" onClick={undo} disabled={state === "busy"}>
<Undo2Icon aria-hidden />
{t("inbox.undo")}
</Button>
{state === "error" && (
<span role="alert" className="text-xs text-destructive">
{t("common.error")}
</span>
)}
</div>
);
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247"use client";
import { BookOpenIcon, FileTextIcon, SearchIcon, ShieldAlertIcon, Trash2Icon, UploadIcon } from "lucide-react";
import { useState, type FormEvent } from "react";
import { toast } from "sonner";
import { EmptyState, ErrorState, PageHeader } from "@/components/shell/page";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
import { Textarea } from "@/components/ui/textarea";
import { api, ApiError } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { formatDateTime } from "@/lib/format";
import { useI18n } from "@/lib/i18n";
import { useApi } from "@/lib/use-api";
import type { KnowledgeDoc, KnowledgeSearch } from "./types";
function toBase64(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result).split(",", 2)[1] ?? "");
reader.onerror = () => reject(reader.error ?? new Error("read failed"));
reader.readAsDataURL(file);
});
}
function UploadForm({ onAdded }: { onAdded: () => void }) {
const { t } = useI18n();
const [title, setTitle] = useState("");
const [file, setFile] = useState<File | null>(null);
const [text, setText] = useState("");
const [url, setUrl] = useState("");
const [busy, setBusy] = useState(false);
const submit = async (e: FormEvent) => {
e.preventDefault();
setBusy(true);
try {
let body: Record<string, string>;
if (file) {
body = { filename: file.name, content_type: file.type, content_base64: await toBase64(file) };
} else if (text.trim()) {
body = { text };
} else {
body = { url: url.trim() };
}
await api("/knowledge/docs", {
method: "POST",
body: { ...body, title: title.trim() || file?.name || undefined },
});
toast.success(t("knowledge.added"));
setTitle("");
setFile(null);
setText("");
setUrl("");
onAdded();
} catch (err) {
toast.error(err instanceof ApiError ? err.detail : t("common.error"));
} finally {
setBusy(false);
}
};
const ready = Boolean(file || text.trim() || url.trim());
return (
<form onSubmit={submit} className="space-y-3 rounded-lg border bg-card p-4" data-testid="knowledge-upload">
<div>
<h2 className="text-sm font-semibold">{t("knowledge.upload")}</h2>
<p className="text-xs text-muted-foreground">{t("knowledge.uploadHint")}</p>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div className="space-y-1.5">
<Label htmlFor="kb-title">{t("knowledge.docTitle")}</Label>
<Input id="kb-title" value={title} onChange={(e) => setTitle(e.target.value)} maxLength={300} />
</div>
<div className="space-y-1.5">
<Label htmlFor="kb-file">{t("knowledge.file")}</Label>
<Input
id="kb-file"
type="file"
accept=".pdf,.docx,.md,.markdown,.txt,.html,.htm"
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
/>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="kb-text">{t("knowledge.pasteText")}</Label>
<Textarea id="kb-text" rows={4} value={text} onChange={(e) => setText(e.target.value)} disabled={Boolean(file)} />
</div>
<div className="space-y-1.5">
<Label htmlFor="kb-url">{t("knowledge.url")}</Label>
<Input
id="kb-url"
type="url"
dir="ltr"
placeholder="https://"
value={url}
onChange={(e) => setUrl(e.target.value)}
disabled={Boolean(file || text.trim())}
/>
</div>
<Button type="submit" disabled={!ready || busy} data-testid="knowledge-add">
<UploadIcon className="size-4" aria-hidden />
{t("knowledge.add")}
</Button>
</form>
);
}
function SearchPanel() {
const { t } = useI18n();
const [q, setQ] = useState("");
const [result, setResult] = useState<KnowledgeSearch | null>(null);
const [busy, setBusy] = useState(false);
const submit = async (e: FormEvent) => {
e.preventDefault();
if (q.trim().length < 2) return;
setBusy(true);
try {
setResult(await api<KnowledgeSearch>("/knowledge/search", { query: { q: q.trim(), k: 5 } }));
} catch (err) {
toast.error(err instanceof ApiError ? err.detail : t("common.error"));
} finally {
setBusy(false);
}
};
return (
<section className="space-y-3 rounded-lg border bg-card p-4">
<h2 className="text-sm font-semibold">{t("knowledge.searchTitle")}</h2>
<form onSubmit={submit} className="flex gap-2">
<Input
aria-label={t("common.search")}
placeholder={t("knowledge.searchPlaceholder")}
value={q}
onChange={(e) => setQ(e.target.value)}
maxLength={500}
/>
<Button type="submit" variant="outline" disabled={busy} data-testid="knowledge-search">
<SearchIcon className="size-4" aria-hidden />
{t("common.search")}
</Button>
</form>
{result && result.hits.length === 0 && (
<p className="text-sm text-muted-foreground">{t("knowledge.noHits")}</p>
)}
{result && result.hits.length > 0 && (
<ol className="space-y-2" data-testid="knowledge-hits">
{result.hits.map((h) => (
<li key={h.chunk_id} className="rounded-md border p-3 text-sm">
<div className="mb-1 flex flex-wrap items-center gap-2">
<cite className="font-medium not-italic" data-testid="citation">
{h.citation}
</cite>
<Badge variant="outline">{t("knowledge.untrusted")}</Badge>
{h.flags.includes("possible_injection") && (
<Badge variant="destructive" title={t("knowledge.flaggedHint")}>
<ShieldAlertIcon className="size-3" aria-hidden />
{t("knowledge.flagged", { n: 1 })}
</Badge>
)}
<span className="text-xs text-muted-foreground tabular">
{t("knowledge.score", { s: h.score.toFixed(2) })}
</span>
</div>
<p className="whitespace-pre-wrap text-muted-foreground" dir="auto">
{h.text}
</p>
</li>
))}
</ol>
)}
</section>
);
}
export function KnowledgeView() {
const { t, locale } = useI18n();
const { hasRole } = useAuth();
const docs = useApi<KnowledgeDoc[]>("/knowledge/docs");
const canEdit = hasRole("manager");
const remove = async (d: KnowledgeDoc) => {
try {
await api(`/knowledge/docs/${d.id}`, { method: "DELETE" });
toast.success(t("knowledge.removed"));
docs.reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.detail : t("common.error"));
}
};
let list;
if (docs.error && !docs.data) {
list = <ErrorState error={docs.error} onRetry={docs.reload} />;
} else if (!docs.data) {
list = <Skeleton className="h-24 w-full" />;
} else if (docs.data.length === 0) {
list = <EmptyState icon={BookOpenIcon} title={t("knowledge.noDocs")} hint={t("knowledge.noDocsHint")} />;
} else {
list = (
<ul className="divide-y rounded-lg border bg-card" data-testid="knowledge-docs">
{docs.data.map((d) => (
<li key={d.id} className="flex flex-wrap items-center gap-3 p-3 text-sm">
<FileTextIcon className="size-4 text-muted-foreground" aria-hidden />
<div className="min-w-0 flex-1">
<p className="truncate font-medium">{d.title}</p>
<p className="text-xs text-muted-foreground">
{d.source_type.toUpperCase()} · {t("knowledge.chunks", { n: d.chunk_count })}
{d.page_count ? ` · ${t("knowledge.pages", { n: d.page_count })}` : ""} ·{" "}
{formatDateTime(d.created_at, locale)}
</p>
</div>
{d.flagged_chunks > 0 && (
<Badge variant="destructive" title={t("knowledge.flaggedHint")}>
<ShieldAlertIcon className="size-3" aria-hidden />
{t("knowledge.flagged", { n: d.flagged_chunks })}
</Badge>
)}
{canEdit && (
<Button variant="ghost" size="icon" aria-label={`${t("knowledge.remove")} ${d.title}`} onClick={() => void remove(d)}>
<Trash2Icon className="size-4" aria-hidden />
</Button>
)}
</li>
))}
</ul>
);
}
return (
<div className="space-y-5">
<PageHeader title={t("knowledge.title")} subtitle={t("knowledge.subtitle")} />
{canEdit && <UploadForm onAdded={docs.reload} />}
<section className="space-y-2">
<h2 className="text-sm font-semibold">{t("knowledge.docs")}</h2>
{list}
</section>
<SearchPanel />
</div>
);
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115import { screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, describe, expect, it, vi } from "vitest";
import { KnowledgeView } from "@/components/knowledge/knowledge-view";
import { MemoryView } from "@/components/knowledge/memory-view";
import { setAccessToken } from "@/lib/session";
import { mockFetch } from "@/test/fixtures";
import { renderUi } from "@/test/render";
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
usePathname: () => "/knowledge",
}));
afterEach(() => {
vi.unstubAllGlobals();
setAccessToken(null);
});
const DOC = {
id: "d1",
title: "Returns Policy",
source_type: "markdown",
source_uri: null,
size_bytes: 900,
page_count: null,
chunk_count: 3,
status: "ready",
flagged_chunks: 1,
created_by: "user:1",
created_at: "2026-12-05T10:00:00Z",
};
const HIT = {
chunk_id: "c1aaaaaa-0000-0000-0000-000000000000",
doc_id: "d1",
title: "Returns Policy",
page: null,
ordinal: 1,
text: "If your item arrives damaged or defective, contact us within 7 days.",
score: 0.61,
flags: [],
source_uri: null,
citation: "Returns Policy (chunk c1aaaaaa)",
};
describe("KnowledgeView", () => {
it("lists documents, flags injected passages and shows search hits with citations", async () => {
const { calls } = mockFetch({
"GET /knowledge/docs": () => [DOC],
"GET /knowledge/search": () => ({ untrusted: true, hits: [HIT] }),
"POST /knowledge/docs": () => DOC,
});
renderUi(<KnowledgeView />);
const docs = await screen.findByTestId("knowledge-docs");
expect(within(docs).getByText("Returns Policy")).toBeInTheDocument();
expect(within(docs).getByText("1 flagged")).toBeInTheDocument();
await userEvent.type(screen.getByLabelText("Search"), "return policy damaged");
await userEvent.click(screen.getByTestId("knowledge-search"));
const hits = await screen.findByTestId("knowledge-hits");
expect(within(hits).getByTestId("citation")).toHaveTextContent("Returns Policy (chunk c1aaaaaa)");
expect(within(hits).getByText("Untrusted text")).toBeInTheDocument();
await waitFor(() => expect(screen.getByTestId("knowledge-upload")).toBeInTheDocument());
await userEvent.type(screen.getByLabelText("Or paste text"), "Exchanges within 14 days.");
await userEvent.click(screen.getByTestId("knowledge-add"));
await waitFor(() =>
expect(calls.some((c) => c.method === "POST" && c.path === "/knowledge/docs")).toBe(true),
);
const post = calls.find((c) => c.method === "POST" && c.path === "/knowledge/docs");
expect(post?.body).toMatchObject({ text: "Exchanges within 14 days." });
});
});
describe("MemoryView", () => {
it("shows remembered items and hides tampered content", async () => {
mockFetch({
"GET /memory/items": () => [
{
id: "m1",
namespace: ["tenant", "t1", "cases", "support"],
key: "run:1",
kind: "case",
value: { category: "inquiry", resolution: "answer drafted" },
integrity_ok: true,
size_bytes: 80,
written_by: "agent:1",
created_at: "2026-12-05T10:00:00Z",
updated_at: "2026-12-05T10:00:00Z",
expires_at: "2027-06-03T10:00:00Z",
},
{
id: "m2",
namespace: ["tenant", "t1", "customer", "c9"],
key: "pref",
kind: "customer",
value: null,
integrity_ok: false,
size_bytes: 40,
written_by: "user:1",
created_at: "2026-12-05T10:00:00Z",
updated_at: "2026-12-05T10:00:00Z",
expires_at: "2027-06-03T10:00:00Z",
},
],
});
renderUi(<MemoryView />);
const table = await screen.findByTestId("memory-table");
expect(within(table).getByText(/resolution: answer drafted/)).toBeInTheDocument();
expect(within(table).getByText(/Integrity check failed/)).toBeInTheDocument();
expect(within(table).getByText("Resolved cases")).toBeInTheDocument();
});
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170"use client";
import { BrainIcon, ShieldAlertIcon, Trash2Icon } from "lucide-react";
import { useState, type FormEvent } from "react";
import { toast } from "sonner";
import { EmptyState, ErrorState, PageHeader } from "@/components/shell/page";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { api, ApiError } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { formatDateTime } from "@/lib/format";
import { useI18n } from "@/lib/i18n";
import { useApi } from "@/lib/use-api";
import { cn } from "@/lib/utils";
import type { MemoryItem, MemoryKind } from "./types";
const KINDS: (MemoryKind | "all")[] = ["all", "customer", "prefs", "case"];
function summarize(value: Record<string, unknown> | null): string {
if (!value) return "";
return Object.entries(value)
.map(([k, v]) => `${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`)
.join(" · ");
}
function ForgetCustomer({ onDone }: { onDone: () => void }) {
const { t } = useI18n();
const [id, setId] = useState("");
const submit = async (e: FormEvent) => {
e.preventDefault();
if (!id.trim()) return;
try {
const r = await api<{ deleted: number }>(`/memory/customers/${encodeURIComponent(id.trim())}`, {
method: "DELETE",
});
toast.success(t("memory.forgetCustomerDone", { n: r.deleted }));
setId("");
onDone();
} catch (err) {
toast.error(err instanceof ApiError ? err.detail : t("common.error"));
}
};
return (
<form onSubmit={submit} className="flex flex-wrap items-end gap-2">
<div className="space-y-1.5">
<Label htmlFor="mem-customer">{t("memory.customerId")}</Label>
<Input id="mem-customer" dir="ltr" value={id} onChange={(e) => setId(e.target.value)} className="w-64" />
</div>
<Button type="submit" variant="outline" disabled={!id.trim()}>
{t("memory.forgetCustomer")}
</Button>
</form>
);
}
export function MemoryView() {
const { t, m, locale } = useI18n();
const { hasRole, me } = useAuth();
const [kind, setKind] = useState<MemoryKind | "all">("all");
const allowed = hasRole("manager");
const items = useApi<MemoryItem[]>(allowed ? "/memory/items" : null, {
query: kind === "all" ? {} : { kind },
});
const forget = async (item: MemoryItem) => {
try {
await api(`/memory/items/${item.id}`, { method: "DELETE" });
toast.success(t("memory.forgotten"));
items.reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.detail : t("common.error"));
}
};
let body;
if (me && !allowed) {
body = <EmptyState icon={BrainIcon} title={t("memory.managerOnly")} />;
} else if (items.error && !items.data) {
body = <ErrorState error={items.error} onRetry={items.reload} />;
} else if (!items.data) {
body = <Skeleton className="h-32 w-full" />;
} else if (items.data.length === 0) {
body = <EmptyState icon={BrainIcon} title={t("memory.empty")} hint={t("memory.emptyHint")} />;
} else {
body = (
<div className="rounded-lg border bg-card">
<Table data-testid="memory-table">
<TableHeader>
<TableRow>
<TableHead>{t("memory.namespace")}</TableHead>
<TableHead>{t("memory.key")}</TableHead>
<TableHead>{t("memory.value")}</TableHead>
<TableHead>{t("memory.expires")}</TableHead>
<TableHead className="w-10" />
</TableRow>
</TableHeader>
<TableBody>
{items.data.map((it) => (
<TableRow key={it.id}>
<TableCell>
<Badge variant="secondary">
{it.kind === "other" ? it.namespace.slice(2).join(" / ") : m.memory.kinds[it.kind]}
</Badge>
{it.namespace.length > 3 && (
<span className="ms-2 font-mono text-xs text-muted-foreground" dir="ltr">
{it.namespace.slice(3).join("/")}
</span>
)}
</TableCell>
<TableCell className="font-mono text-xs" dir="ltr">
{it.key}
</TableCell>
<TableCell className="max-w-md whitespace-normal text-sm" dir="auto">
{it.integrity_ok ? (
summarize(it.value)
) : (
<span className="inline-flex items-center gap-1 text-destructive">
<ShieldAlertIcon className="size-3.5" aria-hidden />
{t("memory.tampered")}
</span>
)}
</TableCell>
<TableCell className="text-xs text-muted-foreground">
{formatDateTime(it.expires_at, locale)}
</TableCell>
<TableCell>
<Button variant="ghost" size="icon" aria-label={`${t("memory.forget")} ${it.key}`} onClick={() => void forget(it)}>
<Trash2Icon className="size-4" aria-hidden />
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
);
}
return (
<div className="space-y-5">
<PageHeader title={t("memory.title")} subtitle={t("memory.subtitle")} />
{allowed && (
<div className="flex flex-wrap items-end justify-between gap-3">
<div className="flex flex-wrap gap-1" role="group" aria-label={t("memory.namespace")}>
{KINDS.map((k) => (
<Button
key={k}
size="sm"
variant={kind === k ? "default" : "outline"}
aria-pressed={kind === k}
onClick={() => setKind(k)}
className={cn(kind === k && "pointer-events-none")}
>
{m.memory.kinds[k]}
</Button>
))}
</div>
<ForgetCustomer onDone={items.reload} />
</div>
)}
{body}
</div>
);
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849// Phase 12 API shapes (core/api/routes/knowledge.py).
export interface KnowledgeDoc {
id: string;
title: string;
source_type: "pdf" | "docx" | "markdown" | "text" | "html";
source_uri: string | null;
size_bytes: number;
page_count: number | null;
chunk_count: number;
status: string;
flagged_chunks: number;
created_by: string;
created_at: string;
}
export interface KnowledgeHit {
chunk_id: string;
doc_id: string;
title: string;
page: number | null;
ordinal: number;
text: string;
score: number;
flags: string[];
source_uri: string | null;
citation: string;
}
export interface KnowledgeSearch {
untrusted: boolean;
hits: KnowledgeHit[];
}
export type MemoryKind = "customer" | "prefs" | "case";
export interface MemoryItem {
id: string;
namespace: string[];
key: string;
kind: MemoryKind | "other";
value: Record<string, unknown> | null;
integrity_ok: boolean;
size_bytes: number;
written_by: string;
created_at: string;
updated_at: string;
expires_at: string;
}web/README.mdAdded+52
web/playwright.config.tsAdded+50
web/playwright.staging.config.tsAdded+19
web/src/app/(app)/analytics/page.tsxAdded+9
web/src/app/(app)/chat/page.tsxAdded+9
web/src/app/(app)/cod/page.tsxAdded+9
web/src/app/(app)/inbox/page.tsxAdded+9
web/src/app/(app)/integrations/page.tsxAdded+9
web/src/app/(app)/knowledge/page.tsxAdded+9
web/src/app/(app)/layout.tsxAdded+13
web/src/app/(app)/memory/page.tsxAdded+9
web/src/app/(app)/orders/[number]/page.tsxAdded+10
web/src/app/(app)/orders/page.tsxAdded+9
web/src/app/(app)/rules/page.tsxAdded+9
web/src/app/(app)/runs/[id]/page.tsxAdded+10
web/src/app/(app)/runs/page.tsxAdded+9
web/src/app/(app)/settings/page.tsxAdded+9
web/src/app/(app)/workflows/[id]/page.tsxAdded+10
web/src/app/(app)/workflows/page.tsxAdded+9
web/src/app/(auth)/login/page.tsxAdded+14
web/src/app/(auth)/signup/page.tsxAdded+14
web/src/app/api/session/[action]/route.tsAdded+77
web/src/app/favicon.icoAdded
web/src/app/globals.cssAdded+180
web/src/app/layout.tsxAdded+47
web/src/app/page.tsxAdded+5
web/src/components/analytics/analytics-view.tsxAdded+156
web/src/components/analytics/operations-health.test.tsxAdded+144
web/src/components/analytics/operations-health.tsxAdded+225
web/src/components/chat/chat-view.tsxAdded+174
web/src/components/chat/gen-ui.tsxAdded+194
web/src/components/commerce/cod-view.tsxAdded+81
web/src/components/commerce/order-detail.tsxAdded+129
web/src/components/commerce/orders-view.tsxAdded+191
web/src/components/commerce/risk-badge.tsxAdded+32
web/src/components/ext/integrations-view.tsxAdded+564
web/src/components/ext/rules-view.tsxAdded+239
web/src/components/ext/types.tsAdded+92
web/src/components/inbox/approval-card.tsxAdded+329
web/src/components/inbox/diff-view.tsxAdded+198
web/src/components/inbox/edit-args-form.tsxAdded+226
web/src/components/inbox/inbox-view.tsxAdded+227
web/src/components/inbox/inbox.test.tsxAdded+247
web/src/components/inbox/provenance-badge.tsxAdded+53
web/src/components/inbox/stepup.tsxAdded+195
web/src/components/inbox/undo-countdown.tsxAdded+77
web/src/components/knowledge/knowledge-view.tsxAdded+247
web/src/components/knowledge/knowledge.test.tsxAdded+115
web/src/components/knowledge/memory-view.tsxAdded+170
web/src/components/knowledge/types.tsAdded+49