Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,37 @@ const config = [
'react-hooks/immutability': 'off',
},
},
// P1.5 — Discourage bare `fetch('/api/...')`.
// The team must migrate to `apiFetch<T>()` from `@/lib/api-client` so that
// 401 / 403 / 5xx / network failures are handled uniformly.
// Phase 1 (this PR): warn level, allow incremental migration.
// Phase 3 (final cleanup): upgrade to error and forbid merges that introduce
// new bare fetch('/api/...') sites.
// Selector rationale:
// - covers single-quoted, double-quoted, and template-literal forms
// - filters by /api prefix so cross-origin / external fetches stay untouched
// - exempts api-client.ts itself (the one allowed implementer)
{
files: ['src/**/*.{ts,tsx,js,jsx}'],
ignores: ['src/lib/api-client.ts'],
rules: {
'no-restricted-syntax': [
'warn',
{
selector:
"CallExpression[callee.name='fetch'] > Literal[value=/^\\/api\\//]",
message:
"Use apiFetch<T>() from '@/lib/api-client' instead of bare fetch('/api/...'). It handles 401 redirect, 403/5xx typed errors, and network failures uniformly. See PR-api-client.md.",
},
{
selector:
"CallExpression[callee.name='fetch'] > TemplateLiteral.arguments:first-child[quasis.0.value.raw=/^\\/api\\//]",
message:
"Use apiFetch<T>() from '@/lib/api-client' instead of bare fetch(`/api/...`). It handles 401 redirect, 403/5xx typed errors, and network failures uniformly.",
},
],
},
},
]

export default config
2 changes: 2 additions & 0 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { NextIntlClientProvider } from 'next-intl'
import { getLocale, getMessages } from 'next-intl/server'
import { THEME_IDS } from '@/lib/themes'
import { ThemeBackground } from '@/components/ui/theme-background'
import { AuthExpiredListener } from '@/components/auth-expired-listener'
import './globals.css'

