Frontend architecture
About 3812 wordsAbout 13 min
The operator-facing admin UI lives in its own repository: spora-ai/spora-frontend. It is a Vue 3 single-page application built with Vite, shipped as a Composer package (spora-frontend, type spora-frontend), and served by the Spora host out of public/dist/.
This document covers how the frontend is structured, how it talks to the backend, and where to plug in new pages and apps.
Tech stack
| Concern | Choice | Notes |
|---|---|---|
| Framework | Vue 3 (<script setup>) | Composition API everywhere; SFCs are the unit of reuse. |
| Build tool | Vite | npm run dev for HMR, npm run build for production. |
| Language | TypeScript (vue-tsc) | Strict mode; npm run build runs vue-tsc before bundling. |
| Styling | Tailwind CSS + radix-vue primitives | Utility-first; radix-vue supplies accessible headless components (dialogs, dropdowns, tooltips). |
| State | Pinia | One store per resource; composables wrap derived state. |
| Icons | lucide-vue-next | Tree-shaken; the shared <Icon> component resolves names from the lucide palette. |
| HTTP | fetch via the shared api/client.ts | Same envelope handling as the backend ({ data } / { error }). |
| Routing | vue-router 4 | Route guards read the auth store. |
| i18n | vue-i18n 11 | Bundled catalogues; the catalogue contract is enforced in CI. |
Build & deploy
From spora-frontend/:
npm install
npm run dev # Vite dev server with HMR (proxies /api/v1 to the host)
npm run build # vue-tsc + vite build → dist/
npm run lint # ESLint
npm test # VitestThe operator skeleton pulls the prebuilt spora-frontend Composer package, which lands at public/dist/. The host serves dist/index.html and dist/assets/* directly — there is no Node runtime in production.
Build provenance: the package’s
composer.jsonships adist/directory containing the Vite output. Operators do not runnpm install/npm run buildin production; rebuilding the frontend happens in thespora-frontendrepo and is published as a new tag of thespora-frontendComposer package.
Talking to the backend
All HTTP traffic goes through one client: src/api/client.ts. It handles:
- Base URL —
import.meta.env.VITE_API_URL(empty string in production; the SPA is served from the same origin as the API). - CSRF —
X-CSRF-Tokenheader injected on POST/PUT/PATCH/DELETE, sourced from the auth store. Falls back toGET /auth/mewhen the token is missing but the user looks logged in. - Session expiry —
setupSessionHandler()lets the router register a callback that fires on a 401UNAUTHENTICATEDresponse, so the user gets a single toast instead of a flood of failures. - Envelope unwrapping —
body.data ?? bodyreturns the inner payload transparently;body.erroris parsed into anApiError(withcode,status,message) and thrown. - Logging —
request()routes 5xx tolog.error, 4xx tolog.warn, and 401 tolog.debug(the toast is the user-facing signal).
Pages never call fetch directly — they import api from @/api/client:
import { api } from '@/api/client'
const { agents } = await api.get<{ agents: Agent[] }>('/agents')
await api.post('/agents', { name: 'Researcher', prompt: '...' })ApiError carries code and status so UI code can branch on machine-readable failures. There is no per-field error map on the class — the envelope is { error: { code, message } }, so VALIDATION_ERROR (HTTP 422) arrives as a single human-readable message for the page to render inline:
try {
await api.post('/agents', payload)
} catch (e) {
if (e instanceof ApiError && e.code === 'VALIDATION_ERROR') {
formError.value = e.message
} else {
toast.error(e.message)
}
}Forms that want per-field errors derive them client-side during local validation (as AgentToolOverrideForm.vue does with its own local fieldErrors ref) — they are not read off the ApiError. The full envelope, the complete error code registry, and the toast mapping are on the Error handling page.
Composables
Composables in src/composables/ hold cross-cutting logic that doesn’t belong in a Pinia store but is reused by multiple pages. Two are wired into nearly every page:
useAdminAuth()
Returns reactive isAdmin and isForbidden flags derived from the auth store’s user.is_admin. Pages use it to gate admin-only UI (tool settings, plugin management, etc.) without re-reading the auth store directly:
const { isAdmin, isForbidden } = useAdminAuth()<template>
<section v-if="isAdmin">…</section>
<div v-else-if="isForbidden" class="text-muted-foreground">…</div>
</template>useFeatureEnabled(key)
Resolves a runtime feature flag against the public config (GET /api/v1/config). Returns a computed boolean that flips when the user reloads or the config refreshes. Use it for opt-in features that operators toggle via environment variables — for example, the Web-UI plugin installer is only shown when SPORA_PLUGIN_INSTALL_ENABLED=true, so its mount point reads:
const pluginInstallEnabled = useFeatureEnabled('plugin_install')<RouterLink v-if="pluginInstallEnabled" :to="{ name: 'plugins-install' }">
Install plugin
</RouterLink>Why a composable, not a constant? Feature flags can change at runtime (the config endpoint is polled by some admin flows). Hiding the link in a
computedkeeps the UI honest without forcing a full refresh.
Pinia stores
One store per resource, defined in src/stores/. Convention:
- State is plain
ref()s (agents,loading,error). - Actions are async functions that call
api.*and translateApiErrorinto a user-readable message. - No normalisation — stores keep the shape the backend returns, so resource objects round-trip cleanly through SSR/serialisation if we ever add it.
Stores expose a load() action that pages call from onMounted and from refresh buttons. App-scoped stores (e.g. the plugin inventory at src/apps/plugins/stores/plugins.ts) live under their app folder, not in the global stores/.
Sub-task cache (sub_agent op)
The useTaskStore exposes a reactive sub-task cache for the SubAgentTool sub_agent op (src/stores/tasks.ts). subTaskCache: Map<number, TaskDetail> is keyed by child task id; fetchSubTaskDetail(id) populates it via GET /api/v1/tasks/{id} and SSE updates for non-active task ids patch the cached entry in place via applyTaskUpdate so per-row status badges flip live without a re-fetch. clearSubTaskCache() empties the map on TaskChatPage unmount so child rows do not leak across parent visits.
TaskDetail.data
The TaskDetail.data field is a free-form JSON column (snake_case, per the backend data JSON column convention) carrying tool-specific side-channel payloads. Today it is read by TaskChatMessageList to render the delegation breadcrumb via data.handover.{target_agent_id, target_agent_name, target_task_id} (the task id is the link’s destination; the breadcrumb falls back to the agent page when it is absent), and by TaskChatPage to drive the sub-agent count badge via data.spawned_sub_task_ids: number[]. Vue components normalise the snake_case payload into camelCase locals — consumers should not hard-code snake_case field access in templates.
i18n
The interface is translated with vue-i18n (Composition API only, legacy: false). Four places carry it:
| Path | What it holds |
|---|---|
src/i18n/index.ts | The createI18n instance, the bundled catalogues, availableLocales. |
src/locales/*.json | One catalogue per locale. en.json is generated; the others are hand-edited. |
src/stores/locale.ts | The Pinia store that owns the active language and resolves it. |
src/components/profile/LocaleSelector.vue | The picker in the profile menu. |
The catalogues are bundled, not fetched
src/i18n/index.ts inlines every src/locales/*.json at build time with import.meta.glob(..., { eager: true }). A locale switch therefore costs no round trip. The alternative — a runtime fetch per locale — would put a request on the critical path of every first paint for a payload of a few KB.
Which language wins
useLocaleStore().init() resolves the active locale in this order:
- the signed-in user’s own preference, stored server-side in
users.locale(not only in the browser — a preference that lives inlocalStoragealone is gone on the next device); - the instance default,
SPORA_DEFAULT_LANG, read from the boot config; en.
Accept-Language is deliberately not consulted: the instance owner sets one language for the install, and a browser header would show the same user two languages on two machines.
The localStorage copy under spora.locale is a boot placeholder, not a fourth link in the chain. It paints the right language before the preference round trip resolves, and init() then overwrites it with the authoritative answer — treating it as a link would pin the browser to a stale language forever, because nothing would ever demote it once the instance default changed.
An untranslated string
The key is the English source text, so en.json is a generated identity map ("Save": "Save"). A key with no translation in the active locale falls back to en, which renders the English text rather than a raw key. The fallback is a safety net, not the everyday path: the CI gate below fails the build when a target locale is missing a key.
Dates, numbers and relative time
src/utils/locale.ts exports activeLocale() — the app’s own locale, not the browser’s, because toLocaleString(undefined, …) follows the runtime’s locale, which is the machine’s. Dates and numbers are formatted through it (toLocaleDateString(activeLocale(), …), n.toLocaleString(activeLocale())), and relative times go through formatRelativeTime(iso, locale) in src/composables/useRelativeTime.ts, which uses Intl.RelativeTimeFormat for every locale except English — English keeps the compact 5m ago form the dashboard has always shipped.
The catalogue is enforced in CI
scripts/i18n.mjs harvests the literal $t('…') / t('…') arguments out of the source, using the two parsers already in the tree (vue-eslint-parser and @typescript-eslint/typescript-estree) rather than a bundler plugin, because the failure output has to name file:line. npm run i18n:extract regenerates en.json; npm run i18n:check writes nothing and fails on:
- a key vue-i18n cannot compile;
en.jsondrifting from the source;- a target locale missing a key, or carrying a key the source no longer has — the English text was edited and the translation was orphaned;
- an empty or English-identical value — an untranslated placeholder that reads as translated until a German user hits it;
- a translation whose placeholders are not the key’s placeholders, which would render them literally;
- raw operator-facing text outside
t().
Both run in .github/workflows/ci.yml: extract first, then check.
What a plugin frontend costs
A plugin frontend that ships its own catalogue brings its own vue-i18n runtime — roughly 74 KB measured — and the host deliberately does not publish an instance of its own for plugins to share (src/apps/registry.ts:53-57). Five plugin frontends therefore ship five copies of the runtime, which is why the per-plugin bundle budget in spora-plugin-typst-frontend was raised from 200 KB to 240 KB.
The trade-off is deliberate: a plugin that could not translate at all would be a plugin an operator cannot read in their own language, and sharing one instance across independently versioned plugins would couple their release cycles. The cost is measured per plugin, and a plugin that does not need a catalogue should not ship one.
The command menu
The chat’s task commands live in useTaskChatCommands() (src/composables/useTaskChatCommands.ts) and render through the shared CommandMenu component (src/components/ui/CommandMenu.vue). The list is data — CommandAction[] — so the menu stays a dumb renderer and a second command is one entry rather than a new component.
A CommandAction carries an id, a label, an optional one-line description, an optional icon (a bundled name or a raw SVG path), a disabled flag and the onSelect callback. CommandMenu owns the open state, closes on an outside click and on Escape, and disables its trigger while an action is in flight — which is how the compaction command locks itself out for the duration of its model round trip.
Today the list holds one command: Compact conversation, which asks the backend to compact the task’s history and reports the outcome as a toast. The menu renders on the follow-up bar, so it is offered for a finished conversation — COMPLETED, FAILED or ABORTED, and only when the agent allows follow-ups. Those are exactly the states the backend accepts a compaction for.
The compacted turns of a chat
A compaction keeps the turns it replaced in the history — the model gets a summary in their place.
The transcript shows the conversation as it happened, with the compaction marked in it. buildChatMessages() (src/composables/useTaskChat.ts) turns a summary row into a summary message, and buildChatBlocks() gives it a block of its own, so the marker stands where the summary row sits. That position is the point in the conversation where the compaction happened: the backend appends the summary row to the history at that moment, so its sequence is the marker’s place. The turns the summary stands in for stay in the transcript — the chat is the history, not the model’s view of it.
CompactionMarker.vue renders the marker: collapsed it says how many turns the summary stands in for (the range the summary carries names them), expanded it shows what the model was given in their place.
The chat’s scroll position
The chat follows the newest message while the agent works: TaskChatPage calls scrollToBottom() after every fetch and on every new history entry, and the message list scrolls its anchor into view.
An operator who scrolls up to read a tool call must not be pulled back down by the next message, so useChatAutoScroll() (src/composables/useChatAutoScroll.ts) sits in front of that call. It watches the surface the transcript scrolls in and holds a paused flag; while the flag is set, follow() does nothing and the chat waits for the operator to ask for the newest message.
The surface is not the message list: the chat column is not height-constrained, so the transcript scrolls in the layout’s scroll container above it. The composable finds it by walking up from the transcript — the first ancestor with overflow-y: auto that actually overflows.
The control that ends the pause is TaskChatScrollToBottom.vue, a round button in the lower right corner of the chat. It is sticky rather than absolute, because the transcript has no box of its own to position against, and it comes after the transcript in the DOM because a sticky element is only pulled up into view when it would otherwise be below the scrollport.
The reasoning-effort picker
The chat can pick a reasoning effort per message. Five modules carry it, and the split is the point: the capability comes from the server, the cache holds it, and the component renders it.
src/composables/useAgentEffort.ts— the capability, the cache and the reconciliation. It asksGET /agents/{id}/effortfor the agent’s level set and the default the agent runs with, and it keeps the operator’s choice in step with the level set: a choice the configuration no longer offers is replaced by the agent’s default, or by the model default when there is none.src/composables/agentEffortCache.ts— the session cache of the capabilities, keyed by agent id. It lives in its own module because the composable that fills it cannot be the one that drops it:useAgentEffortimports the agent store, and the agent store is where the LLM configuration changes.src/components/EffortSelect.vue— the picker, rendered in two places: a labelled select on the initial composer, and an icon-only trigger on the follow-up row. ItsemptyChoiceprop is what lets the same component serve a surface whose empty entry means something else.src/types/effort.ts— the shared vocabulary: the shape of the endpoint’s answer, the selection type, and the known level names. A level is astring, because the configuration’s set is not a fixed scale; the union of the known names is kept for the labels, not for the wire.src/utils/effortLevels.ts— the label of one level, the fallback for a level the endpoint did not name.
Where the picker appears
The composer and the follow-up row are the two the picker has always had. Three more surfaces carry a level of their own, and each reuses useAgentEffort rather than asking the server again:
src/components/PromptTemplateDialog.vue— a saved prompt’s own effort.src/components/shared/ScheduleEditor/ScheduleEffortOverride.vue— a scheduled run’s effort override, rendered on step 3 of the schedule wizard;ScheduleEditor/index.vuecarries it into the payload.src/components/agent/settings/AgentIdentitySection.vue— the agent’s own default.
The three are defaults, not per-message choices, and they say so: an unset effort on a template inherits the agent’s default, and an unset override on a run inherits the template’s. That is what the emptyChoice prop is for — the empty entry reads Model default in the chat, Use the agent default on a template, Use the template default on a run and Inherit on the agent’s own default, where it means the configuration’s default.
The step-cap bound
The agent’s settings form does not know the instance’s ceiling on its own. src/stores/runtimeConfig.ts reads max_agent_steps from GET /api/v1/config and falls back to DEFAULT_MAX_AGENT_STEPS (200) when the key is absent — an older backend sends no key. src/components/agent/settings/AgentIdentitySection.vue uses it as the max of the Max steps input and names the bound in the field’s hint, so a plain user editing their own agent is bounded even though the admin settings are admin-only.
The cache’s invalidation contract
The cached answer carries the agent’s level set and the default it runs with, so it goes stale when either the agent’s effective LLM configuration changes or the agent’s own default_effort does. It is cached for the session, and four rules keep that cache honest:
- It is keyed per agent id. Two agents on one page have two capabilities, and a capability that arrives for one agent never answers for another.
- It is dropped wherever the answer can change. The agent store drops that agent’s entry when the agent is pointed at another LLM configuration — its
llm_driver_config_id— and when the agent’s owndefault_effortchanges: the cached answer carries the default as well as the level set, so either one moving makes it stale. The whole session cache goes when the signed-in user drifts away: the capability belongs to the user who asked for it. The LLM-config, LLM-preferences and group stores drop the whole session cache when a configuration is edited, deleted or made the default, and when a new one is created as the default: any of those can move any agent’s effective configuration, and therefore any agent’s level set. A configuration created as a non-default moves nothing, so the cache stays. An LLM tool override is not one of them — the effort comes from the configuration row the agent resolves to, and the override row is not on that path. - It is epoch-guarded. Every agent carries a counter, bumped whenever its capability is dropped. An answer that was already on the wire when the drop happened describes a configuration that no longer holds — and, after a sign-out, the previous user’s agent — so it is discarded instead of written back.
- The selection lives in the agent store, not in the composer draft. The initial composer and the follow-up row are two component trees that have to agree on the level the operator picked, and the composer’s draft is not shared between them.
The apps/ directory — extending the frontend
Each “app” is a self-contained bundle of pages, components, types, stores, and an API client. The pattern keeps feature work isolated — adding a new top-level page (e.g. Plugins) does not touch the rest of the app.
flowchart TD
root["src/apps/"]
plugins["plugins/"]
api["api/<br/>typed wrappers around<br/>/api/v1/plugins/*"]
components["components/<br/>PluginCard,<br/>MigrationStatusBadge,<br/>PluginDetailDialog"]
pages["pages/<br/>PluginsPage.vue<br/>(mounted by the router)"]
stores["stores/<br/>Pinia store for plugin<br/>inventory state"]
types["types/<br/>PluginResource,<br/>MigrationInfo, etc."]
root --> plugins
plugins --> api
plugins --> components
plugins --> pages
plugins --> stores
plugins --> types
classDef root fill:var(--spora-paper),stroke:var(--spora-warm),color:var(--spora-ink),font-weight:bold
classDef app fill:var(--spora-paper-deep),stroke:var(--spora-warm-deep),color:var(--spora-ink),font-weight:bold
classDef child fill:var(--spora-cream),stroke:var(--spora-warm-mist),color:var(--spora-ink)
class root root
class plugins app
class api,components,pages,stores,types childUse plugins/ as the template for new apps
When you add a new top-level page:
- Create a folder under
src/apps/<your-app>/. - Mirror the layout:
api/,components/,pages/,stores/,types/. - Define resource shapes in
types/and mirror them on the backend (PluginsService↔PluginResource). - Register the page in
src/router/index.tsunder a clear route name and gate it behind a composable if it requires an admin or a feature flag. - Add tests alongside the source (
*.test.tsco-located with the module they cover).
The existing plugins/ app is the canonical reference implementation — read it before adding a new one.
Routing
src/router/index.ts declares every page. Routes use named navigation guards for auth and admin gating:
{
path: '/admin/plugins',
name: 'admin-plugins',
component: () => import('@/apps/plugins/pages/PluginsPage.vue'),
meta: { requiresAdmin: true },
}The global guard reads meta.requiresAdmin / meta.requiresAuth and short-circuits to /login or /403 accordingly.
Where to look next
src/api/client.ts— every HTTP call in the app routes through this module.src/composables/useAdminAuth.ts— the canonical admin-gate pattern.src/composables/useFeatureEnabled.ts— runtime feature flags from/api/v1/config.src/components/agent/TaskChat/SubAgentToolCall.vue— the row widget rendered when a sub-agent op reports the spawned child ids —sub_agentandsub_agent_continueboth do (one row per spawned child, live status fromsubTaskCache).src/components/agent/TaskChat/MediaEmbedFrame.vue— the framed widget a script-capable media asset renders as. The chat’s HTML goes throughrenderMarkdown()— the tool bubble and the reasoning row — whose DOMPurify allow-list carries noiframeand noscript, so the embed is its own component with its own<iframe>rather than markup in the bubble. Itssandboxattribute mirrors theContent-Security-Policythe embed route sends; the header is the ceiling the browser enforces, andallow-same-originis never present — with it, a same-origin framed document could remove its own sandbox.src/components/agent/TaskChat/MessageContent.vue— one assistant message, rendered. A message may ask for a live frame by linking an asset’s embed route, and the chat renders the message as segments (renderMarkdownSegments()insrc/composables/useMarkdown.ts) because a Vue component cannot live inside the markup the sanitiser produced — so the reference is a segment and the frame is mounted where it stood. A reference that cannot be framed stays the link the model wrote.src/composables/useMessageEmbeds.ts— resolves the references in a message to descriptors from the server (POST /api/v1/media/resolve) and hands the frame itsurl,mimeandscripts. The descriptor’surlis checked to be a same-origin path before it reaches the frame.src/composables/useTaskChatCommands.ts— the task commands the chat offers, as data.src/composables/useAgentEffort.ts— the agent’s reasoning-effort capability, and the reconciliation that keeps the picked level in step with it.src/components/EffortSelect.vue— the effort picker, rendered in the composer and on the follow-up row.src/components/ui/CommandMenu.vue— the shared command-menu component those commands render through.src/apps/plugins/— the template for adding a new top-level app.src/stores/auth.ts— session, login, CSRF token.src/i18n/index.ts— the i18n instance, the bundled catalogues and the locale set the picker offers.scripts/i18n.mjs— the catalogue extractor and the CI rules that keepsrc/locales/*.jsonhonest.