* ui: Extract server stream lifecycle from chatStore into ChatStreamManager
Discovery, attach/replay, resume retry and the remote-running snapshot
formed a cohesive cluster inside chatStore. It now lives in
chat-streams.svelte.ts as ChatStreamManager, owned by chatStore, which
keeps the public entry points as delegates so components are
unchanged. chatStore: 2877 -> 2418 lines.
* ui: Extract user interaction gates from agenticStore into AgenticGates
Tool permission requests, turn-limit continue prompts and queued
steering messages are the state the loop waits on between turns. They
had no coupling to session state, so they now live in
agentic-gates.svelte.ts; agenticStore keeps delegates so components
are unchanged. agenticStore: 1196 -> 1073 lines.
* ui: Compose MCP resources under mcpStore.resources
Resource state was a second import scope next to mcpStore. Consumers
now go through mcpStore.resources, so the MCP surface is one store;
mcp-resources.svelte.ts stays a separate file owned by mcpStore.
* ui: Reorganize stores into domain namespaces
* fix: Update stale doc comments
* ui: Consolidate conv running-state into a chat activity ledger
Running-state was split across chatStore.chatLoadingStates (local
pipes), ChatStreamManager.remoteRunningConvs (backend sessions) and
attachingConvs (attach lifecycle), unioned by hand in
getAllLoadingChats and cross-cleaned by setChatLoading calling
streams.clearRemoteRunning - the 'spinner ghosts until tab toggle'
workaround.
chatActivityStore now owns both sets with one transition per event:
markLocal / localEnded (local pipe end also drops the stale remote
hint, no cross-owner call) / applyRemoteSnapshot (diffed). The
sidebar reads chatStore.activity.loadingConvs through the unchanged
getAllLoadingChats entry point.
Consequences:
- isStreamingActive and its five manual writers are gone; isStreaming()
now reports whether the active conversation has a live streaming
pipe, which is what all four consumers (assistant row, stop action,
context gauge, chat screen) actually check
- isLoading/isReasoning become derived from the per-conv maps plus
the active conversation, dropping the manual resync in
syncLoadingStateForChat and clearUIState
- attachingConvs and the last-attach coordination disappear from
ChatStreamManager
- getAllStreamingChats (no consumers) is removed
* ui: Give store collaborators narrow host interfaces
Collaborators took 'host: typeof <store>', i.e. the store's entire
public surface, which is how chatStore's streamChatCompletion,
createAssistantMessage, getApiOptions and setStreamingActive got
widened to public. Replace with per-collaborator interfaces carrying
only the members each one drives:
- ChatStreamHost (chat/streams) - activity, processing, streaming
states, abort controller, loading/streaming setters
- ChatFlowsHost (chat/flows) - streaming core, message creation,
per-conv state setters
- McpHealthHost (mcp/health) - connection registry + reconnection
- ModelPropsHost / ModelStatusHost (models) - model rows, feed
updates; the managers write modalities/status back onto the host's
rows, so those members stay writable
- ConversationsPreferencesHost (conversations) - the active row and
the conversation list
The store classes now declare 'implements <Host>' so the contract is
visible at the class level, and the 'import type { <store> }' back
references in the collaborators disappear entirely - the host
contract is local to each collaborator file, and collaborators can
no longer reach around their slice. Members stay public (structural
typing), but the collaborator side is now compiler-enforced.
* test: Chat Activity store test
* refactor: Cleanup
* chore: Remove legacy architecture docs
* ui: Memoize findMessageIndex for the streaming hot path
Streaming looks up the same message index on every chunk, a linear
scan of activeMessages each time. Cache the last lookup and reuse it
after validating the id still sits at the same position (O(1)); any
structural change to the array fails validation and falls back to a
full scan.
* ui: Throttle per-chunk stream state writes to localStorage
saveStreamState ran JSON.stringify + a synchronous localStorage.setItem
on every decoded chunk of the stream. The read loop now goes through a
new saveStreamStateThrottled (one write per conversation per 500ms,
latest value held pending); the public saveStreamState keeps its
immediate-write contract for stream start and pre-fetch, and also
resets the throttle window.
A pending offset is force-flushed at resume boundaries (resumeStream
reads the offset back from localStorage), on visibilitychange->hidden
and on pagehide, so a reload always finds a usable offset. The resume
offset only needs to be roughly current since the server retransmits
from a line boundary and the client discards its partial line.
Adds unit tests for the throttled/flush/clear interplay.
* ui: Compute context gauge timing stats in one pass
currentRead/Fresh/Cache/Output were separate deriveds, each running a
full reverse scan of activeMessages for the last assistant timings,
and cumulative ran its own forward scan plus an agentic filter - 4-5
O(n) passes per chunk while streaming. Replace with a single
summarizeAssistantTimings() pass (last assistant timings, last
agentic llm totals and the cumulative sums) feeding a shared derived
snapshot. Semantics unchanged, including the live-stats overrides and
the agentic llm-totals branch.
* agentic : clear session state when a conversation is deleted
Every conversation that ran an agentic flow left an AgenticSession in the
store forever; clearSession was never called. conversationsStore now
notifies deletion listeners and agenticStore drops the matching sessions,
avoiding a circular import back into conversationsStore.
* chat : extract ChatService.normalizeMessagesForApi
The DB->API message normalization (convert + drop empty system messages)
was duplicated in sendMessage, preEncode and the agentic flow. Extract it
into one shared method and call it from all three.
* sse : share record splitting and data extraction
splitSseRecords and extractSseDataPayload centralize the record-boundary
splitting and data: line extraction used by parseSseJsonStream and the
models status feed. chat.service keeps its own line-based parser for
resume support.
* api : delegate apiFetchWithParams to apiFetch
apiFetchWithParams duplicated apiFetch's headers/fetch/error handling
body-for-body; it only differs in URL construction. Build the URL and
delegate.
* chat flows : dedupe title, timings and cleanup handling
- conversationsStore.applyTitleFromContent centralizes the title-from-first-
message logic duplicated in 5 places
- ChatProcessingStore.applyStreamTimings centralizes the onTimings handler
shared by the chat and continue flows
- host.cleanupStreaming centralizes the loading/streaming/processing reset
repeated across the continue flow's exit paths
* conversations : centralize conversation update mirroring
rename, pin, mcp override, reasoning effort and cwd all repeated the same
write-DB-then-mirror-into-list-and-active dance. A single
applyConversationUpdate(id, updates) on the host collapses all five and
removes the forgot-to-mirror-one-field bug class. Drops the redundant
array reassignment in setCwd (deep field assignment is reactive).
* mcp : dedupe tool execution, server parsing and tool indexing
- executeTool delegates to executeToolByName (only diff was argument parsing)
- drop the private #parseServerSettings copy; use parseMcpServerSettings
- cache getServers() keyed on the raw config value (hot path)
- indexServerTools() unifies the three identical toolsIndex rebuild loops
Assisted-by: Claude
* mcp : share cursor pagination and tool indexing
- MCPService.paginate() collapses the identical do-while loops in
listAllResources and listAllResourceTemplates
- promoteHealthCheckToConnection now uses indexServerTools like the other
connect paths
Assisted-by: Claude
* database : share message parent-child bookkeeping
- addChildToParent() dedups the append-to-children update in createMessageBranch
and createSystemMessage
- removeChildFromParent() dedups the remove-from-children cleanup in deleteMessage
and deleteMessageCascading
- bulkAdd the cloned messages when forking a conversation instead of one add
per message
Assisted-by: Claude
* chore: Lint/format
* fix: `pagehide` event from `window`
* refactor: Api Fetch util
* docs : rewrite architecture sections in README
Update the high-level diagram, routes, hooks, stores, services and data
flow tables to match the current UI structure (mcp/settings/search
routes, agentic/tools/mcp stores, MCPService/ToolsService/SandboxService,
/tools API). Fix stale architectural patterns for per-conversation state
and modality validation.
* chore : add ESLint rule for blank lines between accessors
Enforce a blank line between consecutive class accessors. The core
padding-line-between-statements rule does not cover class members, so a
local rule is needed.
* refactor : reorder store members and unify naming
Order store class members as public fields, private fields, constructor,
getters, public methods, then private methods. Normalize private naming
to the `private` keyword (drop `#` and the `_` prefix where there is no
matching public getter). Rename conversationsStore.init() to
initialize() to match the other stores.
* refactor : prefix lookup methods with get in agentic and chat stores
Unify bare-name lookup methods with the get* prefix used across the
other stores (mcp, models, tools, settings). Renames currentTurn,
totalToolCalls, lastError, streamingToolCall, executingToolCallId,
pendingPermissionRequest, pendingContinueRequest,
pendingSteeringMessageContent, pendingSteeringMessageExtras in the
agentic store and pendingMessageContent, pendingMessageExtras in the
chat store. Updates the two consuming components and a doc comment.
* refactor: Clean up comments in stores' and services' code
* chore : add ESLint rule for class member ordering
Enforce structural order (public fields -> private fields -> constructor ->
getters -> setters -> public methods -> private methods) with alphabetical
sorting within each group via perfectionist/sort-classes. Dependency
detection keeps Svelte $derived fields in a valid dependency order instead
of alphabetizing them, since Svelte rejects forward references.
Assisted-by: Claude
* refactor : reorder class members to match new ESLint rule
Apply the sort-classes rule across stores, services, hooks and utils.
Pure reordering - verified no logic changes by comparing sorted line
multisets before/after. All tests and svelte-check pass.
452 lines
13 KiB
TypeScript
452 lines
13 KiB
TypeScript
/**
|
|
* modelsStore - Model management for MODEL and ROUTER modes
|
|
*
|
|
* Owns model lists, selection, favorites and load/unload state. Composes the
|
|
* per-model props cache (modalities, thinking detection) as
|
|
* {@link ModelsStore.props} and the /models/sse status feed as
|
|
* {@link ModelsStore.status}; tracks which conversations use which models.
|
|
*/
|
|
|
|
import { FAVORITE_MODELS_LOCALSTORAGE_KEY } from '$lib/constants';
|
|
import { ServerModelStatus } from '$lib/enums';
|
|
import { ModelsService } from '$lib/services/models.service';
|
|
// direct imports between stores, not via the barrel, to avoid circular deps
|
|
import { conversationsStore } from '$lib/stores/conversations/index.svelte';
|
|
import { type ModelPropsHost, ModelPropsManager } from '$lib/stores/models/props.svelte';
|
|
import { type ModelStatusHost, ModelStatusManager } from '$lib/stores/models/status.svelte';
|
|
import { serverStore } from '$lib/stores/server.svelte';
|
|
import { getConversationModel } from '$lib/utils/conversation-utils';
|
|
import { SvelteSet } from 'svelte/reactivity';
|
|
import { toast } from 'svelte-sonner';
|
|
|
|
class ModelsStore implements ModelPropsHost, ModelStatusHost {
|
|
error = $state<string | null>(null);
|
|
favoriteModelIds = $state<Set<string>>(this.loadFavoritesFromStorage());
|
|
loading = $state(false);
|
|
models = $state<ModelOption[]>([]);
|
|
routerModels = $state<ApiModelDataEntry[]>([]);
|
|
selectedModelId = $state<string | null>(null);
|
|
selectedModelName = $state<string | null>(null);
|
|
|
|
updating = $state(false);
|
|
|
|
/** Per-model props cache, modalities and thinking detection, composed here. */
|
|
private _props = new ModelPropsManager(this);
|
|
|
|
/** Load/unload operations and the /models/sse status feed, composed here. */
|
|
private _status = new ModelStatusManager(this);
|
|
|
|
// Dedup concurrent fetch() callers — all awaiters share the same inflight promise.
|
|
// Without this, ?model=<name> URL handler races an in-progress fetch and sees an empty list.
|
|
private inflightFetch: Promise<void> | null = null;
|
|
|
|
/**
|
|
* Model the active conversation view resolves to. Router mode: the user's
|
|
* selection first, then the conversation's own model. Otherwise the single
|
|
* served model, from the models list or the server props as a fallback.
|
|
*/
|
|
get activeModelId(): string | null {
|
|
if (!serverStore.isRouterMode) {
|
|
return this.models.length > 0 ? this.models[0].model : this.singleModelName;
|
|
}
|
|
|
|
if (this.selectedModelId) {
|
|
const selected = this.models.find((m) => m.id === this.selectedModelId);
|
|
|
|
if (selected) return selected.model;
|
|
}
|
|
|
|
const conversationModel = getConversationModel(conversationsStore.activeMessages);
|
|
|
|
if (conversationModel) {
|
|
const model = this.models.find((m) => m.model === conversationModel);
|
|
|
|
if (model) return model.model;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
get loadedModelIds(): string[] {
|
|
return this.routerModels
|
|
.filter(
|
|
(m) =>
|
|
m.status.value === ServerModelStatus.LOADED ||
|
|
m.status.value === ServerModelStatus.SLEEPING
|
|
)
|
|
.map((m) => m.id);
|
|
}
|
|
|
|
get props() {
|
|
return this._props;
|
|
}
|
|
|
|
get selectedModel(): ModelOption | null {
|
|
if (!this.selectedModelId) return null;
|
|
|
|
return this.models.find((m) => m.id === this.selectedModelId) ?? null;
|
|
}
|
|
|
|
get selectedModelContextSize(): number | null {
|
|
if (!this.selectedModelName) return null;
|
|
|
|
return this.props.getModelContextSize(this.selectedModelName);
|
|
}
|
|
|
|
/**
|
|
* Get model name in MODEL mode (single model).
|
|
* Extracts from model_path or model_alias from server props.
|
|
* In ROUTER mode, returns null (model is per-conversation).
|
|
*/
|
|
get singleModelName(): string | null {
|
|
if (serverStore.isRouterMode) return null;
|
|
|
|
const props = serverStore.props;
|
|
|
|
if (props?.model_alias) return props.model_alias;
|
|
|
|
if (!props?.model_path) return null;
|
|
|
|
return props.model_path.split(/(\\|\/)/).pop() || null;
|
|
}
|
|
|
|
get status() {
|
|
return this._status;
|
|
}
|
|
|
|
clearSelection(): void {
|
|
this.selectedModelId = null;
|
|
this.selectedModelName = null;
|
|
}
|
|
|
|
/**
|
|
* Auto-selects the first available model if none is selected.
|
|
* Prioritizes:
|
|
* 1. Model from active conversation's last assistant response (if loaded)
|
|
* 2. Model from active conversation's last assistant response (if not loaded)
|
|
* 3. First loaded model (not from active conversation)
|
|
* 4. A favorite model
|
|
* 5. First available model
|
|
*/
|
|
async ensureFirstModelSelected(): Promise<void> {
|
|
if (this.selectedModelName) return;
|
|
|
|
const availableModels = this.getVisibleModels();
|
|
|
|
if (availableModels.length === 0) return;
|
|
|
|
// Try to select model from last assistant response first
|
|
const lastModel = this.getModelFromLastAssistantResponse();
|
|
|
|
if (lastModel) {
|
|
const lastModelOption = availableModels.find((m) => m.model === lastModel);
|
|
|
|
if (lastModelOption) {
|
|
await this.selectModelById(lastModelOption.id);
|
|
|
|
if (this.isModelLoaded(lastModel)) {
|
|
await this.props.fetchModelProps(lastModel);
|
|
}
|
|
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Try a loaded model first
|
|
const loadedModel = availableModels.find((m) => this.isModelLoaded(m.model));
|
|
|
|
if (loadedModel) {
|
|
await this.selectModelById(loadedModel.id);
|
|
await this.props.fetchModelProps(loadedModel.model);
|
|
|
|
return;
|
|
}
|
|
|
|
// Try loading a favorite model
|
|
const favorite = this.favoriteModelIds.values().next()?.value;
|
|
|
|
if (favorite) {
|
|
await this.selectModelById(favorite);
|
|
|
|
return;
|
|
}
|
|
|
|
// Fall back to the first available model
|
|
await this.selectModelById(availableModels[0].id);
|
|
}
|
|
|
|
/**
|
|
* Fetch list of models from server and detect server role.
|
|
* Also fetches modalities for MODEL mode (single model).
|
|
*/
|
|
async fetch(force = false): Promise<void> {
|
|
if (this.inflightFetch) return this.inflightFetch;
|
|
|
|
if (this.models.length > 0 && !force) return;
|
|
|
|
this.inflightFetch = this.runFetch();
|
|
try {
|
|
await this.inflightFetch;
|
|
} finally {
|
|
this.inflightFetch = null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Fetch router models with full metadata (ROUTER mode only).
|
|
* No-op in router mode — fetch() already calls listRouter() internally.
|
|
* Kept for API compatibility (e.g. handleOpenChange dropdown open handler).
|
|
*/
|
|
async fetchRouterModels(): Promise<void> {
|
|
if (!serverStore.isRouterMode) return;
|
|
|
|
try {
|
|
const response = await ModelsService.listRouter();
|
|
|
|
this.routerModels = response.data;
|
|
await this.props.fetchModalitiesForLoadedModels();
|
|
|
|
const visible = this.getVisibleModels();
|
|
|
|
if (visible.length === 1 && this.isModelLoaded(visible[0].model)) {
|
|
this.selectModelById(visible[0].id);
|
|
}
|
|
} catch (error) {
|
|
console.warn('Failed to fetch router models:', error);
|
|
this.routerModels = [];
|
|
}
|
|
}
|
|
|
|
findModelById(modelId: string): ModelOption | null {
|
|
return this.models.find((model) => model.id === modelId) ?? null;
|
|
}
|
|
|
|
findModelByName(modelName: string): ModelOption | null {
|
|
return (
|
|
this.models.find(
|
|
(model) =>
|
|
model.model === modelName || model.id === modelName || model.aliases?.includes(modelName)
|
|
) ?? null
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Gets the model name from the last assistant message in the active conversation.
|
|
* Used by both the chat page and settings page to maintain model consistency.
|
|
*/
|
|
getModelFromLastAssistantResponse(): string | null {
|
|
const messages = conversationsStore.activeMessages;
|
|
|
|
if (!messages || messages.length === 0) return null;
|
|
|
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
if (messages[i].model) {
|
|
return messages[i].model;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
getModelStatus(modelId: string): ServerModelStatus | null {
|
|
const model = this.routerModels.find((m) => m.id === modelId);
|
|
|
|
return model?.status.value ?? null;
|
|
}
|
|
|
|
hasModel(modelName: string): boolean {
|
|
return this.models.some((model) => model.model === modelName);
|
|
}
|
|
|
|
isFavorite(modelId: string): boolean {
|
|
return this.favoriteModelIds.has(modelId);
|
|
}
|
|
|
|
isModelLoaded(modelId: string): boolean {
|
|
const model = this.routerModels.find((m) => m.id === modelId);
|
|
|
|
return (
|
|
model?.status.value === ServerModelStatus.LOADED ||
|
|
model?.status.value === ServerModelStatus.SLEEPING
|
|
);
|
|
}
|
|
|
|
async selectModelById(modelId: string): Promise<void> {
|
|
if (!modelId || this.updating) return;
|
|
|
|
if (this.selectedModelId === modelId) return;
|
|
|
|
const option = this.models.find((model) => model.id === modelId);
|
|
|
|
if (!option) throw new Error('Selected model is not available');
|
|
|
|
this.updating = true;
|
|
this.error = null;
|
|
|
|
try {
|
|
this.selectedModelId = option.id;
|
|
this.selectedModelName = option.model;
|
|
} finally {
|
|
this.updating = false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Select a model by its model name (used for syncing with conversation model).
|
|
*/
|
|
selectModelByName(modelName: string): void {
|
|
const option = this.models.find((model) => model.model === modelName);
|
|
|
|
if (option) {
|
|
this.selectedModelId = option.id;
|
|
this.selectedModelName = option.model;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Auto-selects the model from the last assistant response if available and loaded.
|
|
* Returns true if a model was selected, false otherwise.
|
|
*/
|
|
async selectModelFromLastAssistantResponse(): Promise<boolean> {
|
|
const lastModel = this.getModelFromLastAssistantResponse();
|
|
|
|
if (!lastModel || this.selectedModelName === lastModel) return false;
|
|
|
|
const matchingModel = this.models.find((option) => option.model === lastModel);
|
|
|
|
if (!matchingModel || !this.isModelLoaded(lastModel)) return false;
|
|
|
|
try {
|
|
await this.selectModelById(matchingModel.id);
|
|
console.log(`[modelsStore] Automatically selected model: ${lastModel} from last message`);
|
|
|
|
return true;
|
|
} catch (error) {
|
|
console.warn('[modelsStore] Failed to automatically select model from last message:', error);
|
|
|
|
return false;
|
|
}
|
|
}
|
|
|
|
toDisplayName(id: string): string {
|
|
const segments = id.split(/\\|\//);
|
|
const candidate = segments.pop();
|
|
|
|
return candidate && candidate.trim().length > 0 ? candidate : id;
|
|
}
|
|
|
|
toggleFavorite(modelId: string): void {
|
|
const next = new SvelteSet(this.favoriteModelIds);
|
|
|
|
if (next.has(modelId)) {
|
|
next.delete(modelId);
|
|
} else {
|
|
next.add(modelId);
|
|
}
|
|
|
|
this.favoriteModelIds = next;
|
|
|
|
try {
|
|
localStorage.setItem(FAVORITE_MODELS_LOCALSTORAGE_KEY, JSON.stringify([...next]));
|
|
} catch {
|
|
toast.error('Failed to save favorite models to local storage');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Build ModelOption[] from an API response.
|
|
* Both MODEL and ROUTER modes share the same mapping logic;
|
|
* they differ only in which endpoint is called.
|
|
*/
|
|
private buildModelOptions(
|
|
response: ApiModelListResponse | ApiRouterModelsListResponse
|
|
): ModelOption[] {
|
|
return response.data.map((item: ApiModelDataEntry, index: number) => {
|
|
const details = response.models?.[index];
|
|
const rawCapabilities = Array.isArray(details?.capabilities) ? details?.capabilities : [];
|
|
const displayNameSource =
|
|
details?.name && details.name.trim().length > 0 ? details.name : item.id;
|
|
const modelId = details?.model || item.id;
|
|
|
|
return {
|
|
aliases: item.aliases ?? [],
|
|
capabilities: rawCapabilities.filter((value: unknown): value is string => Boolean(value)),
|
|
description: details?.description,
|
|
details: details?.details,
|
|
id: item.id,
|
|
meta: item.meta ?? null,
|
|
modalities: this.props.buildArchitectureModalities(item.architecture),
|
|
model: modelId,
|
|
name: this.toDisplayName(displayNameSource),
|
|
parsedId: ModelsService.parseModelId(modelId),
|
|
tags: item.tags ?? []
|
|
};
|
|
});
|
|
}
|
|
|
|
/** Fetch models in MODEL mode (single model, standard OpenAI-compatible). */
|
|
private async fetchModelModeInternal(): Promise<ModelOption[]> {
|
|
const response = await ModelsService.list();
|
|
|
|
return this.buildModelOptions(response);
|
|
}
|
|
|
|
/**
|
|
* Filter to models visible in the UI (ui !== false).
|
|
*/
|
|
private getVisibleModels(): ModelOption[] {
|
|
return this.models.filter((option) => this.props.getModelProps(option.model)?.ui !== false);
|
|
}
|
|
|
|
private loadFavoritesFromStorage(): Set<string> {
|
|
try {
|
|
const raw = localStorage.getItem(FAVORITE_MODELS_LOCALSTORAGE_KEY);
|
|
|
|
return raw ? new Set(JSON.parse(raw) as string[]) : new Set();
|
|
} catch {
|
|
toast.error('Failed to load favorite models from local storage');
|
|
|
|
return new Set();
|
|
}
|
|
}
|
|
|
|
private async runFetch(): Promise<void> {
|
|
this.loading = true;
|
|
this.error = null;
|
|
|
|
try {
|
|
if (!serverStore.props) {
|
|
await serverStore.fetch();
|
|
}
|
|
|
|
const router = serverStore.isRouterMode;
|
|
|
|
if (router) {
|
|
const response = await ModelsService.listRouter();
|
|
|
|
this.routerModels = response.data;
|
|
this.models = this.buildModelOptions(response);
|
|
|
|
await this.props.fetchModalitiesForLoadedModels();
|
|
|
|
const visible = this.getVisibleModels();
|
|
|
|
if (visible.length === 1 && this.isModelLoaded(visible[0].model)) {
|
|
this.selectModelById(visible[0].id);
|
|
}
|
|
} else {
|
|
this.models = await this.fetchModelModeInternal();
|
|
}
|
|
} catch (error) {
|
|
this.models = [];
|
|
this.error = error instanceof Error ? error.message : 'Failed to load models';
|
|
|
|
throw error;
|
|
} finally {
|
|
this.loading = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
export const modelsStore = new ModelsStore();
|