const inter = Inter({
Expand Down Expand Up @@ -114,6 +115,7 @@ export default async function RootLayout({
disableTransitionOnChange
>
<ThemeBackground />
<AuthExpiredListener />
<div className="h-screen overflow-hidden bg-background text-foreground">
{children}
</div>
Expand Down
33 changes: 33 additions & 0 deletions src/components/auth-expired-listener.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'use client'

import { useEffect } from 'react'

/**
* Listens for `mc:auth-expired` CustomEvent dispatched by `apiFetch()` when the
* server returns 401. The redirect to `/login?from=...` is already handled inside
* `apiFetch`; this listener exists so we have a single observability hook the
* team can extend (toast, telemetry, Sentry).
*
* Mounted once at the root layout. SSR-safe (effect runs only on the client).
*
* Why a separate component?
* - layout.tsx is a server component (uses `await headers()`); we cannot
* attach window listeners there directly.
* - Co-locating the listener with the api-client keeps the auth-failure
* contract in one place.
*/
export function AuthExpiredListener(): null {
useEffect(() => {
const onExpired = (e: Event) => {
const detail = (e as CustomEvent<{ path: string; status: number }>).detail
// No toast lib installed yet — log for now. Replace with sonner in next PR.
console.warn(
`[mc] session expired on ${detail?.path ?? 'unknown'} (status=${detail?.status ?? 401}), redirecting to /login`
)
}
window.addEventListener('mc:auth-expired', onExpired)
return () => window.removeEventListener('mc:auth-expired', onExpired)
}, [])

return null
}
87 changes: 40 additions & 47 deletions src/components/panels/settings-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Loader } from '@/components/ui/loader'
import { clearOnboardingDismissedThisSession, clearOnboardingReplayFromStart } from '@/lib/onboarding-session'
import { resolveCoordinatorDeliveryTarget, type CoordinatorAgentRecord } from '@/lib/coordinator-routing'
import type { GatewaySession } from '@/lib/sessions'
import { apiFetch } from '@/lib/api-client'

interface Setting {
key: string
Expand Down Expand Up @@ -188,7 +189,7 @@ export function SettingsPanel() {

const fetchSettings = useCallback(async () => {
try {
const res = await fetch('/api/settings')
const res = await apiFetch<Response>('/api/settings', { raw: true, redirectOnUnauthenticated: false })
if (res.status === 401) {
window.location.assign('/login?next=%2Fsettings')
return
Expand All @@ -211,39 +212,33 @@ export function SettingsPanel() {

// Load agent options for coordinator routing dropdown
try {
const agentsRes = await fetch('/api/agents?limit=200')
if (agentsRes.ok) {
const agentsData = await agentsRes.json()
setCoordinatorTargetAgents(parseCoordinatorTargetAgents(agentsData.agents || []))
}
const agentsData = await apiFetch<any>('/api/agents?limit=200')
setCoordinatorTargetAgents(parseCoordinatorTargetAgents(agentsData.agents || []))
} catch {
// non-critical
}

// Load live sessions to preview coordinator routing resolution
try {
const sessionsRes = await fetch('/api/sessions')
if (sessionsRes.ok) {
const sessionsData = await sessionsRes.json()
const mapped: CoordinatorSession[] = Array.isArray(sessionsData.sessions)
? sessionsData.sessions.map((session: any) => ({
key: String(session?.key || ''),
agent: String(session?.agent || ''),
source: typeof session?.source === 'string' ? session.source : undefined,
sessionId: String(session?.id || session?.key || ''),
updatedAt: Number(session?.lastActivity || session?.startTime || 0),
chatType: String(session?.kind || 'unknown'),
channel: String(session?.channel || ''),
model: String(session?.model || ''),
totalTokens: 0,
inputTokens: 0,
outputTokens: 0,
contextTokens: 0,
active: Boolean(session?.active),
})).filter((session: CoordinatorSession) => session.key && session.agent)
: []
setCoordinatorSessions(mapped)
}
const sessionsData = await apiFetch<any>('/api/sessions')
const mapped: CoordinatorSession[] = Array.isArray(sessionsData.sessions)
? sessionsData.sessions.map((session: any) => ({
key: String(session?.key || ''),
agent: String(session?.agent || ''),
source: typeof session?.source === 'string' ? session.source : undefined,
sessionId: String(session?.id || session?.key || ''),
updatedAt: Number(session?.lastActivity || session?.startTime || 0),
chatType: String(session?.kind || 'unknown'),
channel: String(session?.channel || ''),
model: String(session?.model || ''),
totalTokens: 0,
inputTokens: 0,
outputTokens: 0,
contextTokens: 0,
active: Boolean(session?.active),
})).filter((session: CoordinatorSession) => session.key && session.agent)
: []
setCoordinatorSessions(mapped)
} catch {
// non-critical
}
Expand All @@ -257,11 +252,8 @@ export function SettingsPanel() {
const fetchApiKeyInfo = useCallback(async () => {
setApiKeyLoading(true)
try {
const res = await fetch('/api/tokens/rotate')
if (res.ok) {
const data = await res.json()
setApiKeyInfo(data)
}
const data = await apiFetch<ApiKeyInfo>('/api/tokens/rotate')
setApiKeyInfo(data)
} catch {
// Silent — non-critical
} finally {
Expand All @@ -272,7 +264,7 @@ export function SettingsPanel() {
const handleRotateKey = async () => {
setRotating(true)
try {
const res = await fetch('/api/tokens/rotate', { method: 'POST' })
const res = await apiFetch<Response>('/api/tokens/rotate', { method: 'POST', raw: true })
const data = await res.json()
if (res.ok) {
setNewApiKey(data.key)
Expand Down Expand Up @@ -311,10 +303,8 @@ export function SettingsPanel() {

const fetchHermesStatus = useCallback(async () => {
try {
const res = await fetch('/api/hermes')
if (res.ok) {
setHermesStatus(await res.json())
}
const data = await apiFetch<typeof hermesStatus>('/api/hermes')
setHermesStatus(data)
} catch { /* non-critical */ }
}, [])

Expand Down Expand Up @@ -343,10 +333,11 @@ export function SettingsPanel() {

setSaving(true)
try {
const res = await fetch('/api/settings', {
const res = await apiFetch<Response>('/api/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ settings: changes }),
raw: true,
})
const data = await res.json()
if (res.ok) {
Expand All @@ -365,7 +356,7 @@ export function SettingsPanel() {

const handleReset = async (key: string) => {
try {
const res = await fetch(`/api/settings?key=${encodeURIComponent(key)}`, { method: 'DELETE' })
const res = await apiFetch<Response>(`/api/settings?key=${encodeURIComponent(key)}`, { method: 'DELETE', raw: true })
const data = await res.json()
if (res.ok) {
showFeedback(true, `Reset "${key}" to default`)
Expand Down Expand Up @@ -486,7 +477,7 @@ export function SettingsPanel() {
onClick={async () => {
setMcBackupRunning(true)
try {
const res = await fetch('/api/backup', { method: 'POST' })
const res = await apiFetch<Response>('/api/backup', { method: 'POST', raw: true })
const data = await res.json()
if (res.ok) {
showFeedback(true, `MC backup created (${(data.backup?.size / 1024).toFixed(0)} KB)`)
Expand All @@ -510,7 +501,7 @@ export function SettingsPanel() {
onClick={async () => {
setGwBackupRunning(true)
try {
const res = await fetch('/api/backup?target=gateway', { method: 'POST' })
const res = await apiFetch<Response>('/api/backup?target=gateway', { method: 'POST', raw: true })
const data = await res.json()
if (res.ok) {
showFeedback(true, `Gateway backup created: ${data.output}`)
Expand Down Expand Up @@ -542,7 +533,7 @@ export function SettingsPanel() {
onClick={async () => {
setReplayingOnboarding(true)
try {
await fetch('/api/onboarding', {
await apiFetch('/api/onboarding', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'reset' }),
Expand Down Expand Up @@ -610,10 +601,11 @@ export function SettingsPanel() {
setHermesHookAction(true)
const action = hermesStatus.hookInstalled ? 'uninstall-hook' : 'install-hook'
try {
const res = await fetch('/api/hermes', {
const res = await apiFetch<Response>('/api/hermes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action }),
raw: true,
})
const data = await res.json()
if (res.ok) {
Expand Down Expand Up @@ -809,10 +801,11 @@ export function SettingsPanel() {
setHookProfile(profile.value)
setHookProfileSaving(true)
try {
const res = await fetch('/api/settings', {
const res = await apiFetch<Response>('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'hook_profile', value: profile.value }),
raw: true,
})
if (res.ok) {
showFeedback(true, `Hook profile set to ${profile.label}`)
Expand Down Expand Up @@ -1014,7 +1007,7 @@ function InterfaceModeSelector() {
setInterfaceMode(mode)
setSaving(true)
try {
await fetch('/api/settings', {
await apiFetch('/api/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ settings: { 'general.interface_mode': mode } }),
Expand Down Expand Up @@ -1109,7 +1102,7 @@ function AccountOAuthSection() {
const handleDisconnect = async () => {
setDisconnecting(true)
try {
const res = await fetch('/api/auth/google/disconnect', { method: 'POST' })
const res = await apiFetch<Response>('/api/auth/google/disconnect', { method: 'POST', raw: true })
const data = await res.json().catch(() => ({}))
if (res.ok) {
setFeedback({ ok: true, text: 'Google account disconnected. You can now sign in with username and password.' })
Expand Down
Loading