* 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.
196 lines
6.6 KiB
TypeScript
196 lines
6.6 KiB
TypeScript
/**
|
|
* ParameterSyncService - Syncs sampling parameters with the server
|
|
*
|
|
* Decides for each sampling parameter whether the user's setting is an
|
|
* override of the server default, and normalizes floating-point values.
|
|
* No reactive state; consumed by settingsStore.
|
|
*/
|
|
|
|
import { SETTINGS_KEYS, SYNCABLE_PARAMETERS } from '$lib/constants';
|
|
import { ParameterSource, SyncableParameterType } from '$lib/enums';
|
|
import type { ParameterInfo, ParameterRecord, ParameterValue } from '$lib/types';
|
|
import { normalizeFloatingPoint } from '$lib/utils';
|
|
|
|
export class ParameterSyncService {
|
|
/**
|
|
* Check if a parameter can be synced from server.
|
|
*
|
|
* @param key - The parameter key to check
|
|
* @returns True if the parameter is in the syncable parameters list
|
|
*/
|
|
static canSyncParameter(key: string): boolean {
|
|
return SYNCABLE_PARAMETERS.some((param) => param.key === key && param.canSync);
|
|
}
|
|
|
|
/**
|
|
* Create a diff between current settings and server defaults.
|
|
* Shows which parameters differ from server values, useful for debugging
|
|
* and for the "Reset to defaults" functionality.
|
|
*
|
|
* @param currentSettings - Current parameter values in the settings store
|
|
* @param serverDefaults - Default values extracted from server props
|
|
* @returns Record of parameter diffs with current value, server value, and whether they differ
|
|
*/
|
|
static createParameterDiff(
|
|
currentSettings: ParameterRecord,
|
|
serverDefaults: ParameterRecord
|
|
): Record<string, { current: ParameterValue; server: ParameterValue; differs: boolean }> {
|
|
const diff: Record<
|
|
string,
|
|
{ current: ParameterValue; server: ParameterValue; differs: boolean }
|
|
> = {};
|
|
|
|
for (const key of this.getSyncableParameterKeys()) {
|
|
const currentValue = currentSettings[key];
|
|
const serverValue = serverDefaults[key];
|
|
|
|
if (serverValue !== undefined) {
|
|
diff[key] = {
|
|
current: currentValue,
|
|
differs: currentValue !== serverValue,
|
|
server: serverValue
|
|
};
|
|
}
|
|
}
|
|
|
|
return diff;
|
|
}
|
|
|
|
/**
|
|
* Extract server default parameters that can be synced from `/props` response.
|
|
* Handles both generation settings parameters and UI-specific settings.
|
|
* Converts samplers array to semicolon-delimited string for UI display.
|
|
*
|
|
* @param serverParams - Raw generation settings from server `/props` endpoint
|
|
* @returns Record of extracted parameter key-value pairs with normalized precision
|
|
*/
|
|
static extractServerDefaults(
|
|
serverParams: ApiLlamaCppServerProps['default_generation_settings']['params'] | null
|
|
): ParameterRecord {
|
|
const extracted: ParameterRecord = {};
|
|
|
|
if (serverParams) {
|
|
for (const param of SYNCABLE_PARAMETERS) {
|
|
if (param.canSync && param.serverKey in serverParams) {
|
|
const value = (serverParams as unknown as Record<string, ParameterValue>)[
|
|
param.serverKey
|
|
];
|
|
|
|
if (value !== undefined) {
|
|
// Apply precision rounding to avoid JavaScript floating-point issues
|
|
extracted[param.key] = this.roundFloatingPoint(value);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Handle samplers array conversion to string
|
|
if (serverParams.samplers && Array.isArray(serverParams.samplers)) {
|
|
extracted[SETTINGS_KEYS.SAMPLERS] = serverParams.samplers.join(';');
|
|
}
|
|
}
|
|
|
|
return extracted;
|
|
}
|
|
|
|
/**
|
|
* Get parameter information including source and values.
|
|
* Used by SettingsChatParameterSourceIndicator to display the correct badge
|
|
* (Custom vs Default) for each parameter in the settings UI.
|
|
*
|
|
* @param key - The parameter key to get info for
|
|
* @param currentValue - The current value of the parameter
|
|
* @param propsDefaults - Server default values from `/props`
|
|
* @param userOverrides - Set of parameter keys explicitly overridden by the user
|
|
* @returns Parameter info with source, server default, and user override values
|
|
*/
|
|
static getParameterInfo(
|
|
key: string,
|
|
currentValue: ParameterValue,
|
|
propsDefaults: ParameterRecord,
|
|
userOverrides: Set<string>
|
|
): ParameterInfo {
|
|
const hasPropsDefault = propsDefaults[key] !== undefined;
|
|
const isUserOverride = userOverrides.has(key);
|
|
// Simple logic: either using default (from props) or custom (user override)
|
|
const source = isUserOverride ? ParameterSource.CUSTOM : ParameterSource.DEFAULT;
|
|
|
|
return {
|
|
serverDefault: hasPropsDefault ? propsDefaults[key] : undefined, // Keep same field name for compatibility
|
|
source,
|
|
userOverride: isUserOverride ? currentValue : undefined,
|
|
value: currentValue
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Get all syncable parameter keys.
|
|
*
|
|
* @returns Array of parameter keys that can be synced from server
|
|
*/
|
|
static getSyncableParameterKeys(): string[] {
|
|
return SYNCABLE_PARAMETERS.filter((param) => param.canSync).map((param) => param.key);
|
|
}
|
|
|
|
/**
|
|
* Merge server defaults with current user settings.
|
|
* User overrides always take priority — only parameters not in `userOverrides`
|
|
* set will be updated from server defaults.
|
|
*
|
|
* @param currentSettings - Current parameter values in the settings store
|
|
* @param serverDefaults - Default values extracted from server props
|
|
* @param userOverrides - Set of parameter keys explicitly overridden by the user
|
|
* @returns Merged parameter record with user overrides preserved
|
|
*/
|
|
static mergeWithServerDefaults(
|
|
currentSettings: ParameterRecord,
|
|
serverDefaults: ParameterRecord,
|
|
userOverrides: Set<string> = new Set()
|
|
): ParameterRecord {
|
|
const merged = { ...currentSettings };
|
|
|
|
for (const [key, serverValue] of Object.entries(serverDefaults)) {
|
|
// Only update if user hasn't explicitly overridden this parameter
|
|
if (!userOverrides.has(key)) {
|
|
merged[key] = this.roundFloatingPoint(serverValue);
|
|
}
|
|
}
|
|
|
|
return merged;
|
|
}
|
|
|
|
/**
|
|
* Validate a server parameter value against its expected type.
|
|
*
|
|
* @param key - The parameter key to validate
|
|
* @param value - The value to validate
|
|
* @returns True if value matches the expected type for this parameter
|
|
*/
|
|
static validateServerParameter(key: string, value: ParameterValue): boolean {
|
|
const param = SYNCABLE_PARAMETERS.find((p) => p.key === key);
|
|
|
|
if (!param) return false;
|
|
|
|
switch (param.type) {
|
|
case SyncableParameterType.NUMBER:
|
|
return typeof value === 'number' && !isNaN(value);
|
|
case SyncableParameterType.STRING:
|
|
return typeof value === 'string';
|
|
case SyncableParameterType.BOOLEAN:
|
|
return typeof value === 'boolean';
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Round floating-point numbers to avoid JavaScript precision issues.
|
|
* E.g., 0.1 + 0.2 = 0.30000000000000004 → 0.3
|
|
*
|
|
* @param value - Parameter value to normalize
|
|
* @returns Precision-normalized value
|
|
*/
|
|
private static roundFloatingPoint(value: ParameterValue): ParameterValue {
|
|
return normalizeFloatingPoint(value) as ParameterValue;
|
|
}
|
|
}
|