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
}
21 changes: 11 additions & 10 deletions src/components/chat/chat-workspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { SessionMessage, shouldShowTimestamp, type SessionTranscriptMessage } fr
import { getSessionKindLabel, SessionKindAvatar } from './session-kind-brand'
import { TerminalView } from '@/components/terminal/terminal-view'
import { SplitPaneLayout, type SplitPane } from '@/components/terminal/split-pane-layout'
import { apiFetch } from '@/lib/api-client'

const log = createClientLogger('ChatWorkspace')

Expand Down Expand Up @@ -79,9 +80,7 @@ export function ChatWorkspace({ mode = 'embedded', onClose }: ChatWorkspaceProps
useEffect(() => {
async function loadAgents() {
try {
const res = await fetch('/api/agents')
if (!res.ok) return
const data = await res.json()
const data = await apiFetch<any>('/api/agents')
if (data.agents) setAgents(data.agents)
} catch (err) {
log.error('Failed to load agents:', err)
Expand All @@ -100,9 +99,7 @@ export function ChatWorkspace({ mode = 'embedded', onClose }: ChatWorkspaceProps
}

try {
const res = await fetch(`/api/chat/messages?conversation_id=${encodeURIComponent(activeConversation)}&limit=100`)
if (!res.ok) return
const data = await res.json()
const data = await apiFetch<any>(`/api/chat/messages?conversation_id=${encodeURIComponent(activeConversation)}&limit=100`)
if (data.messages) setChatMessages(data.messages)
} catch (err) {
log.error('Failed to load messages:', err)
Expand Down Expand Up @@ -164,7 +161,7 @@ export function ChatWorkspace({ mode = 'embedded', onClose }: ChatWorkspaceProps
setIsGenerating(true)

try {
const res = await fetch('/api/chat/messages', {
const res = await apiFetch<Response>('/api/chat/messages', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
Expand All @@ -176,6 +173,7 @@ export function ChatWorkspace({ mode = 'embedded', onClose }: ChatWorkspaceProps
attachments,
forward: true,
}),
raw: true,
})

if (res.ok) {
Expand Down Expand Up @@ -287,10 +285,11 @@ export function ChatWorkspace({ mode = 'embedded', onClose }: ChatWorkspaceProps
color: payload.colorTag || null,
}

const res = await fetch('/api/chat/session-prefs', {
const res = await apiFetch<Response>('/api/chat/session-prefs', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
raw: true,
})
const data = await res.json().catch(() => ({}))
if (!res.ok) {
Expand Down Expand Up @@ -587,7 +586,7 @@ function SessionConversationView({
if (isGatewaySession) {
// Gateway sessions: forward message to the agent via chat messages API
const agentName = session.agent || session.sessionId.split(':')[1] || 'unknown'
const res = await fetch('/api/chat/messages', {
const res = await apiFetch<Response>('/api/chat/messages', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
Expand All @@ -599,6 +598,7 @@ function SessionConversationView({
forward: true,
sessionKey: session.sessionKey || undefined,
}),
raw: true,
})
const data = await res.json().catch(() => ({}))
if (!res.ok) {
Expand All @@ -612,14 +612,15 @@ function SessionConversationView({
// Refresh transcript after a short delay to capture the response
setTimeout(() => onRefreshTranscript(), 2000)
} else {
const res = await fetch('/api/sessions/continue', {
const res = await apiFetch<Response>('/api/sessions/continue', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
kind: session.sessionKind,
id: session.sessionId,
prompt,
}),
raw: true,
})
const data = await res.json().catch(() => ({}))
if (!res.ok) {
Expand Down
21 changes: 11 additions & 10 deletions src/components/chat/conversation-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { useSmartPoll } from '@/lib/use-smart-poll'
import { createClientLogger } from '@/lib/client-logger'
import { Button } from '@/components/ui/button'
import { SessionKindAvatar, SessionKindPill } from './session-kind-brand'
import { apiFetch } from '@/lib/api-client'

const log = createClientLogger('ConversationList')

Expand Down Expand Up @@ -200,10 +201,11 @@ export function ConversationList({ onNewConversation: _onNewConversation }: Conv
if (name !== undefined) body.name = name || null
if (color !== undefined) body.color = color || null

const res = await fetch('/api/chat/session-prefs', {
const res = await apiFetch<Response>('/api/chat/session-prefs', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
raw: true,
})
if (!res.ok) {
log.error('Failed to save session pref, server returned', res.status)
Expand Down Expand Up @@ -250,17 +252,16 @@ export function ConversationList({ onNewConversation: _onNewConversation }: Conv
const loadConversations = useCallback(async () => {
try {
const sessionsUrl = '/api/sessions'
const requests: Promise<Response>[] = [
fetch(sessionsUrl),
fetch('/api/chat/session-prefs'),
]
const [sessionsData, prefs] = await Promise.all([
apiFetch<any>(sessionsUrl),
apiFetch<any>('/api/chat/session-prefs'),
])

const [sessionsRes, prefsRes] = await Promise.all(requests)
const sessionsData = sessionsRes.ok ? readSessions(await sessionsRes.json()) : []
const prefs = prefsRes.ok ? readSessionPrefs(await prefsRes.json().catch(() => null)) : {}
const validSessions = sessionsData ? readSessions(sessionsData) : []
const validPrefs = prefs ? readSessionPrefs(prefs) : {}

const providerSessions = sessionsData
.map((s, idx: number) => {
const providerSessions = (sessionsData as any[])
.map((s: any, idx: number) => {
const lastActivityMs = Number(s.lastActivity || s.startTime || 0)
const updatedAt = lastActivityMs > 1_000_000_000_000
? Math.floor(lastActivityMs / 1000)
Expand Down
4 changes: 3 additions & 1 deletion src/components/chat/message-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useRef, useEffect, useState, useCallback } from 'react'
import { useMissionControl, ChatMessage } from '@/store'
import { MessageBubble } from './message-bubble'
import { Button } from '@/components/ui/button'
import { apiFetch } from '@/lib/api-client'

function formatDateGroup(timestamp: number): string {
const date = new Date(timestamp * 1000)
Expand Down Expand Up @@ -98,7 +99,7 @@ export function MessageList() {
updatePendingMessage(msg.id, { pendingStatus: 'sending' })

try {
const res = await fetch('/api/chat/messages', {
const res = await apiFetch<Response>('/api/chat/messages', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
Expand All @@ -109,6 +110,7 @@ export function MessageList() {
message_type: msg.message_type,
forward: true,
}),
raw: true,
})

if (res.ok) {
Expand Down
64 changes: 30 additions & 34 deletions src/components/dashboard/dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { SignalPill, getLocalOsStatus, getProviderHealth, getMcHealth } from './
import { OnboardingChecklistWidget } from './widgets/onboarding-checklist-widget'
import { EmptyStateLaunchpad } from './empty-state-launchpad'
import { WidgetGrid } from './widget-grid'
import { apiFetch } from '@/lib/api-client'
import type { DbStats, ClaudeStats, LogLike, DashboardData } from './widget-primitives'

export function Dashboard() {
Expand Down Expand Up @@ -55,61 +56,56 @@ export function Dashboard() {
const requests: Promise<void>[] = []

requests.push(
fetch('/api/status?action=dashboard')
.then(async (res) => {
if (!res.ok) return
const data = await res.json()
(async () => {
try {
const data = await apiFetch<any>('/api/status?action=dashboard')
if (data && !data.error) {
setSystemStats(data)
if (data.db) setDbStats(data.db)
}
})
.catch(() => {})
.finally(() => setLoading(prev => ({ ...prev, system: false })))
} catch {}
finally { setLoading(prev => ({ ...prev, system: false })) }
})()
)

requests.push(
fetch('/api/sessions')
.then(async (res) => {
if (!res.ok) return
const data = await res.json()
(async () => {
try {
const data = await apiFetch<any>('/api/sessions')
if (data && !data.error) setSessions(data.sessions || data)
})
.catch(() => {})
.finally(() => setLoading(prev => ({ ...prev, sessions: false })))
} catch {}
finally { setLoading(prev => ({ ...prev, sessions: false })) }
})()
)

if (isLocal) {
requests.push(
fetch('/api/claude/sessions')
.then(async (res) => {
if (!res.ok) return
const data = await res.json()
(async () => {
try {
const data = await apiFetch<any>('/api/claude/sessions')
if (data?.stats) setClaudeStats(data.stats)
})
.catch(() => {})
.finally(() => setLoading(prev => ({ ...prev, claude: false })))
} catch {}
finally { setLoading(prev => ({ ...prev, claude: false })) }
})()
)

requests.push(
fetch('/api/github?action=stats')
.then(async (res) => {
if (!res.ok) return
const data = await res.json()
(async () => {
try {
const data = await apiFetch<any>('/api/github?action=stats')
if (data && !data.error) setGithubStats(data)
})
.catch(() => {})
.finally(() => setLoading(prev => ({ ...prev, github: false })))
} catch {}
finally { setLoading(prev => ({ ...prev, github: false })) }
})()
)

requests.push(
fetch('/api/hermes')
.then(async (res) => {
if (!res.ok) return
const data = await res.json()
(async () => {
try {
const data = await apiFetch<any>('/api/hermes')
if (data?.cronJobCount != null) setHermesCronJobCount(data.cronJobCount)
})
.catch(() => {})
} catch {}
})()
)
} else {
setLoading(prev => ({ ...prev, claude: false, github: false }))
Expand Down
Loading