Moves the agent model out of env-only config into an admin-editable Settings
section, and enforces is_admin for the first time — it has been in the schema
since migration 0001, plumbed to the client, and checked nowhere.
Backend:
- Migration 0010: instance_settings, a single-row (CHECK id=1) table — pansy's
first instance-level state. Holds agent_model ('' = inherit env) and
agent_enabled (NULL = inherit env), version-guarded like every mutable row.
SECRETS STAY IN ENV: OLLAMA_CLOUD_API_KEY is never stored here.
- requireAdmin at the service seam (authoritative) plus a cheap middleware
early-403. Non-admin gets 403, not 404 — settings existence isn't masked.
- EffectiveAgent resolves DB-over-env (model, enabled); key always from env.
- The live Runner is hot-swapped, not built once. agentHolder holds it behind
an atomic.Pointer; the chat routes are now registered UNCONDITIONALLY and
nil-check agent.get(), so a settings change turns the assistant on/off/onto a
new model with no restart and no race against in-flight readers. /capabilities
reads the pointer, so it reports what's live, not what booted.
- internal/agentmodel is a new leaf package holding the one place that knows how
to turn a spec into a model. Both agent (to run) and service (to validate a
spec before storing it) import it; it can't live in agent, which imports
service. Settings PATCH validates the spec via Parse, so a typo is a 400 now
rather than a broken assistant on the next turn.
Frontend:
- /settings route (admin guard), a Settings page (model field, tri-state
enabled, live status), nav link shown only to admins.
- useCapabilities drops staleTime:Infinity — the assistant can now change under
a running page — and the settings save invalidates it.
Contract change: chat routes always exist, so "assistant off" is a runtime 503
+ capabilities:false, not a missing route. Updated the test that asserted the
old shape.
Verified live against the built binary: disable flips capabilities to false and
logs it; re-enable with a new model swaps it back; a bad spec is rejected 400;
the setting persists across a restart. Swap is race-clean under `go test -race`.
Docs: README (precedence + key-stays-in-env), DESIGN (decision + routes),
CLAUDE (don't re-add conditional route registration; key never in the DB).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01H3zbym8Doka2d7D48maSgZ
165 lines
5.1 KiB
TypeScript
165 lines
5.1 KiB
TypeScript
import {
|
|
createRootRouteWithContext,
|
|
createRoute,
|
|
createRouter,
|
|
redirect,
|
|
} from '@tanstack/react-router'
|
|
import type { QueryClient } from '@tanstack/react-query'
|
|
import { AppShell } from '@/components/layout/AppShell'
|
|
import { NotFound } from '@/components/NotFound'
|
|
import { RouteError } from '@/components/RouteError'
|
|
import { LoginPage } from '@/pages/LoginPage'
|
|
import { RegisterPage } from '@/pages/RegisterPage'
|
|
import { GardensPage } from '@/pages/GardensPage'
|
|
import { GardenEditorPage } from '@/pages/GardenEditorPage'
|
|
import { PublicGardenPage } from '@/pages/PublicGardenPage'
|
|
import { PlantsPage } from '@/pages/PlantsPage'
|
|
import { SettingsPage } from '@/pages/SettingsPage'
|
|
import { meQueryOptions } from '@/lib/auth'
|
|
import { queryClient } from '@/lib/queryClient'
|
|
import { safeRedirectPath } from '@/lib/redirect'
|
|
|
|
interface RouterContext {
|
|
queryClient: QueryClient
|
|
}
|
|
|
|
const rootRoute = createRootRouteWithContext<RouterContext>()({
|
|
component: AppShell,
|
|
// A beforeLoad/loader failure that isn't a redirect (e.g. /auth/me errors with
|
|
// a 500 or the network drops) lands here instead of a blank screen.
|
|
errorComponent: RouteError,
|
|
// Unknown paths render inside the app shell rather than a blank screen.
|
|
notFoundComponent: NotFound,
|
|
})
|
|
|
|
// requireAuth: resolve the current user (shared cache with useMe); send anyone
|
|
// unauthenticated to /login, remembering the path they were headed to.
|
|
async function requireAuth(context: RouterContext, path: string) {
|
|
const me = await context.queryClient.ensureQueryData(meQueryOptions)
|
|
if (!me) {
|
|
throw redirect({ to: '/login', search: { redirect: path } })
|
|
}
|
|
}
|
|
|
|
// requireGuest: keep already-authenticated users off /login and /register.
|
|
async function requireGuest(context: RouterContext, redirectTo: string) {
|
|
const me = await context.queryClient.ensureQueryData(meQueryOptions)
|
|
if (me) {
|
|
throw redirect({ to: redirectTo })
|
|
}
|
|
}
|
|
|
|
// requireAdmin: authenticated AND admin. A non-admin who navigates to /settings
|
|
// is sent to /gardens rather than shown a page whose API calls would 403. This
|
|
// is convenience routing, not the security boundary — the server's requireAdmin
|
|
// is authoritative.
|
|
async function requireAdmin(context: RouterContext, path: string) {
|
|
const me = await context.queryClient.ensureQueryData(meQueryOptions)
|
|
if (!me) {
|
|
throw redirect({ to: '/login', search: { redirect: path } })
|
|
}
|
|
if (!me.isAdmin) {
|
|
throw redirect({ to: '/gardens' })
|
|
}
|
|
}
|
|
|
|
const indexRoute = createRoute({
|
|
getParentRoute: () => rootRoute,
|
|
path: '/',
|
|
beforeLoad: () => {
|
|
throw redirect({ to: '/gardens' })
|
|
},
|
|
})
|
|
|
|
interface LoginSearch {
|
|
redirect?: string
|
|
error?: string
|
|
}
|
|
|
|
const loginRoute = createRoute({
|
|
getParentRoute: () => rootRoute,
|
|
path: 'login',
|
|
// Optional properties (not `key: undefined`) so links to /login don't have to
|
|
// pass a search object.
|
|
validateSearch: (search: Record<string, unknown>): LoginSearch => {
|
|
const out: LoginSearch = {}
|
|
if (typeof search.redirect === 'string') out.redirect = search.redirect
|
|
if (typeof search.error === 'string') out.error = search.error
|
|
return out
|
|
},
|
|
beforeLoad: ({ context, search }) => requireGuest(context, safeRedirectPath(search.redirect)),
|
|
component: LoginPage,
|
|
})
|
|
|
|
const registerRoute = createRoute({
|
|
getParentRoute: () => rootRoute,
|
|
path: 'register',
|
|
beforeLoad: ({ context }) => requireGuest(context, '/gardens'),
|
|
component: RegisterPage,
|
|
})
|
|
|
|
const gardensRoute = createRoute({
|
|
getParentRoute: () => rootRoute,
|
|
path: 'gardens',
|
|
beforeLoad: ({ context, location }) => requireAuth(context, location.href),
|
|
component: GardensPage,
|
|
})
|
|
|
|
const gardenEditorRoute = createRoute({
|
|
getParentRoute: () => rootRoute,
|
|
path: 'gardens/$gardenId',
|
|
// ?focus=<objectId> frames that object on load.
|
|
validateSearch: (search: Record<string, unknown>): { focus?: number } => {
|
|
const f = Number(search.focus)
|
|
return Number.isInteger(f) && f > 0 ? { focus: f } : {}
|
|
},
|
|
beforeLoad: ({ context, location }) => requireAuth(context, location.href),
|
|
component: GardenEditorPage,
|
|
})
|
|
|
|
const plantsRoute = createRoute({
|
|
getParentRoute: () => rootRoute,
|
|
path: 'plants',
|
|
beforeLoad: ({ context, location }) => requireAuth(context, location.href),
|
|
component: PlantsPage,
|
|
})
|
|
|
|
const settingsRoute = createRoute({
|
|
getParentRoute: () => rootRoute,
|
|
path: 'settings',
|
|
beforeLoad: ({ context, location }) => requireAdmin(context, location.href),
|
|
component: SettingsPage,
|
|
})
|
|
|
|
// Public read-only garden by share token. Deliberately has NO beforeLoad auth
|
|
// guard, so a logged-out visitor viewing a shared link is never redirected to
|
|
// /login or OIDC.
|
|
const publicGardenRoute = createRoute({
|
|
getParentRoute: () => rootRoute,
|
|
path: 'g/$token',
|
|
component: PublicGardenPage,
|
|
})
|
|
|
|
const routeTree = rootRoute.addChildren([
|
|
indexRoute,
|
|
loginRoute,
|
|
registerRoute,
|
|
gardensRoute,
|
|
gardenEditorRoute,
|
|
plantsRoute,
|
|
settingsRoute,
|
|
publicGardenRoute,
|
|
])
|
|
|
|
export const router = createRouter({
|
|
routeTree,
|
|
defaultPreload: 'intent',
|
|
context: { queryClient },
|
|
})
|
|
|
|
declare module '@tanstack/react-router' {
|
|
interface Register {
|
|
router: typeof router
|
|
}
|
|
}
|