Merge feat/l1-workspace into integration branch
Some checks failed
Mirror to GitHub / mirror (push) Successful in 5s
CI / frontend (pull_request) Failing after 1m29s
CI / e2e (pull_request) Failing after 6m23s
CI / backend (pull_request) Successful in 11m30s

# Conflicts:
#	frontend/src/router.tsx
This commit is contained in:
2026-05-28 23:51:50 -04:00
74 changed files with 13239 additions and 98 deletions

View File

@@ -0,0 +1,189 @@
/**
* E2E tests for the L1 Workspace surface (Phase 1).
*
* Covers:
* 1. L1 user lands on /l1 after login and can start an ad-hoc walk, take
* notes (autosave), and resolve the session.
* 2. L1 user cannot access /pilot, /trees/new, or /escalations — route
* guards bounce them back to /.
* 3. Engineer with can_cover_l1=true sees the "L1 Workspace" nav entry and
* the "You're covering L1" banner.
* 4. escalate-without-walk API endpoint returns an escalated adhoc session
* when called from an authenticated L1 user.
*
* Seed users (added by seed_test_users.py):
* l1@resolutionflow.example.com — account_role=l1_tech
* engineer-coverage@resolutionflow.example.com — engineer + can_cover_l1
*/
import { test, expect, type Page } from '@playwright/test'
// These tests always log in fresh — no shared storageState from auth.setup.ts.
test.use({ storageState: { cookies: [], origins: [] } })
const L1_EMAIL = 'l1@resolutionflow.example.com'
const COVERAGE_EMAIL = 'engineer-coverage@resolutionflow.example.com'
const PASSWORD = 'TestPass123!'
const apiOrigin = process.env.PLAYWRIGHT_API_ORIGIN || 'http://127.0.0.1:8000'
/**
* Log in via the login form using exact test-IDs / labels that LoginPage uses.
* Uses data-testid="login-form", getByLabel('Email address'), getByLabel('Password'),
* and data-testid="login-submit" — matching the actual LoginPage.tsx markup.
*/
async function login(page: Page, email: string): Promise<void> {
await page.goto('/login')
await expect(page.getByTestId('login-form')).toBeVisible()
await page.getByLabel('Email address').fill(email)
await page.getByLabel('Password').fill(PASSWORD)
await page.getByTestId('login-submit').click()
}
/**
* Obtain a bearer token for the given email via the JSON login endpoint.
* Used for direct API assertions without going through the browser.
*/
async function getToken(
page: Page,
email: string,
): Promise<string> {
const response = await page.request.post(`${apiOrigin}/api/v1/auth/login/json`, {
data: { email, password: PASSWORD },
})
expect(response.ok()).toBeTruthy()
const body = (await response.json()) as { access_token: string }
return body.access_token
}
test.describe('L1 Workspace', () => {
// -------------------------------------------------------------------------
// Test 1: Happy path — login → /l1 → start walk → notes → resolve
// -------------------------------------------------------------------------
test('L1 user lands on /l1 after login and can intake, take notes, and resolve', async ({ page }) => {
await login(page, L1_EMAIL)
// ProtectedRoute redirects l1_tech from / → /l1
await expect(page).toHaveURL(/\/l1$/, { timeout: 10_000 })
// Greeting heading: "Good morning|afternoon|evening, <name>."
await expect(
page.getByRole('heading', { name: /Good (morning|afternoon|evening)/i }),
).toBeVisible()
// Fill in problem statement textarea
const problemTextarea = page.getByPlaceholder("What's the user calling about?")
await expect(problemTextarea).toBeVisible()
await problemTextarea.fill('Customer says Outlook is broken after the latest update')
// Click "Start walk →" button
await page.getByRole('button', { name: /Start walk/i }).click()
// Should navigate to /l1/walk/<uuid>
await expect(page).toHaveURL(/\/l1\/walk\//, { timeout: 10_000 })
// The header badge shows "Ad-hoc walk"
await expect(page.getByText('Ad-hoc walk')).toBeVisible()
// Take notes in the walk textarea
const notesTextarea = page.getByPlaceholder(
'What did the customer say? What did you check? What did you try?',
)
await expect(notesTextarea).toBeVisible()
await notesTextarea.fill('Walked customer through closing and reopening Outlook — issue resolved')
// Autosave fires after 300ms debounce; wait up to 5s for the "Saved Xs ago" indicator
await expect(
page.getByText(/Saved \d+s ago|Saving…/i),
).toBeVisible({ timeout: 5_000 })
// Open the Resolve modal
await page.getByRole('button', { name: /Resolve/i }).click()
// Modal heading: "Did this resolve it?"
await expect(
page.getByRole('heading', { name: 'Did this resolve it?' }),
).toBeVisible()
// Click "Yes"
await page.getByRole('button', { name: 'Yes' }).click()
// Fill resolution notes
await page.getByPlaceholder('Resolution notes…').fill('Fixed via restarting Outlook')
// Confirm
await page.getByRole('button', { name: 'Confirm' }).click()
// After resolution, onDone() navigates back to /l1
await expect(page).toHaveURL(/\/l1$/, { timeout: 10_000 })
})
// -------------------------------------------------------------------------
// Test 2: Route guard — L1 user cannot access engineer-only routes
// -------------------------------------------------------------------------
test('L1 user cannot access /pilot, /trees/new, or /escalations', async ({ page }) => {
await login(page, L1_EMAIL)
await expect(page).toHaveURL(/\/l1$/, { timeout: 10_000 })
// /pilot — ProtectedRoute requires at least engineer rank; l1_tech gets bounced
await page.goto('/pilot')
await expect(page).not.toHaveURL(/\/pilot/, { timeout: 5_000 })
// /trees/new — same guard
await page.goto('/trees/new')
await expect(page).not.toHaveURL(/\/trees\/new/, { timeout: 5_000 })
// /escalations — if this route exists with a role guard it should bounce too
await page.goto('/escalations')
await expect(page).not.toHaveURL(/\/escalations/, { timeout: 5_000 })
})
// -------------------------------------------------------------------------
// Test 3: Coverage engineer sees the L1 nav link and the coverage banner
// -------------------------------------------------------------------------
test('Engineer with can_cover_l1 sees the L1 Workspace nav and coverage banner', async ({ page }) => {
await login(page, COVERAGE_EMAIL)
// Coverage engineer is not l1_tech — they land on the normal workspace root
await expect(page.getByTestId('app-shell')).toBeVisible({ timeout: 10_000 })
// Sidebar should show "L1 Workspace" link
const l1NavLink = page.getByRole('link', { name: /L1 Workspace/i })
await expect(l1NavLink).toBeVisible({ timeout: 10_000 })
// Navigate to /l1
await l1NavLink.click()
await expect(page).toHaveURL(/\/l1/, { timeout: 10_000 })
// L1CoverageBanner renders: "You're covering L1. Actions logged as coverage."
await expect(
page.getByText(/You're covering L1/i),
).toBeVisible({ timeout: 5_000 })
})
// -------------------------------------------------------------------------
// Test 4: escalate-without-walk endpoint — direct API assertion
// -------------------------------------------------------------------------
test('escalate-without-walk returns an escalated adhoc session', async ({ page }) => {
const token = await getToken(page, L1_EMAIL)
const response = await page.request.post(
`${apiOrigin}/api/v1/l1/escalate-without-walk`,
{
data: {
problem_statement: 'Customer issue with no KB content available',
reason_category: 'No KB available',
},
headers: { Authorization: `Bearer ${token}` },
},
)
expect(response.status()).toBe(200)
const body = (await response.json()) as {
status: string
session_kind: string
}
expect(body.status).toBe('escalated')
expect(body.session_kind).toBe('adhoc')
})
})

64
frontend/src/api/l1.ts Normal file
View File

@@ -0,0 +1,64 @@
import { apiClient } from './client'
import type {
IntakeRequest,
IntakeResponse,
QueueRow,
WalkSession,
AdhocNote,
} from '@/types/l1'
export const l1Api = {
intake: (body: IntakeRequest) =>
apiClient.post<IntakeResponse>('/l1/intake', body).then(r => r.data),
queue: (statusFilter?: string) =>
apiClient.get<QueueRow[]>('/l1/queue', {
params: statusFilter ? { status_filter: statusFilter } : {},
}).then(r => r.data),
listActiveSessions: () =>
apiClient.get<WalkSession[]>('/l1/sessions/active').then(r => r.data),
getSession: (sessionId: string) =>
apiClient.get<WalkSession>(`/l1/sessions/${sessionId}`).then(r => r.data),
step: (
sessionId: string,
step: { node_id: string; question: string; answer: string; note?: string | null },
) =>
apiClient
.post<WalkSession>(`/l1/sessions/${sessionId}/step`, step)
.then(r => r.data),
notes: (sessionId: string, notes: AdhocNote[]) =>
apiClient
.post<WalkSession>(`/l1/sessions/${sessionId}/notes`, { notes })
.then(r => r.data),
resolve: (
sessionId: string,
body: { helpful: boolean; resolution_notes: string },
) =>
apiClient
.post<WalkSession>(`/l1/sessions/${sessionId}/resolve`, body)
.then(r => r.data),
escalate: (
sessionId: string,
body: { reason: string; reason_category: string },
) =>
apiClient
.post<WalkSession>(`/l1/sessions/${sessionId}/escalate`, body)
.then(r => r.data),
escalateWithoutWalk: (body: {
problem_statement: string
customer_name?: string
customer_contact?: string
reason_category: string
reason?: string
}) =>
apiClient
.post<WalkSession>('/l1/escalate-without-walk', body)
.then(r => r.data),
}

17
frontend/src/api/seats.ts Normal file
View File

@@ -0,0 +1,17 @@
import { apiClient } from './client'
export interface SeatCheck {
available: boolean
current: number
limit: number | null
role: 'engineer' | 'l1_tech'
}
export interface SeatUsage {
engineer: SeatCheck
l1_tech: SeatCheck
}
export const seatsApi = {
getUsage: () => apiClient.get<SeatUsage>('/accounts/me/seats').then((r) => r.data),
}

View File

@@ -0,0 +1,33 @@
import { useEffect, useState } from 'react'
import { seatsApi, type SeatUsage } from '@/api/seats'
interface RowProps { label: string; check: SeatUsage['engineer'] }
function SeatRow({ label, check }: RowProps) {
const overLimit = check.limit !== null && check.current > check.limit
const limitText = check.limit === null ? '∞' : check.limit
return (
<div className={overLimit ? 'text-warning' : ''}>
<p className="text-xs uppercase tracking-wider text-muted-foreground mb-1">{label}</p>
<p className="text-lg font-mono">{check.current} / {limitText}</p>
{overLimit && <p className="text-xs">Over limit (grandfathered)</p>}
</div>
)
}
export function SeatCounterWidget() {
const [usage, setUsage] = useState<SeatUsage | null>(null)
useEffect(() => {
seatsApi.getUsage().then(setUsage).catch(() => setUsage(null))
}, [])
if (!usage) return null
return (
<div className="rounded-lg border border-default bg-card p-4 grid grid-cols-2 gap-4">
<SeatRow label="Engineer seats" check={usage.engineer} />
<SeatRow label="L1 seats" check={usage.l1_tech} />
</div>
)
}

View File

@@ -0,0 +1,35 @@
import { usePermissions } from '@/hooks/usePermissions'
interface Props {
onUploadClick?: () => void
}
export function EmptyStateCard({ onUploadClick }: Props) {
const { canCoverL1 } = usePermissions()
return (
<div className="rounded-lg border border-default bg-card p-6">
<h2 className="font-heading text-xl font-bold text-heading mb-2">
Your knowledge base is empty
</h2>
<p className="text-muted-foreground mb-4">
L1 Workspace works best when your account has KB content or authored flows.
Right now there's nothing to match against calls will start as ad-hoc walks.
</p>
{canCoverL1 && onUploadClick ? (
<button
type="button"
onClick={onUploadClick}
className="rounded-md bg-accent text-white px-4 py-2 text-sm font-medium hover:bg-accent/90 transition-colors"
>
Upload KB content
</button>
) : (
<ul className="text-sm text-muted-foreground space-y-1 ml-4 list-disc">
<li>Ask your admin to upload KB documents</li>
<li>Or ask them to author a flow in the Flows library</li>
</ul>
)}
</div>
)
}

View File

@@ -0,0 +1,23 @@
import { useNavigate } from 'react-router-dom'
import { usePermissions } from '@/hooks/usePermissions'
export function L1CoverageBanner() {
const perms = usePermissions()
const navigate = useNavigate()
// Show only for engineer-coverers / owners-stepping-in. Native L1 doesn't see it.
if (perms.isL1Tech) return null
if (!perms.canCoverL1) return null
return (
<div className="bg-info/10 text-info text-sm px-4 py-1.5 flex items-center justify-between border-b border-info/20">
<span>You're covering L1. Actions logged as coverage.</span>
<button
onClick={() => navigate('/')}
className="text-info hover:underline underline-offset-2"
>
Switch back
</button>
</div>
)
}

View File

@@ -0,0 +1,156 @@
import { useEffect, useRef, useState } from 'react'
import { ChevronLeft } from 'lucide-react'
import { Link } from 'react-router-dom'
import { l1Api } from '@/api/l1'
import type { AdhocNote, WalkSession } from '@/types/l1'
import { EscalateModal, ResolveModal } from '@/components/l1/WalkModals'
interface Props {
session: WalkSession
onSessionUpdate: (s: WalkSession) => void
onDone: () => void
}
export function L1WalkAdhocVariant({ session, onSessionUpdate, onDone }: Props) {
const [showResolve, setShowResolve] = useState(false)
const [showEscalate, setShowEscalate] = useState(false)
// Show prior notes as joined paragraphs so the L1 sees an editable timeline.
const [notesText, setNotesText] = useState(() =>
session.walk_notes.map((n) => n.content).join('\n\n')
)
const [savedAt, setSavedAt] = useState<Date | null>(null)
const [saving, setSaving] = useState(false)
const saveTimer = useRef<number | null>(null)
// Debounced autosave: 300ms after the last keystroke, send to the backend.
useEffect(() => {
if (session.status !== 'active') return
if (saveTimer.current) window.clearTimeout(saveTimer.current)
saveTimer.current = window.setTimeout(async () => {
// Split paragraphs into structured notes. Empty paragraphs are skipped.
const parts = notesText
.split('\n\n')
.map((c) => c.trim())
.filter(Boolean)
const notes: AdhocNote[] = parts.map((content) => ({
timestamp: new Date().toISOString(),
content,
}))
try {
setSaving(true)
const updated = await l1Api.notes(session.id, notes)
onSessionUpdate(updated)
setSavedAt(new Date())
} catch (err) {
console.error('notes save failed:', err)
} finally {
setSaving(false)
}
}, 300)
return () => {
if (saveTimer.current) window.clearTimeout(saveTimer.current)
}
}, [notesText, session.id, session.status, onSessionUpdate])
const savedAgo = savedAt ? Math.max(1, Math.round((Date.now() - savedAt.getTime()) / 1000)) : null
return (
<div className="flex flex-col h-full">
{/* Header */}
<header className="border-b border-default px-6 py-4 flex items-center justify-between bg-sidebar">
<Link
to="/l1"
className="flex items-center gap-2 text-muted-foreground hover:text-heading transition-colors"
>
<ChevronLeft className="w-4 h-4" />
<span className="font-mono text-xs">#{session.id.slice(0, 8)}</span>
<span className="ml-2 text-xs bg-info/10 text-info px-2 py-0.5 rounded">Ad-hoc walk</span>
</Link>
<div className="flex gap-2">
<button
onClick={() => setShowEscalate(true)}
disabled={session.status !== 'active'}
className="rounded-md border border-default px-3 py-1.5 text-sm hover:bg-elevated transition-colors disabled:opacity-50"
>
Escalate
</button>
<button
onClick={() => setShowResolve(true)}
disabled={session.status !== 'active'}
className="rounded-md bg-accent text-white px-3 py-1.5 text-sm hover:bg-accent/90 transition-colors disabled:opacity-50"
>
Resolve
</button>
</div>
</header>
{/* Single-pane body */}
<main className="flex-1 p-6 overflow-y-auto min-h-0">
<div className="max-w-3xl mx-auto">
{session.status !== 'active' ? (
<div className="rounded-lg border border-default bg-card p-6">
<p className="text-sm text-muted-foreground">
This session is <span className="font-semibold">{session.status}</span>.
</p>
<button
onClick={onDone}
className="mt-3 rounded-md bg-accent text-white px-3 py-1.5 text-sm hover:bg-accent/90 transition-colors"
>
Back to workspace
</button>
</div>
) : (
<>
<p className="text-sm text-muted-foreground mb-3">
Take notes as you work through the call. They're auto-saved.
</p>
<textarea
value={notesText}
onChange={(e) => setNotesText(e.target.value)}
rows={20}
placeholder="What did the customer say? What did you check? What did you try?"
className="w-full bg-card border border-default rounded-md px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-accent/40 leading-relaxed font-sans"
/>
<p className="text-xs text-muted-foreground mt-2">
{saving
? 'Saving'
: savedAgo !== null
? `Saved ${savedAgo}s ago`
: 'Not yet saved'}
</p>
</>
)}
</div>
</main>
{/* Modals */}
{showResolve && (
<ResolveModal
defaultNotes={notesText}
onClose={() => setShowResolve(false)}
onConfirm={async (helpful, resolutionNotes) => {
try {
await l1Api.resolve(session.id, { helpful, resolution_notes: resolutionNotes })
onDone()
} catch (err) {
console.error('resolve failed:', err)
}
}}
/>
)}
{showEscalate && (
<EscalateModal
onClose={() => setShowEscalate(false)}
onConfirm={async (category, reason) => {
try {
await l1Api.escalate(session.id, { reason, reason_category: category })
onDone()
} catch (err) {
console.error('escalate failed:', err)
}
}}
/>
)}
</div>
)
}

View File

@@ -0,0 +1,173 @@
import { useState } from 'react'
import { ChevronLeft } from 'lucide-react'
import { Link } from 'react-router-dom'
import { l1Api } from '@/api/l1'
import type { WalkSession } from '@/types/l1'
import { EscalateModal, ResolveModal } from '@/components/l1/WalkModals'
interface Props {
session: WalkSession
onSessionUpdate: (s: WalkSession) => void
onDone: () => void
}
export function L1WalkTreeVariant({ session, onSessionUpdate, onDone }: Props) {
const [showResolve, setShowResolve] = useState(false)
const [showEscalate, setShowEscalate] = useState(false)
const [note, setNote] = useState('')
// Phase 1: we don't have the live flow-tree fetch wired up here yet
// (the tree-navigation pages have their own loader). The walker shows the
// walked-path side panel, advance buttons stubbed for now — Phase 2 wires
// the actual flow tree fetching + node advancement against tree data.
// The "Yes/No" buttons record a synthetic step so the walked_path JSONB
// grows; this gives us a functional roundtrip until Phase 2 wires the tree.
const handleAnswer = async (answer: 'yes' | 'no') => {
const nodeId = session.current_node_id || `step-${session.walked_path.length + 1}`
try {
const updated = await l1Api.step(session.id, {
node_id: nodeId,
question: `Step ${session.walked_path.length + 1}`,
answer,
note: note || null,
})
onSessionUpdate(updated)
setNote('')
} catch (err) {
// Keep silent for v1 — Phase 2 wires real error UI
console.error('step failed', err)
}
}
const lastError = (err: unknown): string => {
if (typeof err === 'object' && err && 'response' in err) {
const detail = (err as any).response?.data?.detail
if (typeof detail === 'string') return detail
}
return 'Unexpected error'
}
return (
<div className="flex flex-col h-full">
{/* Header */}
<header className="border-b border-default px-6 py-4 flex items-center justify-between bg-sidebar">
<Link to="/l1" className="flex items-center gap-2 text-muted-foreground hover:text-heading transition-colors">
<ChevronLeft className="w-4 h-4" />
<span className="font-mono text-xs">#{session.id.slice(0, 8)}</span>
{session.session_kind === 'proposal' && (
<span className="ml-2 text-xs bg-accent/10 text-accent px-2 py-0.5 rounded">AI-built</span>
)}
</Link>
<div className="flex gap-2">
<button
onClick={() => setShowEscalate(true)}
className="rounded-md border border-default px-3 py-1.5 text-sm hover:bg-elevated transition-colors"
disabled={session.status !== 'active'}
>
Escalate
</button>
<button
onClick={() => setShowResolve(true)}
className="rounded-md bg-accent text-white px-3 py-1.5 text-sm hover:bg-accent/90 transition-colors disabled:opacity-50"
disabled={session.status !== 'active'}
>
Resolve
</button>
</div>
</header>
{/* Two-pane body */}
<div className="flex-1 flex min-h-0">
<main className="flex-1 p-6 overflow-y-auto min-h-0">
<p className="font-sans text-[0.625rem] uppercase tracking-[0.12em] font-semibold text-muted-foreground mb-2">
Step {session.walked_path.length + 1}
</p>
{session.status !== 'active' ? (
<div className="rounded-lg border border-default bg-card p-6">
<p className="text-sm text-muted-foreground">
This session is <span className="font-semibold">{session.status}</span>.
</p>
<button onClick={onDone} className="mt-3 rounded-md bg-accent text-white px-3 py-1.5 text-sm">
Back to workspace
</button>
</div>
) : (
<div className="rounded-lg border border-default bg-card p-6 max-w-2xl">
<p className="text-lg mb-6">Continue the walk:</p>
<div className="flex gap-3">
<button
onClick={() => handleAnswer('yes')}
className="flex-1 rounded-md bg-accent text-white py-3 text-base font-medium hover:bg-accent/90 min-h-[44px] transition-colors"
>
Yes
</button>
<button
onClick={() => handleAnswer('no')}
className="flex-1 rounded-md border border-default py-3 text-base font-medium hover:bg-elevated min-h-[44px] transition-colors"
>
No
</button>
</div>
<textarea
value={note}
onChange={(e) => setNote(e.target.value)}
placeholder="Optional note for this step…"
rows={2}
className="mt-4 w-full bg-page border border-default rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-accent/40"
/>
</div>
)}
</main>
{/* Right pane: transcript */}
<aside className="w-80 border-l border-default bg-page p-4 overflow-y-auto">
<p className="font-sans text-[0.625rem] uppercase tracking-[0.12em] font-semibold text-muted-foreground mb-3">
Walked so far
</p>
{session.walked_path.length === 0 ? (
<p className="text-xs text-muted-foreground">No steps yet.</p>
) : (
<ol className="space-y-3 text-sm">
{session.walked_path.map((step, i) => (
<li key={i} className="flex flex-col">
<span className="text-muted-foreground text-xs">{step.question}</span>
<span className="font-medium"> {step.answer}</span>
{step.l1_note && <span className="text-muted-foreground text-xs italic mt-0.5">{step.l1_note}</span>}
</li>
))}
</ol>
)}
</aside>
</div>
{/* Modals */}
{showResolve && (
<ResolveModal
onClose={() => setShowResolve(false)}
onConfirm={async (helpful, resolutionNotes) => {
try {
await l1Api.resolve(session.id, { helpful, resolution_notes: resolutionNotes })
onDone()
} catch (err) {
console.error('resolve failed:', lastError(err))
}
}}
/>
)}
{showEscalate && (
<EscalateModal
onClose={() => setShowEscalate(false)}
onConfirm={async (category, reason) => {
try {
await l1Api.escalate(session.id, { reason, reason_category: category })
onDone()
} catch (err) {
console.error('escalate failed:', lastError(err))
}
}}
/>
)}
</div>
)
}

View File

@@ -0,0 +1,49 @@
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { l1Api } from '@/api/l1'
import type { WalkSession } from '@/types/l1'
export function ResumeInProgress() {
const [sessions, setSessions] = useState<WalkSession[] | null>(null)
useEffect(() => {
l1Api
.listActiveSessions()
.then(setSessions)
.catch(() => setSessions([]))
}, [])
if (!sessions || sessions.length === 0) return null
return (
<section>
<div className="flex items-center gap-3 mb-3">
<span className="font-sans text-[0.625rem] uppercase tracking-[0.12em] font-semibold text-muted-foreground">
Resume in progress · {sessions.length}
</span>
<div className="flex-1 h-px bg-border" />
</div>
<div className="rounded-lg border border-default bg-card overflow-hidden">
{sessions.map((s) => (
<Link
key={s.id}
to={`/l1/walk/${s.id}`}
className="flex items-center justify-between px-4 py-3 hover:bg-elevated transition-colors border-b border-default last:border-b-0"
>
<div className="flex items-center gap-3">
<span className="font-mono text-xs text-muted-foreground">#{s.id.slice(0, 8)}</span>
<span className="text-sm">
{s.session_kind === 'adhoc'
? `Ad-hoc · ${s.walk_notes.length} notes`
: `Step ${s.walked_path.length}`}
</span>
</div>
<span className="text-xs text-muted-foreground">
{new Date(s.last_step_at).toLocaleTimeString()}
</span>
</Link>
))}
</div>
</section>
)
}

View File

@@ -0,0 +1,121 @@
import { useState } from 'react'
export interface ResolveModalProps {
defaultNotes?: string
onClose: () => void
onConfirm: (helpful: boolean, notes: string) => Promise<void>
}
export function ResolveModal({ defaultNotes = '', onClose, onConfirm }: ResolveModalProps) {
const [helpful, setHelpful] = useState<boolean | null>(null)
const [notes, setNotes] = useState(defaultNotes)
const [submitting, setSubmitting] = useState(false)
return (
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
<div className="bg-card border border-default rounded-lg p-6 max-w-md w-full">
<h3 className="font-heading text-lg font-bold mb-4">Did this resolve it?</h3>
<div className="flex gap-3 mb-4">
<button
onClick={() => setHelpful(true)}
className={`flex-1 py-2 rounded-md transition-colors ${helpful === true ? 'bg-accent text-white' : 'border border-default hover:bg-elevated'}`}
>
Yes
</button>
<button
onClick={() => setHelpful(false)}
className={`flex-1 py-2 rounded-md transition-colors ${helpful === false ? 'bg-warning text-white' : 'border border-default hover:bg-elevated'}`}
>
No
</button>
</div>
<textarea
value={notes}
onChange={(e) => setNotes(e.target.value)}
rows={3}
placeholder="Resolution notes…"
className="w-full bg-page border border-default rounded-md px-3 py-2 text-sm mb-4 focus:outline-none focus:ring-2 focus:ring-accent/40"
/>
<div className="flex justify-end gap-2">
<button
onClick={onClose}
className="rounded-md border border-default px-4 py-2 text-sm hover:bg-elevated transition-colors"
>
Cancel
</button>
<button
disabled={helpful === null || submitting}
onClick={async () => {
setSubmitting(true)
try { await onConfirm(helpful!, notes) } finally { setSubmitting(false) }
}}
className="rounded-md bg-accent text-white px-4 py-2 text-sm disabled:opacity-50 hover:bg-accent/90 transition-colors"
>
{submitting ? 'Saving…' : 'Confirm'}
</button>
</div>
</div>
</div>
)
}
export interface EscalateModalProps {
onClose: () => void
onConfirm: (category: string, reason: string) => Promise<void>
}
const REASON_CATEGORIES = [
'Out of L1 scope',
'Customer demanding senior',
'Tree dead-ended',
'AI tree wrong',
'No KB available',
'Other',
] as const
export function EscalateModal({ onClose, onConfirm }: EscalateModalProps) {
const [category, setCategory] = useState<string>(REASON_CATEGORIES[0])
const [reason, setReason] = useState('')
const [submitting, setSubmitting] = useState(false)
return (
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
<div className="bg-card border border-default rounded-lg p-6 max-w-md w-full">
<h3 className="font-heading text-lg font-bold mb-4">Escalate to engineering</h3>
<label className="block text-xs uppercase tracking-wider text-muted-foreground mb-1">Reason</label>
<select
value={category}
onChange={(e) => setCategory(e.target.value)}
className="w-full bg-page border border-default rounded-md px-3 py-2 text-sm mb-3 focus:outline-none focus:ring-2 focus:ring-accent/40"
>
{REASON_CATEGORIES.map((c) => (<option key={c}>{c}</option>))}
</select>
<textarea
value={reason}
onChange={(e) => setReason(e.target.value)}
rows={3}
placeholder="Details (optional)…"
className="w-full bg-page border border-default rounded-md px-3 py-2 text-sm mb-4 focus:outline-none focus:ring-2 focus:ring-accent/40"
/>
<div className="flex justify-end gap-2">
<button
onClick={onClose}
className="rounded-md border border-default px-4 py-2 text-sm hover:bg-elevated transition-colors"
>
Cancel
</button>
<button
disabled={submitting}
onClick={async () => {
setSubmitting(true)
try { await onConfirm(category, reason) } finally { setSubmitting(false) }
}}
className="rounded-md bg-warning text-white px-4 py-2 text-sm disabled:opacity-50 hover:bg-warning/90 transition-colors"
>
{submitting ? 'Escalating…' : 'Confirm escalate'}
</button>
</div>
</div>
</div>
)
}

View File

@@ -0,0 +1,18 @@
import { Navigate } from 'react-router-dom'
import { usePermissions } from '@/hooks/usePermissions'
import { L1CoverageBanner } from '@/components/l1/L1CoverageBanner'
export function L1RouteGuard({ children }: { children: React.ReactNode }) {
const { canUseL1Surface } = usePermissions()
if (!canUseL1Surface) {
return <Navigate to="/" replace />
}
return (
<div className="flex flex-col h-full">
<L1CoverageBanner />
<div className="flex-1 min-h-0 flex flex-col">
{children}
</div>
</div>
)
}

View File

@@ -32,9 +32,10 @@ export function ProtectedRoute({ requiredRole, children }: ProtectedRouteProps)
if (requiredRole) {
const ROLE_HIERARCHY: Record<EffectiveRole, number> = {
super_admin: 4,
owner: 3,
engineer: 2,
super_admin: 5,
owner: 4,
engineer: 3,
l1_tech: 2,
viewer: 1,
}
if (ROLE_HIERARCHY[effectiveRole] < ROLE_HIERARCHY[requiredRole]) {
@@ -42,6 +43,12 @@ export function ProtectedRoute({ requiredRole, children }: ProtectedRouteProps)
}
}
// L1 users landing on / (e.g. post-login) get redirected to their workspace.
// Does not fire when already on /l1 or any other path, preventing loops.
if (effectiveRole === 'l1_tech' && location.pathname === '/') {
return <Navigate to="/l1" replace />
}
return <>{children}</>
}

View File

@@ -12,6 +12,7 @@ import { useUserPreferencesStore } from '@/store/userPreferencesStore'
import { sidebarApi } from '@/api'
import type { SidebarStatsResponse } from '@/api/sidebar'
import { prefetchForRoute } from '@/lib/routePrefetch'
import { usePermissions } from '@/hooks/usePermissions'
/* ── Types ──────────────────────────────────────────── */
@@ -37,6 +38,7 @@ export function Sidebar() {
const location = useLocation()
const sidebarPinned = useUserPreferencesStore(s => s.sidebarPinned)
const toggleSidebarPinned = useUserPreferencesStore(s => s.toggleSidebarPinned)
const { isL1Tech, canCoverL1 } = usePermissions()
const [stats, setStats] = useState<SidebarStatsResponse | null>(null)
// Phase 6: pending-drafts badge on the Scripts nav. Fetched independently
@@ -77,58 +79,74 @@ export function Sidebar() {
* and pinned modes. Pin/unpin is a width/label affordance, not an
* IA switch. A hairline divider separates the two groups; no labels. */
const workItems: NavEntry[] = [
{
href: '/', icon: LayoutGrid, label: 'Dashboard', shortLabel: 'Dash',
matchPaths: ['/'],
},
{
href: '/tickets', icon: Ticket, label: 'Tickets', shortLabel: 'Tickets',
matchPaths: ['/tickets'],
},
{
href: '/sessions', icon: Clock, label: 'Sessions', shortLabel: 'Sessions',
badge: stats?.active_count || undefined,
matchPaths: ['/sessions'],
},
{
href: '/escalations', icon: AlertTriangle, label: 'Escalations', shortLabel: 'Escal',
badge: stats?.escalation_count || undefined,
matchPaths: ['/escalations'],
},
]
// L1 users get a focused sidebar with only their surfaces.
// Engineers/owners get the full sidebar; those with canCoverL1 also get
// an appended "L1 Workspace" entry in the library group.
const workItems: NavEntry[] = isL1Tech
? [
{ href: '/l1', icon: LayoutGrid, label: 'Workspace', shortLabel: 'Work', matchPaths: ['/l1'] },
{ href: '/l1/tickets', icon: Ticket, label: 'Tickets', shortLabel: 'Tickets', matchPaths: ['/l1/tickets'] },
{ href: '/l1/drafts', icon: FileText, label: 'My Drafts', shortLabel: 'Drafts', matchPaths: ['/l1/drafts'] },
]
: [
{
href: '/', icon: LayoutGrid, label: 'Dashboard', shortLabel: 'Dash',
matchPaths: ['/'],
},
{
href: '/tickets', icon: Ticket, label: 'Tickets', shortLabel: 'Tickets',
matchPaths: ['/tickets'],
},
{
href: '/sessions', icon: Clock, label: 'Sessions', shortLabel: 'Sessions',
badge: stats?.active_count || undefined,
matchPaths: ['/sessions'],
},
{
href: '/escalations', icon: AlertTriangle, label: 'Escalations', shortLabel: 'Escal',
badge: stats?.escalation_count || undefined,
matchPaths: ['/escalations'],
},
]
const libraryItems: NavEntry[] = [
{
href: '/trees', icon: GitBranch, label: 'Flows', shortLabel: 'Flows',
badge: stats?.tree_counts.total || undefined,
matchPaths: ['/trees', '/flows', '/my-trees', '/step-library', '/network-diagrams'],
children: [
{ href: '/trees?type=procedural', label: 'Projects', count: stats?.tree_counts.procedural || undefined },
{ href: '/step-library', label: 'Solutions Library' },
{ href: '/network-diagrams', label: 'Network Maps' },
],
},
{
href: '/scripts', icon: FileText, label: 'Scripts', shortLabel: 'Scripts',
badge: pendingDraftCount || undefined,
matchPaths: ['/scripts', '/script-builder'],
children: [
{ href: '/script-builder', label: 'Script Builder' },
],
},
{
href: '/review-queue', icon: ListChecks, label: 'Review Queue', shortLabel: 'Review',
matchPaths: ['/review-queue'],
},
{
href: '/analytics', icon: BarChart3, label: 'Analytics', shortLabel: 'Stats',
matchPaths: ['/analytics', '/shares'],
children: [
{ href: '/shares', label: 'Exports' },
],
},
]
const libraryItems: NavEntry[] = isL1Tech
? []
: [
{
href: '/trees', icon: GitBranch, label: 'Flows', shortLabel: 'Flows',
badge: stats?.tree_counts.total || undefined,
matchPaths: ['/trees', '/flows', '/my-trees', '/step-library', '/network-diagrams'],
children: [
{ href: '/trees?type=procedural', label: 'Projects', count: stats?.tree_counts.procedural || undefined },
{ href: '/step-library', label: 'Solutions Library' },
{ href: '/network-diagrams', label: 'Network Maps' },
],
},
{
href: '/scripts', icon: FileText, label: 'Scripts', shortLabel: 'Scripts',
badge: pendingDraftCount || undefined,
matchPaths: ['/scripts', '/script-builder'],
children: [
{ href: '/script-builder', label: 'Script Builder' },
],
},
{
href: '/review-queue', icon: ListChecks, label: 'Review Queue', shortLabel: 'Review',
matchPaths: ['/review-queue'],
},
{
href: '/analytics', icon: BarChart3, label: 'Analytics', shortLabel: 'Stats',
matchPaths: ['/analytics', '/shares'],
children: [
{ href: '/shares', label: 'Exports' },
],
},
// Engineers/owners with L1 coverage access also get the L1 Workspace entry
...(canCoverL1 ? [{
href: '/l1', icon: LayoutGrid, label: 'L1 Workspace', shortLabel: 'L1',
matchPaths: ['/l1'],
}] : []),
]
const footerItems: NavEntry[] = [
{ href: '/guides', icon: BookOpen, label: 'Guides', shortLabel: 'Guides', matchPaths: ['/guides'] },

View File

@@ -1,19 +1,20 @@
/**
* Centralized permissions hook for ResolutionFlow.
*
* Role hierarchy: super_admin > owner > engineer > viewer
* Role hierarchy: super_admin > owner > engineer > l1_tech > viewer
*
* Mirrors backend logic in backend/app/core/permissions.py
*/
import { useAuthStore } from '@/store/authStore'
import type { User } from '@/types'
export type EffectiveRole = 'super_admin' | 'owner' | 'engineer' | 'viewer'
export type EffectiveRole = 'super_admin' | 'owner' | 'engineer' | 'l1_tech' | 'viewer'
const ROLE_HIERARCHY: Record<EffectiveRole, number> = {
super_admin: 4,
owner: 3,
engineer: 2,
super_admin: 5,
owner: 4,
engineer: 3,
l1_tech: 2,
viewer: 1,
}
@@ -21,7 +22,9 @@ function getEffectiveRole(user: User | null): EffectiveRole {
if (!user) return 'viewer'
if (user.is_super_admin) return 'super_admin'
if (user.account_role === 'owner') return 'owner'
return user.role as EffectiveRole
if (user.account_role === 'engineer') return 'engineer'
if (user.account_role === 'l1_tech') return 'l1_tech'
return 'viewer'
}
function hasMinimumRole(user: User | null, minimum: EffectiveRole): boolean {
@@ -39,8 +42,23 @@ export function usePermissions() {
isSuperAdmin: effectiveRole === 'super_admin',
isAccountOwner: effectiveRole === 'owner' || effectiveRole === 'super_admin',
isEngineer: hasMinimumRole(user, 'engineer'),
isL1Tech: effectiveRole === 'l1_tech',
isViewer: effectiveRole === 'viewer',
// L1 workspace permissions
canCoverL1: (
Boolean(user?.can_cover_l1) ||
effectiveRole === 'owner' ||
effectiveRole === 'super_admin'
),
canUseL1Surface: (
effectiveRole === 'l1_tech' ||
effectiveRole === 'owner' ||
effectiveRole === 'super_admin' ||
(user?.account_role === 'engineer' && Boolean(user?.can_cover_l1))
),
canUseEngineerSurface: hasMinimumRole(user, 'engineer'),
// Content creation permissions
canCreateTrees: hasMinimumRole(user, 'engineer'),
canCreateSteps: hasMinimumRole(user, 'engineer'),

View File

@@ -33,6 +33,7 @@ import { Spinner } from '@/components/common/Spinner'
import { cn } from '@/lib/utils'
import { usePermissions } from '@/hooks/usePermissions'
import { useSubscription } from '@/hooks/useSubscription'
import { SeatCounterWidget } from '@/components/admin/SeatCounterWidget'
import { useAuthStore } from '@/store/authStore'
import { CheckoutButton } from '@/components/subscription/CheckoutButton'
import { toast } from '@/lib/toast'
@@ -236,8 +237,17 @@ export function AccountSettingsPage() {
const invitesData = await accountsApi.getInvites()
setInvites(invitesData)
} catch (err) {
toast.error('Failed to send invitation')
console.error(err)
const resp = (err as any)?.response
if (resp?.status === 402 && resp?.data?.detail?.code === 'seat_limit_exceeded') {
const d = resp.data.detail
const label = d.role === 'l1_tech' ? 'L1' : 'Engineer'
toast.warning(
`${label} seats full: ${d.current}/${d.limit}. Upgrade your plan to add more.`,
)
} else {
toast.error('Failed to send invitation')
console.error(err)
}
} finally {
setIsInviting(false)
}
@@ -432,6 +442,8 @@ export function AccountSettingsPage() {
<section className="space-y-5 border-t border-border pt-8">
<SectionLabel>People</SectionLabel>
<SeatCounterWidget />
<form onSubmit={handleInvite} className="flex flex-wrap items-center gap-2">
<input
type="email"

View File

@@ -0,0 +1,168 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { PageMeta } from '@/components/common/PageMeta'
import { useAuthStore } from '@/store/authStore'
import { l1Api } from '@/api/l1'
import { toast } from '@/lib/toast'
import { EmptyStateCard } from '@/components/l1/EmptyStateCard'
import { ResumeInProgress } from '@/components/l1/ResumeInProgress'
import type { QueueRow } from '@/types/l1'
export default function L1Dashboard() {
const user = useAuthStore((s) => s.user)
const navigate = useNavigate()
const [problem, setProblem] = useState('')
const [customerName, setCustomerName] = useState('')
const [customerContact, setCustomerContact] = useState('')
const [submitting, setSubmitting] = useState(false)
const [queue, setQueue] = useState<QueueRow[]>([])
const [isEmpty, setIsEmpty] = useState(false)
useEffect(() => {
l1Api.queue('open').then(setQueue).catch(() => setQueue([]))
// Phase 1: emptiness detection is just "is the queue empty AND no resumable sessions" —
// we conservatively show the empty-state card on accounts with literally no L1 activity yet.
// (A stricter KB-empty detection arrives in Phase 2 when the kb_documents table exists.)
}, [])
useEffect(() => {
// Show empty-state ONLY for first-run state — no queue items and no active sessions
if (queue.length === 0) {
l1Api
.listActiveSessions()
.then((active) => setIsEmpty(active.length === 0))
.catch(() => setIsEmpty(false))
} else {
setIsEmpty(false)
}
}, [queue])
const handleStart = async () => {
if (!problem.trim()) return
setSubmitting(true)
try {
const response = await l1Api.intake({
problem_statement: problem.trim(),
customer_name: customerName.trim() || undefined,
customer_contact: customerContact.trim() || undefined,
})
navigate(`/l1/walk/${response.session_id}`)
} catch (err) {
const detail = (err as any)?.response?.data?.detail
const msg =
typeof detail === 'string' ? detail : 'Failed to start walk. Try again.'
toast.error(msg)
} finally {
setSubmitting(false)
}
}
const now = new Date()
const greeting =
now.getHours() < 12 ? 'morning' : now.getHours() < 18 ? 'afternoon' : 'evening'
const firstName = user?.name?.split(' ')[0] || 'there'
return (
<div className="overflow-y-auto h-full">
<PageMeta title="L1 Workspace" />
<div className="max-w-4xl mx-auto px-6 pt-12 pb-12 space-y-8">
{/* Greeting */}
<div>
<p className="font-sans text-xs uppercase tracking-[0.12em] text-muted-foreground mb-1">
{now.toLocaleDateString('en-US', {
weekday: 'long',
month: 'long',
day: 'numeric',
})}
</p>
<h1 className="font-heading text-3xl sm:text-4xl font-extrabold tracking-tight text-heading leading-tight">
Good {greeting}, {firstName}.
</h1>
</div>
{/* Empty state (first-run) */}
{isEmpty && <EmptyStateCard />}
{/* Describe the problem */}
<section>
<div className="flex items-center gap-3 mb-3">
<span className="w-1 h-4 bg-accent rounded-sm" />
<span className="font-sans text-[0.625rem] uppercase tracking-[0.12em] font-semibold text-muted-foreground">
Describe the problem
</span>
</div>
<div className="rounded-lg border border-default bg-card p-4 space-y-3">
<textarea
value={problem}
onChange={(e) => setProblem(e.target.value)}
placeholder="What's the user calling about?"
autoFocus
rows={3}
className="w-full bg-page border border-default rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-accent/40"
/>
<div className="grid grid-cols-2 gap-3">
<input
value={customerName}
onChange={(e) => setCustomerName(e.target.value)}
placeholder="Customer name (optional)"
className="bg-page border border-default rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-accent/40"
/>
<input
value={customerContact}
onChange={(e) => setCustomerContact(e.target.value)}
placeholder="Email or phone (optional)"
className="bg-page border border-default rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-accent/40"
/>
</div>
<div className="flex justify-end">
<button
type="button"
onClick={handleStart}
disabled={!problem.trim() || submitting}
className="rounded-md bg-accent text-white px-5 py-2 text-sm font-medium hover:bg-accent/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{submitting ? 'Starting…' : 'Start walk →'}
</button>
</div>
</div>
</section>
{/* Open tickets */}
{queue.length > 0 && (
<section>
<div className="flex items-center gap-3 mb-3">
<span className="font-sans text-[0.625rem] uppercase tracking-[0.12em] font-semibold text-muted-foreground">
Open tickets · {queue.length}
</span>
<div className="flex-1 h-px bg-border" />
</div>
<div className="rounded-lg border border-default bg-card overflow-hidden">
{queue.map((row) => (
/* Phase 1: display-only rows. Phase 2 makes them clickable to claim. */
<div
key={row.ticket_id}
className="px-4 py-3 border-b border-default last:border-b-0"
>
<div className="flex items-center justify-between">
<div>
<span className="font-mono text-xs text-muted-foreground mr-2">
#{row.ticket_id.slice(0, 8)}
</span>
<span className="text-sm">{row.problem_statement}</span>
</div>
<span className="text-xs px-2 py-0.5 rounded bg-elevated text-muted-foreground">
{row.ticket_kind === 'psa' ? 'PSA' : 'Internal'}
</span>
</div>
</div>
))}
</div>
</section>
)}
{/* Resume in progress */}
<ResumeInProgress />
</div>
</div>
)
}

View File

@@ -0,0 +1,15 @@
import { PageMeta } from '@/components/common/PageMeta'
export default function L1DraftsPage() {
return (
<div className="overflow-y-auto h-full">
<PageMeta title="My Drafts" />
<div className="max-w-4xl mx-auto px-6 pt-12 pb-12">
<h1 className="font-heading text-2xl font-bold mb-2">My AI drafts</h1>
<p className="text-muted-foreground">
AI-built drafts you've created will show here once AI build is enabled (Phase 2).
</p>
</div>
</div>
)
}

View File

@@ -0,0 +1,60 @@
import { useEffect, useState } from 'react'
import { PageMeta } from '@/components/common/PageMeta'
import { l1Api } from '@/api/l1'
import type { QueueRow } from '@/types/l1'
export default function L1TicketsPage() {
const [rows, setRows] = useState<QueueRow[]>([])
const [statusFilter, setStatusFilter] = useState<string>('')
useEffect(() => {
l1Api.queue(statusFilter || undefined).then(setRows).catch(() => setRows([]))
}, [statusFilter])
return (
<div className="overflow-y-auto h-full">
<PageMeta title="Tickets" />
<div className="max-w-5xl mx-auto px-6 pt-12 pb-12">
<div className="flex items-center justify-between mb-6">
<h1 className="font-heading text-2xl font-bold">Tickets</h1>
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
className="bg-card border border-default rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-accent/40"
>
<option value="">All</option>
<option value="open">Open</option>
<option value="walking">Walking</option>
<option value="resolved">Resolved</option>
<option value="escalated">Escalated</option>
</select>
</div>
<div className="rounded-lg border border-default bg-card overflow-hidden">
{rows.map((r) => (
<div key={r.ticket_id} className="px-4 py-3 border-b border-default last:border-b-0">
<div className="flex items-center justify-between">
<div>
<span className="font-mono text-xs text-muted-foreground mr-2">
#{r.ticket_id.slice(0, 8)}
</span>
<span className="text-sm">{r.problem_statement}</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xs px-2 py-0.5 rounded bg-elevated text-muted-foreground">
{r.status}
</span>
<span className="text-xs text-muted-foreground">
{r.ticket_kind === 'psa' ? 'PSA' : 'Internal'}
</span>
</div>
</div>
</div>
))}
{rows.length === 0 && (
<p className="px-4 py-8 text-sm text-muted-foreground text-center">No tickets.</p>
)}
</div>
</div>
</div>
)
}

View File

@@ -0,0 +1,70 @@
import { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { PageMeta } from '@/components/common/PageMeta'
import { l1Api } from '@/api/l1'
import { L1WalkTreeVariant } from '@/components/l1/L1WalkTreeVariant'
import { L1WalkAdhocVariant } from '@/components/l1/L1WalkAdhocVariant'
import type { WalkSession } from '@/types/l1'
export default function L1WalkPage() {
const { sessionId } = useParams<{ sessionId: string }>()
const navigate = useNavigate()
const [session, setSession] = useState<WalkSession | null>(null)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
if (!sessionId) return
l1Api.getSession(sessionId)
.then(setSession)
.catch((err) => {
const msg = err?.response?.data?.detail || err?.message || 'Failed to load session'
setError(typeof msg === 'string' ? msg : 'Failed to load session')
})
}, [sessionId])
if (error) {
return (
<div className="overflow-y-auto h-full">
<PageMeta title="L1 Walk" />
<div className="max-w-4xl mx-auto px-6 pt-12 text-muted-foreground">
{error}
</div>
</div>
)
}
if (!session) {
return (
<div className="overflow-y-auto h-full">
<PageMeta title="L1 Walk" />
<div className="max-w-4xl mx-auto px-6 pt-12 text-muted-foreground">Loading</div>
</div>
)
}
const handleDone = () => navigate('/l1')
// Phase 1: adhoc variant handles session_kind='adhoc'. Tree variant handles flow/proposal.
if (session.session_kind === 'adhoc') {
return (
<>
<PageMeta title="L1 Walk" />
<L1WalkAdhocVariant
session={session}
onSessionUpdate={setSession}
onDone={handleDone}
/>
</>
)
}
return (
<>
<PageMeta title="L1 Walk" />
<L1WalkTreeVariant
session={session}
onSessionUpdate={setSession}
onDone={handleDone}
/>
</>
)
}

View File

@@ -8,6 +8,7 @@ import { ErrorBoundary } from '@/components/common/ErrorBoundary'
import { PageLoader } from '@/components/common/PageLoader'
import { lazyWithRetry } from '@/lib/lazyWithRetry'
import { useAuthStore } from '@/store/authStore'
import { L1RouteGuard } from '@/components/layout/L1RouteGuard'
const sentryCreateBrowserRouter = Sentry.wrapCreateBrowserRouterV7(createBrowserRouter)
import {
@@ -96,6 +97,12 @@ const AdminSurveyInvitesPage = lazyWithRetry(() => import('@/pages/admin/SurveyI
const AdminSurveyResponsesPage = lazyWithRetry(() => import('@/pages/admin/SurveyResponsesPage'))
const AdminGalleryManagementPage = lazyWithRetry(() => import('@/pages/admin/GalleryManagementPage'))
// L1 workspace pages
const L1Dashboard = lazyWithRetry(() => import('@/pages/l1/L1Dashboard'))
const L1WalkPage = lazyWithRetry(() => import('@/pages/l1/L1WalkPage'))
const L1DraftsPage = lazyWithRetry(() => import('@/pages/l1/L1DraftsPage'))
const L1TicketsPage = lazyWithRetry(() => import('@/pages/l1/L1TicketsPage'))
// Account pages
const AccountLayout = lazyWithRetry(() => import('@/components/account/AccountLayout'))
const ProfileSettingsPage = lazyWithRetry(() => import('@/pages/account/ProfileSettingsPage'))
@@ -301,6 +308,11 @@ export const router = sentryCreateBrowserRouter([
{ path: '/welcome/step-1', element: page(WelcomeStep1) },
{ path: '/welcome/step-2', element: page(WelcomeStep2) },
{ path: '/welcome/step-3', element: page(WelcomeStep3) },
// L1 workspace routes — gated by canUseL1Surface
{ path: '/l1', element: <L1RouteGuard>{page(L1Dashboard)}</L1RouteGuard> },
{ path: '/l1/walk/:sessionId', element: <L1RouteGuard>{page(L1WalkPage)}</L1RouteGuard> },
{ path: '/l1/drafts', element: <L1RouteGuard>{page(L1DraftsPage)}</L1RouteGuard> },
{ path: '/l1/tickets', element: <L1RouteGuard>{page(L1TicketsPage)}</L1RouteGuard> },
// Admin routes
{
path: '/admin',

52
frontend/src/types/l1.ts Normal file
View File

@@ -0,0 +1,52 @@
export type SessionKind = 'flow' | 'proposal' | 'adhoc'
export type SessionStatus = 'active' | 'resolved' | 'escalated' | 'abandoned'
export type TicketKind = 'psa' | 'internal'
export interface WalkStep {
node_id: string
question: string
answer: string
l1_note: string | null
}
export interface AdhocNote {
timestamp: string
content: string
}
export interface WalkSession {
id: string
session_kind: SessionKind
flow_id: string | null
flow_proposal_id: string | null
current_node_id: string | null
walked_path: WalkStep[]
walk_notes: AdhocNote[]
status: SessionStatus
started_at: string
last_step_at: string
resolved_at: string | null
}
export interface QueueRow {
ticket_id: string
ticket_kind: TicketKind
problem_statement: string | null
customer_name: string | null
status: string
created_at: string | null
}
export interface IntakeRequest {
problem_statement: string
customer_name?: string
customer_contact?: string
flow_id?: string
}
export interface IntakeResponse {
session_id: string
session_kind: SessionKind
ticket_id: string
ticket_kind: TicketKind
}

View File

@@ -9,7 +9,8 @@ export interface User {
is_active: boolean
must_change_password: boolean
account_id: string | null
account_role: 'owner' | 'engineer' | 'viewer' | null
account_role: 'owner' | 'engineer' | 'l1_tech' | 'viewer' | null
can_cover_l1: boolean
team_id: string | null
created_at: string
last_login: string | null