chore: 项目基线(基于 WeKnora 定制版,整理文件忽略规则)
This commit is contained in:
commit
9097ee699d
5769 files changed
+1446466
No files matched your search
@@ -0,0 +1,485 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { computed, ref, shallowReactive, shallowRef, watch } from 'vue'
|
||||
import type { PageContextPayload, PageSelectionPayload } from '@/api/chat/streame'
|
||||
import {
|
||||
DEFAULT_ASSISTANT_ACCESS_LEVEL,
|
||||
capAssistantAccessLevel,
|
||||
getTenantAssistantConfig,
|
||||
isAssistantAccessLevel,
|
||||
type AssistantAccessLevel,
|
||||
type AssistantConfig,
|
||||
} from '@/api/assistant'
|
||||
import { useAuthStore } from './auth'
|
||||
|
||||
/** Pages that tell the assistant where the user is. */
|
||||
export type AssistantPageId =
|
||||
| 'knowledge_base'
|
||||
| 'wiki'
|
||||
| 'agent_editor'
|
||||
| 'settings_models'
|
||||
| 'mcp_services'
|
||||
| 'chat'
|
||||
|
||||
/** What the user has open, as published by the pages that know it. */
|
||||
export interface AssistantPageContext {
|
||||
page?: AssistantPageId
|
||||
/** The part of the page in view, e.g. an editor tab ("tools"). */
|
||||
section?: string
|
||||
agentId?: string
|
||||
agentName?: string
|
||||
knowledgeBaseId?: string
|
||||
knowledgeBaseName?: string
|
||||
/** The knowledge base's chat model, the assistant's default on this page. */
|
||||
chatModelId?: string
|
||||
knowledgeId?: string
|
||||
knowledgeTitle?: string
|
||||
wikiSlug?: string
|
||||
wikiTitle?: string
|
||||
wikiIssueIds?: string[]
|
||||
modelId?: string
|
||||
modelName?: string
|
||||
mcpServiceId?: string
|
||||
mcpServiceName?: string
|
||||
/** A chat message the user asked the assistant about, with its session. */
|
||||
chatSessionId?: string
|
||||
messageId?: string
|
||||
}
|
||||
|
||||
/** A new model's form, filled in by the assistant; never carries credentials. */
|
||||
export interface AssistantModelDraft {
|
||||
type: 'chat' | 'embedding' | 'rerank' | 'vllm' | 'asr'
|
||||
source?: 'remote' | 'local'
|
||||
provider?: string
|
||||
model_name?: string
|
||||
display_name?: string
|
||||
base_url?: string
|
||||
}
|
||||
|
||||
/** A new remote MCP service's form, filled in by the assistant; never carries credentials. */
|
||||
export interface AssistantMcpServiceDraft {
|
||||
name: string
|
||||
usage_instructions?: string
|
||||
transport_type: 'sse' | 'http-streamable'
|
||||
url: string
|
||||
auth_type?: '' | 'api_key' | 'oauth'
|
||||
api_key_header?: string
|
||||
}
|
||||
|
||||
/** Text the user selected on the page beside the assistant. */
|
||||
export interface AssistantPageSelection {
|
||||
text: string
|
||||
/** Set when the text is selected in a field the assistant can write to. */
|
||||
field?: string
|
||||
ref?: string
|
||||
startLine?: number
|
||||
endLine?: number
|
||||
}
|
||||
|
||||
export function toPageSelectionPayload(selection: AssistantPageSelection): PageSelectionPayload {
|
||||
return {
|
||||
text: selection.text,
|
||||
field: selection.field || undefined,
|
||||
ref: selection.ref || undefined,
|
||||
start_line: selection.startLine || undefined,
|
||||
end_line: selection.endLine || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/** A form the user asked the assistant to open, waiting for its page. */
|
||||
export type AssistantPageDraft =
|
||||
| { kind: 'model'; draft: AssistantModelDraft }
|
||||
| { kind: 'mcp_service'; draft: AssistantMcpServiceDraft }
|
||||
|
||||
export interface AssistantOpenRequest {
|
||||
/** Sent as the first message of a new conversation. */
|
||||
query?: string
|
||||
/** Narrows the page context for that first message only. */
|
||||
focus?: Pick<AssistantPageContext, 'wikiIssueIds'>
|
||||
}
|
||||
|
||||
const SESSION_KEY_PREFIX = 'weknora:assistant-session'
|
||||
const VISIBLE_KEY_PREFIX = 'weknora:assistant-visible'
|
||||
const MODEL_KEY_PREFIX = 'weknora:assistant-model'
|
||||
const ACCESS_KEY_PREFIX = 'weknora:assistant-access'
|
||||
const PAGE_ACCESS_KEY_PREFIX = 'weknora:assistant-page-access'
|
||||
const LAYOUT_KEY = 'weknora:assistant-layout'
|
||||
const WIDTH_KEY = 'weknora:assistant-width'
|
||||
const ENTRY_KEY = 'weknora:assistant-entry'
|
||||
|
||||
/** Docked pushes the page aside; floating hovers over it. Neither blocks it. */
|
||||
export type AssistantLayout = 'docked' | 'floating'
|
||||
|
||||
/**
|
||||
* Where the assistant is opened from besides the command palette, which
|
||||
* always offers it: the sidebar button, a floating button at the bottom
|
||||
* right, or nothing else.
|
||||
*/
|
||||
export type AssistantEntry = 'sidebar' | 'launcher' | 'palette'
|
||||
const ASSISTANT_ENTRIES: AssistantEntry[] = ['sidebar', 'launcher', 'palette']
|
||||
|
||||
export const ASSISTANT_PANEL_MIN_WIDTH = 360
|
||||
export const ASSISTANT_PANEL_MAX_WIDTH = 760
|
||||
export const ASSISTANT_PANEL_DEFAULT_WIDTH = 440
|
||||
|
||||
function readLayout(): AssistantLayout {
|
||||
try {
|
||||
return localStorage.getItem(LAYOUT_KEY) === 'floating' ? 'floating' : 'docked'
|
||||
} catch {
|
||||
return 'docked'
|
||||
}
|
||||
}
|
||||
|
||||
function readEntry(): AssistantEntry {
|
||||
try {
|
||||
const raw = localStorage.getItem(ENTRY_KEY) as AssistantEntry | null
|
||||
return raw && ASSISTANT_ENTRIES.includes(raw) ? raw : 'sidebar'
|
||||
} catch {
|
||||
return 'sidebar'
|
||||
}
|
||||
}
|
||||
|
||||
function readWidth(): number {
|
||||
try {
|
||||
const raw = Number(localStorage.getItem(WIDTH_KEY))
|
||||
return Number.isFinite(raw) && raw > 0 ? raw : ASSISTANT_PANEL_DEFAULT_WIDTH
|
||||
} catch {
|
||||
return ASSISTANT_PANEL_DEFAULT_WIDTH
|
||||
}
|
||||
}
|
||||
|
||||
export function toPageContextPayload(context: AssistantPageContext): PageContextPayload {
|
||||
const message = !!context.chatSessionId && !!context.messageId
|
||||
return {
|
||||
page: context.page || undefined,
|
||||
section: (context.page && context.section) || undefined,
|
||||
agent_id: context.agentId || undefined,
|
||||
knowledge_base_id: context.knowledgeBaseId || undefined,
|
||||
knowledge_id: context.knowledgeId || undefined,
|
||||
wiki_slug: context.wikiSlug || undefined,
|
||||
wiki_issue_ids: context.wikiIssueIds?.length ? [...context.wikiIssueIds] : undefined,
|
||||
model_id: context.modelId || undefined,
|
||||
mcp_service_id: context.mcpServiceId || undefined,
|
||||
session_id: message ? context.chatSessionId : undefined,
|
||||
message_id: message ? context.messageId : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
function contextKey(context: AssistantPageContext | null): string {
|
||||
if (!context) return ''
|
||||
return [
|
||||
context.page, context.agentId, context.knowledgeBaseId, context.knowledgeId, context.wikiSlug,
|
||||
context.modelId, context.mcpServiceId, context.messageId,
|
||||
].map(part => part || '').join('|')
|
||||
}
|
||||
|
||||
/** Whether a merged context names anything worth attaching. */
|
||||
function hasPageContext(context: Partial<AssistantPageContext>): boolean {
|
||||
return !!(context.page || context.knowledgeBaseId || context.agentId || context.modelId ||
|
||||
context.mcpServiceId || (context.chatSessionId && context.messageId))
|
||||
}
|
||||
|
||||
/**
|
||||
* Pinia store behind the global WeKnora assistant panel (rendered once in
|
||||
* platform/index.vue). Pages publish what is open through
|
||||
* useAssistantPageContext; anything can open the panel with open().
|
||||
*/
|
||||
export const useAssistantStore = defineStore('assistant', () => {
|
||||
const visible = ref(false)
|
||||
const sessionId = ref('')
|
||||
const pendingRequest = ref<AssistantOpenRequest | null>(null)
|
||||
// Publishers in mount order, so a nested page (Wiki) refines its parent (KB).
|
||||
const layers = shallowReactive(new Map<symbol, Partial<AssistantPageContext>>())
|
||||
const dismissedKey = ref('')
|
||||
|
||||
const pageContext = computed<AssistantPageContext | null>(() => {
|
||||
const merged: Partial<AssistantPageContext> = {}
|
||||
for (const layer of layers.values()) Object.assign(merged, layer)
|
||||
return hasPageContext(merged) ? merged : null
|
||||
})
|
||||
// The page's name from the route, for pages that publish nothing; the
|
||||
// dialog or drawer open over the page; and the text selected on it.
|
||||
const pageTitle = ref('')
|
||||
const pageView = ref('')
|
||||
const pageSelection = shallowRef<AssistantPageSelection | null>(null)
|
||||
// Opening another page or dialog brings a dismissed context back: it is new.
|
||||
const attachKey = computed(() => `${contextKey(pageContext.value)}#${pageTitle.value}#${pageView.value}`)
|
||||
const contextAttached = computed(() =>
|
||||
(!!pageContext.value || !!pageTitle.value || !!pageView.value) && dismissedKey.value !== attachKey.value)
|
||||
|
||||
// '' leaves the choice to the run: the knowledge base's chat model, then
|
||||
// the system default.
|
||||
const modelId = ref('')
|
||||
|
||||
// The conversation and whether the panel is open survive reloads within
|
||||
// the tab and the model choice persists, all scoped like the command palette's history so another user
|
||||
// or workspace never inherits them.
|
||||
const storageKey = (prefix: string): string => {
|
||||
const auth = useAuthStore()
|
||||
return `${prefix}:${auth.user?.id || 'anon'}:${auth.effectiveTenantId ?? 'none'}`
|
||||
}
|
||||
// The user's own level; the workspace ceiling caps what a run gets.
|
||||
const accessLevel = ref<AssistantAccessLevel>(DEFAULT_ASSISTANT_ACCESS_LEVEL)
|
||||
// Workspace name and ceiling. Until it loads the ceiling is the default,
|
||||
// the same one the server applies to a workspace that never set it.
|
||||
const workspaceConfig = ref<AssistantConfig | null>(null)
|
||||
const accessCeiling = computed<AssistantAccessLevel>(() => {
|
||||
const level = workspaceConfig.value?.max_access_level
|
||||
return isAssistantAccessLevel(level) ? level : DEFAULT_ASSISTANT_ACCESS_LEVEL
|
||||
})
|
||||
// Whether the assistant may read and fill the page beside it.
|
||||
const pageAccess = ref(true)
|
||||
const effectiveAccessLevel = computed(() => capAssistantAccessLevel(accessLevel.value, accessCeiling.value))
|
||||
/** The workspace's name for the assistant; empty means the default. */
|
||||
const displayName = computed(() => workspaceConfig.value?.display_name?.trim() || '')
|
||||
|
||||
const restore = () => {
|
||||
try {
|
||||
sessionId.value = sessionStorage.getItem(storageKey(SESSION_KEY_PREFIX)) || ''
|
||||
visible.value = sessionStorage.getItem(storageKey(VISIBLE_KEY_PREFIX)) === '1'
|
||||
modelId.value = localStorage.getItem(storageKey(MODEL_KEY_PREFIX)) || ''
|
||||
const level = localStorage.getItem(storageKey(ACCESS_KEY_PREFIX))
|
||||
accessLevel.value = isAssistantAccessLevel(level) ? level : DEFAULT_ASSISTANT_ACCESS_LEVEL
|
||||
pageAccess.value = localStorage.getItem(storageKey(PAGE_ACCESS_KEY_PREFIX)) !== '0'
|
||||
} catch {
|
||||
sessionId.value = ''
|
||||
visible.value = false
|
||||
modelId.value = ''
|
||||
accessLevel.value = DEFAULT_ASSISTANT_ACCESS_LEVEL
|
||||
pageAccess.value = true
|
||||
}
|
||||
void loadWorkspaceConfig()
|
||||
}
|
||||
const workspaceOwner = () => {
|
||||
const auth = useAuthStore()
|
||||
return auth.user?.id && auth.effectiveTenantId != null ? `${auth.user.id}:${auth.effectiveTenantId}` : ''
|
||||
}
|
||||
const loadWorkspaceConfig = async () => {
|
||||
workspaceConfig.value = null
|
||||
const owner = workspaceOwner()
|
||||
if (!owner) return
|
||||
try {
|
||||
const res = await getTenantAssistantConfig()
|
||||
// A workspace switch can complete while the request is in flight.
|
||||
if (workspaceOwner() === owner) workspaceConfig.value = res?.data || null
|
||||
} catch {
|
||||
// The defaults stand; the server applies the same ones.
|
||||
}
|
||||
}
|
||||
const setWorkspaceConfig = (config: AssistantConfig) => {
|
||||
workspaceConfig.value = { ...config }
|
||||
}
|
||||
const setAccessLevel = (level: AssistantAccessLevel) => {
|
||||
accessLevel.value = level
|
||||
try {
|
||||
localStorage.setItem(storageKey(ACCESS_KEY_PREFIX), level)
|
||||
} catch {
|
||||
// See setSession.
|
||||
}
|
||||
}
|
||||
const setPageAccess = (on: boolean) => {
|
||||
pageAccess.value = on
|
||||
try {
|
||||
if (on) localStorage.removeItem(storageKey(PAGE_ACCESS_KEY_PREFIX))
|
||||
else localStorage.setItem(storageKey(PAGE_ACCESS_KEY_PREFIX), '0')
|
||||
} catch {
|
||||
// See setSession.
|
||||
}
|
||||
}
|
||||
const setSession = (id: string) => {
|
||||
sessionId.value = id
|
||||
try {
|
||||
if (id) sessionStorage.setItem(storageKey(SESSION_KEY_PREFIX), id)
|
||||
else sessionStorage.removeItem(storageKey(SESSION_KEY_PREFIX))
|
||||
} catch {
|
||||
// Storage can throw in private mode; the in-memory value still works.
|
||||
}
|
||||
}
|
||||
const setModel = (id: string) => {
|
||||
modelId.value = id
|
||||
try {
|
||||
if (id) localStorage.setItem(storageKey(MODEL_KEY_PREFIX), id)
|
||||
else localStorage.removeItem(storageKey(MODEL_KEY_PREFIX))
|
||||
} catch {
|
||||
// See setSession.
|
||||
}
|
||||
}
|
||||
// Entry, layout and width are this browser's preference, shared by every
|
||||
// account.
|
||||
const entry = ref<AssistantEntry>(readEntry())
|
||||
const setEntry = (next: AssistantEntry) => {
|
||||
entry.value = next
|
||||
try {
|
||||
localStorage.setItem(ENTRY_KEY, next)
|
||||
} catch {
|
||||
// See setSession.
|
||||
}
|
||||
}
|
||||
const layout = ref<AssistantLayout>(readLayout())
|
||||
const width = ref(readWidth())
|
||||
const setLayout = (next: AssistantLayout) => {
|
||||
layout.value = next
|
||||
try {
|
||||
localStorage.setItem(LAYOUT_KEY, next)
|
||||
} catch {
|
||||
// See setSession.
|
||||
}
|
||||
}
|
||||
const setWidth = (next: number) => {
|
||||
width.value = Math.min(ASSISTANT_PANEL_MAX_WIDTH, Math.max(ASSISTANT_PANEL_MIN_WIDTH, Math.round(next)))
|
||||
try {
|
||||
localStorage.setItem(WIDTH_KEY, String(width.value))
|
||||
} catch {
|
||||
// See setSession.
|
||||
}
|
||||
}
|
||||
|
||||
restore()
|
||||
watch(() => {
|
||||
const auth = useAuthStore()
|
||||
return `${auth.user?.id}:${auth.effectiveTenantId}`
|
||||
}, restore)
|
||||
|
||||
const setVisible = (next: boolean) => {
|
||||
visible.value = next
|
||||
try {
|
||||
if (next) sessionStorage.setItem(storageKey(VISIBLE_KEY_PREFIX), '1')
|
||||
else sessionStorage.removeItem(storageKey(VISIBLE_KEY_PREFIX))
|
||||
} catch {
|
||||
// See setSession.
|
||||
}
|
||||
}
|
||||
const open = (request?: AssistantOpenRequest) => {
|
||||
if (request?.query) {
|
||||
setSession('')
|
||||
pendingRequest.value = request
|
||||
}
|
||||
setVisible(true)
|
||||
}
|
||||
const close = () => {
|
||||
setVisible(false)
|
||||
}
|
||||
const toggle = () => {
|
||||
if (visible.value) close()
|
||||
else open()
|
||||
}
|
||||
const startNewConversation = () => {
|
||||
pendingRequest.value = null
|
||||
setSession('')
|
||||
}
|
||||
const takePendingRequest = (): AssistantOpenRequest | null => {
|
||||
const request = pendingRequest.value
|
||||
pendingRequest.value = null
|
||||
return request
|
||||
}
|
||||
|
||||
const setPageTitle = (title: string) => {
|
||||
pageTitle.value = title
|
||||
}
|
||||
const setPageView = (view: string) => {
|
||||
pageView.value = view
|
||||
}
|
||||
const setPageSelection = (selection: AssistantPageSelection | null) => {
|
||||
pageSelection.value = selection
|
||||
}
|
||||
|
||||
// A message for the open conversation, sent by the conversation itself.
|
||||
const queuedMessage = shallowRef<{ id: number; query: string } | null>(null)
|
||||
let queuedSeq = 0
|
||||
/** Asks in the open conversation, or starts one when there is none. */
|
||||
const ask = (query: string) => {
|
||||
if (!sessionId.value) {
|
||||
open({ query })
|
||||
return
|
||||
}
|
||||
queuedMessage.value = { id: ++queuedSeq, query }
|
||||
setVisible(true)
|
||||
}
|
||||
const takeQueuedMessage = () => {
|
||||
const message = queuedMessage.value
|
||||
queuedMessage.value = null
|
||||
return message
|
||||
}
|
||||
// Bumped to move the cursor into the assistant's input box.
|
||||
const focusRequest = ref(0)
|
||||
const focusComposer = () => {
|
||||
setVisible(true)
|
||||
focusRequest.value++
|
||||
}
|
||||
|
||||
const pageDraft = ref<AssistantPageDraft | null>(null)
|
||||
const setPageDraft = (draft: AssistantPageDraft | null) => {
|
||||
pageDraft.value = draft
|
||||
}
|
||||
/** Hands the waiting form to the page that shows it, once. */
|
||||
function takePageDraft(kind: 'model'): AssistantModelDraft | null
|
||||
function takePageDraft(kind: 'mcp_service'): AssistantMcpServiceDraft | null
|
||||
function takePageDraft(kind: AssistantPageDraft['kind']) {
|
||||
const waiting = pageDraft.value
|
||||
if (!waiting || waiting.kind !== kind) return null
|
||||
pageDraft.value = null
|
||||
return waiting.draft
|
||||
}
|
||||
|
||||
const publishPageContext = (owner: symbol, context: Partial<AssistantPageContext>) => {
|
||||
layers.set(owner, context)
|
||||
}
|
||||
const retractPageContext = (owner: symbol) => {
|
||||
layers.delete(owner)
|
||||
}
|
||||
const dismissPageContext = () => {
|
||||
dismissedKey.value = attachKey.value
|
||||
}
|
||||
const restorePageContext = () => {
|
||||
dismissedKey.value = ''
|
||||
}
|
||||
|
||||
return {
|
||||
visible,
|
||||
sessionId,
|
||||
modelId,
|
||||
accessLevel,
|
||||
accessCeiling,
|
||||
effectiveAccessLevel,
|
||||
pageAccess,
|
||||
displayName,
|
||||
workspaceConfig,
|
||||
entry,
|
||||
layout,
|
||||
width,
|
||||
pendingRequest,
|
||||
pageContext,
|
||||
contextAttached,
|
||||
pageTitle,
|
||||
pageView,
|
||||
pageSelection,
|
||||
setPageTitle,
|
||||
setPageView,
|
||||
setPageSelection,
|
||||
queuedMessage,
|
||||
ask,
|
||||
takeQueuedMessage,
|
||||
focusRequest,
|
||||
focusComposer,
|
||||
open,
|
||||
close,
|
||||
toggle,
|
||||
setSession,
|
||||
setModel,
|
||||
setAccessLevel,
|
||||
setPageAccess,
|
||||
setWorkspaceConfig,
|
||||
loadWorkspaceConfig,
|
||||
setEntry,
|
||||
setLayout,
|
||||
setWidth,
|
||||
startNewConversation,
|
||||
takePendingRequest,
|
||||
pageDraft,
|
||||
setPageDraft,
|
||||
takePageDraft,
|
||||
publishPageContext,
|
||||
retractPageContext,
|
||||
dismissPageContext,
|
||||
restorePageContext,
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,623 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import type { UserInfo, TenantInfo, KnowledgeBaseInfo } from '@/api/auth'
|
||||
import { userInfoFromApi } from '@/api/auth'
|
||||
import type { TenantInfo as TenantInfoFromAPI } from '@/api/tenant'
|
||||
import i18n from '@/i18n'
|
||||
import { reloadFontFromStorage } from '@/composables/useFont'
|
||||
import { reloadThemeFromStorage } from '@/composables/useTheme'
|
||||
import { resetMigrationLatch } from '@/composables/preferenceStorage'
|
||||
import { BUILTIN_QUICK_ANSWER_ID } from '@/api/agent'
|
||||
import { useChatResourcesStore } from '@/stores/chatResources'
|
||||
import { useEditorResourcesStore } from '@/stores/editorResources'
|
||||
import { useOrganizationStore } from '@/stores/organization'
|
||||
import { createSequencedRefresh } from '@/stores/sequencedRefresh'
|
||||
|
||||
/** 登出时丢弃 Pinia 内的空间级资源缓存,避免 SPA 重登复用上一账号数据。 */
|
||||
function clearSessionResourceCaches() {
|
||||
useChatResourcesStore().invalidate()
|
||||
useEditorResourcesStore().invalidate()
|
||||
useOrganizationStore().clearState()
|
||||
}
|
||||
|
||||
// Per-user UI preferences are namespaced by user id in localStorage.
|
||||
// Reload them whenever the active user changes.
|
||||
function reloadUserPreferences() {
|
||||
// Reset the latch so migration runs once for the new active user.
|
||||
resetMigrationLatch()
|
||||
reloadFontFromStorage()
|
||||
reloadThemeFromStorage()
|
||||
}
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
// 状态
|
||||
const user = ref<UserInfo | null>(null)
|
||||
const tenant = ref<TenantInfo | null>(null)
|
||||
const token = ref<string>('')
|
||||
const refreshToken = ref<string>('')
|
||||
const knowledgeBases = ref<KnowledgeBaseInfo[]>([])
|
||||
const currentKnowledgeBase = ref<KnowledgeBaseInfo | null>(null)
|
||||
const selectedTenantId = ref<number | null>(null)
|
||||
const selectedTenantName = ref<string | null>(null)
|
||||
const allTenants = ref<TenantInfoFromAPI[]>([])
|
||||
// memberships lists every tenant the user can authenticate into,
|
||||
// along with their role in each. Populated from /auth/login response.
|
||||
// v1 deployments will typically have length 1; the field is wired now
|
||||
// so PR 3 can render a tenant-switcher UI without a store migration.
|
||||
const memberships = ref<Array<{ tenant_id: number; tenant_name?: string; role: string }>>([])
|
||||
const isLiteMode = ref(false)
|
||||
// pendingInvitationCount is the number of pending tenant invitations
|
||||
// addressed to the current user. Renders as a badge next to the
|
||||
// avatar; updated by fetchPendingInvitationCount, which runs after
|
||||
// login, after tenant switch, and on a polling interval. Polling
|
||||
// (vs SSE) is fine — the count is checked rarely and a 1-2 minute
|
||||
// staleness window is acceptable for an inbox indicator.
|
||||
const pendingInvitationCount = ref<number>(0)
|
||||
// Authoritative deployment capability returned by /auth/me. Defaults to
|
||||
// false (fail-closed): we hide the "create workspace" affordance until
|
||||
// /auth/me confirms the deployment allows it, so an invitation-only
|
||||
// deployment never briefly flashes a create action the backend would
|
||||
// then reject with 403/2005.
|
||||
const canCreateTenant = ref(false)
|
||||
|
||||
const autoAcceptInvitation = ref(false)
|
||||
|
||||
// 计算属性
|
||||
const isLoggedIn = computed(() => {
|
||||
return !!token.value && !!user.value
|
||||
})
|
||||
|
||||
const hasValidTenant = computed(() => {
|
||||
return !!tenant.value && !!tenant.value.id
|
||||
})
|
||||
|
||||
const currentTenantId = computed(() => {
|
||||
return tenant.value?.id || ''
|
||||
})
|
||||
|
||||
// currentTenantName resolves the active tenant's display name across the
|
||||
// app (sidebar, breadcrumbs, headers). It MUST follow the same active-
|
||||
// tenant rule as currentTenantRole / effectiveTenantId: the user's
|
||||
// selected override takes precedence over their home tenant. Reading
|
||||
// tenant.value.name alone would render the home tenant's name even after
|
||||
// the user switched, which is the bug TenantSelector already worked
|
||||
// around inline; this computed centralises that fallback ladder.
|
||||
const currentTenantName = computed(() => {
|
||||
const tid =
|
||||
selectedTenantId.value !== null && selectedTenantId.value !== undefined
|
||||
? String(selectedTenantId.value)
|
||||
: tenant.value?.id
|
||||
? String(tenant.value.id)
|
||||
: ''
|
||||
if (!tid) return ''
|
||||
if (selectedTenantId.value && selectedTenantName.value) {
|
||||
return selectedTenantName.value
|
||||
}
|
||||
const fromMembership = memberships.value.find((m) => String(m.tenant_id) === tid)
|
||||
if (fromMembership?.tenant_name) return fromMembership.tenant_name
|
||||
if (tenant.value && String(tenant.value.id) === tid) return tenant.value.name || ''
|
||||
return ''
|
||||
})
|
||||
|
||||
const currentUserId = computed(() => {
|
||||
return user.value?.id || ''
|
||||
})
|
||||
|
||||
const canAccessAllTenants = computed(() => {
|
||||
return user.value?.can_access_all_tenants || false
|
||||
})
|
||||
|
||||
// isSystemAdmin reflects the platform-wide system-administrator flag
|
||||
// (User.IsSystemAdmin on the server). It is independent of per-tenant
|
||||
// Owner/Admin/Contributor/Viewer roles — a system admin can manage
|
||||
// global settings, built-in models, and other system admins regardless
|
||||
// of which tenant they're currently scoped into.
|
||||
//
|
||||
// SECURITY: same caveat as currentTenantRole — this value is hydrated
|
||||
// from localStorage on reload and is therefore tamper-prone client-side.
|
||||
// Use it ONLY to gate UI visibility (menu entries, route guards). All
|
||||
// real authorisation lives in the server-side RequireSystemAdmin
|
||||
// middleware (see internal/middleware/rbac.go). A user who flips this
|
||||
// bit in DevTools will get a 403 the moment they hit a guarded endpoint.
|
||||
const isSystemAdmin = computed(() => {
|
||||
return user.value?.is_system_admin === true
|
||||
})
|
||||
|
||||
// currentTenantRole returns the user's role in the active tenant
|
||||
// (defaulting to '' when memberships have not been loaded). Used by
|
||||
// role-aware UI gating; PR 2 wires backend enforcement, PR 3 uses
|
||||
// this for menu/button visibility.
|
||||
//
|
||||
// It MUST read effectiveTenantId, not tenant.value.id. tenant.value is
|
||||
// the user's home tenant (set once on login from /auth/me's tenant
|
||||
// field); selectedTenantId is the active override applied by the
|
||||
// tenant switcher. Reading the wrong field used to leak Owner-level
|
||||
// UI to a Viewer who switched into a tenant where they were a Viewer
|
||||
// — every gate above (`hasRole(...)`) returned the home-tenant role.
|
||||
//
|
||||
// SECURITY: This value is read from localStorage (`weknora_memberships`)
|
||||
// and therefore MUST be treated as UI-rendering-only — any user can
|
||||
// tamper with localStorage and grant themselves "owner" here. All real
|
||||
// authorisation decisions live on the server (auth middleware resolves
|
||||
// the role from tenant_members on every request). Never branch
|
||||
// security-sensitive logic on this value alone.
|
||||
const currentTenantRole = computed(() => {
|
||||
const tid =
|
||||
selectedTenantId.value !== null && selectedTenantId.value !== undefined
|
||||
? String(selectedTenantId.value)
|
||||
: tenant.value?.id
|
||||
? String(tenant.value.id)
|
||||
: ''
|
||||
if (!tid) return ''
|
||||
const match = memberships.value.find((m) => String(m.tenant_id) === tid)
|
||||
if (match?.role) return match.role
|
||||
// Cross-tenant superuser visiting a tenant they're not a member of:
|
||||
// backend auth.go resolveTenantRole step2 grants a temporary Admin
|
||||
// role without writing tenant_members. Mirror that here so mutation
|
||||
// UIs aren't hidden in tenants the superuser switched into. Never
|
||||
// surface Owner — the backend caps the temporary grant at Admin too
|
||||
// (Owner-only ops like tenant deletion stay reserved for a real
|
||||
// Owner inside the target tenant).
|
||||
if (canAccessAllTenants.value) return 'admin'
|
||||
return ''
|
||||
})
|
||||
|
||||
// hasRole answers "is the current tenant role at least <min>?", used by
|
||||
// role-aware UI gating across KB / Agent / settings views. The numeric
|
||||
// ordering (viewer < contributor < admin < owner) mirrors the server-side
|
||||
// matrix in middleware/rbac.go so a v-if here lines up with the 403 the
|
||||
// backend would return.
|
||||
//
|
||||
// SECURITY: shares the same caveat as currentTenantRole — derived from
|
||||
// localStorage, MUST be treated as UI-rendering-only. Never rely on
|
||||
// hasRole() for security decisions; the server is the source of truth.
|
||||
const ROLE_LEVEL: Record<string, number> = {
|
||||
viewer: 10,
|
||||
contributor: 20,
|
||||
admin: 30,
|
||||
owner: 40,
|
||||
}
|
||||
const hasRole = (min: 'viewer' | 'contributor' | 'admin' | 'owner'): boolean => {
|
||||
return (ROLE_LEVEL[currentTenantRole.value] ?? 0) >= ROLE_LEVEL[min]
|
||||
}
|
||||
|
||||
const effectiveTenantId = computed(() => {
|
||||
// 如果选择了其他空间,使用选择的空间ID,否则使用用户默认空间ID
|
||||
return selectedTenantId.value || (tenant.value?.id ? Number(tenant.value.id) : null)
|
||||
})
|
||||
|
||||
// 操作方法
|
||||
const setUser = (userData: UserInfo) => {
|
||||
const previousId = user.value?.id
|
||||
user.value = userData
|
||||
// 保存到localStorage
|
||||
localStorage.setItem('weknora_user', JSON.stringify(userData))
|
||||
if (previousId !== userData.id) {
|
||||
reloadUserPreferences()
|
||||
}
|
||||
}
|
||||
|
||||
const setTenant = (tenantData: TenantInfo | null) => {
|
||||
tenant.value = tenantData
|
||||
if (tenantData) {
|
||||
localStorage.setItem('weknora_tenant', JSON.stringify(tenantData))
|
||||
} else {
|
||||
localStorage.removeItem('weknora_tenant')
|
||||
setSelectedTenant(null, null)
|
||||
}
|
||||
}
|
||||
|
||||
const setToken = (tokenValue: string) => {
|
||||
token.value = tokenValue
|
||||
localStorage.setItem('weknora_token', tokenValue)
|
||||
}
|
||||
|
||||
const setRefreshToken = (refreshTokenValue: string) => {
|
||||
refreshToken.value = refreshTokenValue
|
||||
localStorage.setItem('weknora_refresh_token', refreshTokenValue)
|
||||
}
|
||||
|
||||
const setKnowledgeBases = (kbList: KnowledgeBaseInfo[]) => {
|
||||
// 确保输入是数组
|
||||
knowledgeBases.value = Array.isArray(kbList) ? kbList : []
|
||||
localStorage.setItem('weknora_knowledge_bases', JSON.stringify(knowledgeBases.value))
|
||||
}
|
||||
|
||||
const setCurrentKnowledgeBase = (kb: KnowledgeBaseInfo | null) => {
|
||||
currentKnowledgeBase.value = kb
|
||||
if (kb) {
|
||||
localStorage.setItem('weknora_current_kb', JSON.stringify(kb))
|
||||
} else {
|
||||
localStorage.removeItem('weknora_current_kb')
|
||||
}
|
||||
}
|
||||
|
||||
// Wipe chat / KB selections that were saved under the previous tenant.
|
||||
// These keys are NOT tenant-scoped in storage; after a tenant switch they
|
||||
// would otherwise be reloaded verbatim and the chat input would post under
|
||||
// the new tenant with an Agent / model id that only existed in the old
|
||||
// tenant — backend 403s or "model not found". Called from setSelectedTenant
|
||||
// only on an actual tenant change, so logout / init paths are not touched.
|
||||
const clearTenantScopedClientState = () => {
|
||||
try {
|
||||
localStorage.removeItem('weknora_last_chat_model_id')
|
||||
localStorage.removeItem('weknora_current_kb')
|
||||
const raw = localStorage.getItem('WeKnora_settings')
|
||||
if (raw) {
|
||||
const parsed = JSON.parse(raw)
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
parsed.selectedAgentId = BUILTIN_QUICK_ANSWER_ID
|
||||
parsed.selectedAgentSourceTenantId = null
|
||||
parsed.isAgentEnabled = false
|
||||
if (parsed.conversationModels && typeof parsed.conversationModels === 'object') {
|
||||
parsed.conversationModels.summaryModelId = ''
|
||||
parsed.conversationModels.rerankModelId = ''
|
||||
parsed.conversationModels.selectedChatModelId = ''
|
||||
}
|
||||
parsed.selectedKnowledgeBases = []
|
||||
parsed.selectedFiles = []
|
||||
parsed.selectedFileKbMap = {}
|
||||
parsed.knowledgeBaseId = ''
|
||||
localStorage.setItem('WeKnora_settings', JSON.stringify(parsed))
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// localStorage may be disabled or contain malformed JSON — best effort.
|
||||
console.warn('[auth] failed to clear tenant-scoped client state', e)
|
||||
}
|
||||
}
|
||||
|
||||
const setSelectedTenant = (tenantId: number | null, tenantName: string | null = null) => {
|
||||
const previousTenantId = selectedTenantId.value
|
||||
const tenantChanged = previousTenantId !== tenantId
|
||||
selectedTenantId.value = tenantId
|
||||
selectedTenantName.value = tenantName
|
||||
if (tenantId !== null) {
|
||||
localStorage.setItem('weknora_selected_tenant_id', String(tenantId))
|
||||
if (tenantName) {
|
||||
localStorage.setItem('weknora_selected_tenant_name', tenantName)
|
||||
}
|
||||
} else {
|
||||
localStorage.removeItem('weknora_selected_tenant_id')
|
||||
localStorage.removeItem('weknora_selected_tenant_name')
|
||||
}
|
||||
if (tenantChanged) {
|
||||
clearTenantScopedClientState()
|
||||
}
|
||||
}
|
||||
|
||||
const setAllTenants = (tenants: TenantInfoFromAPI[]) => {
|
||||
allTenants.value = tenants
|
||||
}
|
||||
|
||||
const setMemberships = (
|
||||
list: Array<{ tenant_id: number; tenant_name?: string; role: string }>
|
||||
) => {
|
||||
memberships.value = Array.isArray(list) ? list : []
|
||||
localStorage.setItem('weknora_memberships', JSON.stringify(memberships.value))
|
||||
}
|
||||
|
||||
// setPendingInvitationCount is the explicit setter used by the
|
||||
// polling composable below. Keeping the mutation behind a setter
|
||||
// matches the pattern of every other piece of auth state and lets
|
||||
// future devtools / strict-mode checks intercept the write.
|
||||
const setPendingInvitationCount = (n: number) => {
|
||||
pendingInvitationCount.value = Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0
|
||||
}
|
||||
|
||||
const setCanCreateTenant = (allowed: boolean) => {
|
||||
canCreateTenant.value = allowed
|
||||
}
|
||||
|
||||
const setAutoAcceptInvitation = (enabled: boolean) => {
|
||||
autoAcceptInvitation.value = enabled
|
||||
}
|
||||
|
||||
// fetchPendingInvitationCount hits the dedicated /me/invitations/
|
||||
// pending-count endpoint and updates the store. Errors are
|
||||
// swallowed — the badge degrades to its last-known value instead
|
||||
// of nagging the user with a toast. The caller can choose to fire
|
||||
// and forget (login flow) or await (manual refresh button).
|
||||
const fetchPendingInvitationCount = async () => {
|
||||
// Import lazily to avoid circular module ordering between auth
|
||||
// store, axios interceptor, and i18n bootstrapping. The store is
|
||||
// imported by very early modules in main.ts; a top-level api
|
||||
// import would tighten that graph unnecessarily.
|
||||
try {
|
||||
const { getMyPendingInvitationCount } = await import('@/api/tenant/invitations')
|
||||
const resp = await getMyPendingInvitationCount()
|
||||
if (resp.success && resp.data) {
|
||||
setPendingInvitationCount(resp.data.pending_count)
|
||||
}
|
||||
} catch {
|
||||
// best-effort; keep last known value
|
||||
}
|
||||
}
|
||||
|
||||
// Reconcile user / home tenant / memberships with GET /api/v1/auth/me.
|
||||
// Login only populated memberships once; SPA navigations skip
|
||||
// hydrateSessionFromToken when isLoggedIn is already true — so inviting
|
||||
// flows or revokes would leave the sidebar switcher stale until reload.
|
||||
//
|
||||
// 请求排序:refreshFromAuthMe 是「刷新」,结果必须来自本次调用之后发出的请求
|
||||
// (接受邀请 / 建空间 / 改空间信息之后调用,不能吃到侧栏悬停早先发出的那次响应);
|
||||
// ensureAuthMe 是「首屏共用」,有请求在飞行就直接复用。登出会作废飞行中的请求,
|
||||
// 迟到的响应不再把会话写回来。
|
||||
// 本次会话是否已经用 /auth/me 校准过。登录响应 / 自动初始化只写入登录时的快照,
|
||||
// 之后第一次进入平台布局仍需校准一次;此后由写操作显式 refresh。
|
||||
let authMeSynced = false
|
||||
|
||||
const authMeRequest = createSequencedRefresh<boolean>(async (isCurrent) => {
|
||||
try {
|
||||
const { getCurrentUser } = await import('@/api/auth')
|
||||
const response = await getCurrentUser()
|
||||
if (!isCurrent()) return false
|
||||
return applyAuthMeResponse(response)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
|
||||
const refreshFromAuthMe = (): Promise<boolean> => authMeRequest.refresh()
|
||||
|
||||
/** 会话内已校准过就直接返回,否则复用飞行中的 /auth/me,没有就拉一次。 */
|
||||
const ensureAuthMe = (): Promise<boolean> => {
|
||||
if (authMeSynced) return Promise.resolve(true)
|
||||
return authMeRequest.share()
|
||||
}
|
||||
|
||||
type AuthMeResponse = Awaited<ReturnType<typeof import('@/api/auth')['getCurrentUser']>>
|
||||
const applyAuthMeResponse = (response: AuthMeResponse): boolean => {
|
||||
const u = response.data?.user
|
||||
if (!response.success || !u) return false
|
||||
|
||||
setUser(userInfoFromApi(u, response.data?.tenant?.id))
|
||||
|
||||
const tenantSnapshot = response.data?.tenant
|
||||
if (tenantSnapshot) {
|
||||
setTenant({
|
||||
id: String(tenantSnapshot.id) || '',
|
||||
name: tenantSnapshot.name || '',
|
||||
owner_id: tenantSnapshot.owner_id || u.id || '',
|
||||
description: tenantSnapshot.description,
|
||||
status: tenantSnapshot.status,
|
||||
business: tenantSnapshot.business,
|
||||
storage_quota: tenantSnapshot.storage_quota,
|
||||
storage_used: tenantSnapshot.storage_used,
|
||||
created_at: tenantSnapshot.created_at || new Date().toISOString(),
|
||||
updated_at: tenantSnapshot.updated_at || new Date().toISOString(),
|
||||
})
|
||||
} else {
|
||||
setTenant(null)
|
||||
}
|
||||
|
||||
const list = response.data?.memberships
|
||||
if (Array.isArray(list)) {
|
||||
setMemberships(list)
|
||||
}
|
||||
|
||||
const createCapability = response.data?.capabilities?.can_create_tenant
|
||||
if (typeof createCapability === 'boolean') {
|
||||
setCanCreateTenant(createCapability)
|
||||
}
|
||||
|
||||
setAutoAcceptInvitation(response.data?.capabilities?.auto_accept_invitation === true)
|
||||
|
||||
authMeSynced = true
|
||||
return true
|
||||
}
|
||||
|
||||
// 用 token 加入空间并刷新成员关系、切到新空间。token 无效时返回 ok:false(不抛异常),
|
||||
// 提示与跳转交给调用方(store 不碰 router)。
|
||||
const acceptInvitationByTokenAndRefresh = async (
|
||||
token: string,
|
||||
): Promise<{ ok: boolean; tenantId?: number; tenantName?: string }> => {
|
||||
try {
|
||||
const { acceptInvitationByToken } = await import('@/api/tenant/invitations')
|
||||
const resp = await acceptInvitationByToken(token)
|
||||
if (!resp.success || !resp.data?.membership) {
|
||||
return { ok: false }
|
||||
}
|
||||
const tenantId = resp.data.membership.tenant_id
|
||||
const tenantName = resp.data.tenant_name
|
||||
// 刷新成员关系,并切到刚加入的空间。
|
||||
await refreshFromAuthMe()
|
||||
setSelectedTenant(tenantId, tenantName ?? null)
|
||||
return { ok: true, tenantId, tenantName }
|
||||
} catch {
|
||||
return { ok: false }
|
||||
}
|
||||
}
|
||||
|
||||
const getSelectedTenant = () => {
|
||||
return selectedTenantId.value
|
||||
}
|
||||
|
||||
const setLiteMode = (value: boolean) => {
|
||||
isLiteMode.value = value
|
||||
if (value) {
|
||||
localStorage.setItem('weknora_lite_mode', 'true')
|
||||
} else {
|
||||
localStorage.removeItem('weknora_lite_mode')
|
||||
}
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
// 清空状态
|
||||
user.value = null
|
||||
tenant.value = null
|
||||
token.value = ''
|
||||
refreshToken.value = ''
|
||||
knowledgeBases.value = []
|
||||
currentKnowledgeBase.value = null
|
||||
selectedTenantId.value = null
|
||||
selectedTenantName.value = null
|
||||
allTenants.value = []
|
||||
memberships.value = []
|
||||
pendingInvitationCount.value = 0
|
||||
canCreateTenant.value = false
|
||||
autoAcceptInvitation.value = false
|
||||
authMeSynced = false
|
||||
// 飞行中的 /auth/me 作废:登出之后才返回的响应不能再 setUser / setTenant。
|
||||
authMeRequest.invalidate()
|
||||
clearSessionResourceCaches()
|
||||
|
||||
// 清空localStorage
|
||||
localStorage.removeItem('weknora_user')
|
||||
localStorage.removeItem('weknora_tenant')
|
||||
localStorage.removeItem('weknora_token')
|
||||
localStorage.removeItem('weknora_refresh_token')
|
||||
localStorage.removeItem('weknora_knowledge_bases')
|
||||
localStorage.removeItem('weknora_current_kb')
|
||||
localStorage.removeItem('weknora_selected_tenant_id')
|
||||
localStorage.removeItem('weknora_selected_tenant_name')
|
||||
localStorage.removeItem('weknora_memberships')
|
||||
localStorage.removeItem('weknora_lite_mode')
|
||||
isLiteMode.value = false
|
||||
try {
|
||||
sessionStorage.removeItem('weknora_lite_last_path')
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
reloadUserPreferences()
|
||||
}
|
||||
|
||||
const initFromStorage = () => {
|
||||
// 从localStorage恢复状态
|
||||
const storedUser = localStorage.getItem('weknora_user')
|
||||
const storedTenant = localStorage.getItem('weknora_tenant')
|
||||
const storedToken = localStorage.getItem('weknora_token')
|
||||
const storedRefreshToken = localStorage.getItem('weknora_refresh_token')
|
||||
const storedKnowledgeBases = localStorage.getItem('weknora_knowledge_bases')
|
||||
const storedCurrentKb = localStorage.getItem('weknora_current_kb')
|
||||
const storedSelectedTenantId = localStorage.getItem('weknora_selected_tenant_id')
|
||||
const storedSelectedTenantName = localStorage.getItem('weknora_selected_tenant_name')
|
||||
|
||||
if (storedUser) {
|
||||
try {
|
||||
// 走 userInfoFromApi 把老 localStorage(可能缺新字段,如
|
||||
// is_system_admin)规范化一遍,避免「我新加了字段、但老登录态
|
||||
// 没经过登录响应处理过、字段就永远是 undefined」的死角。
|
||||
// 这是「漏拷 4 处」之外的第 5 个隐藏入口,专门给页面刷新走的。
|
||||
user.value = userInfoFromApi(JSON.parse(storedUser))
|
||||
} catch (e) {
|
||||
console.error(i18n.global.t('authStore.errors.parseUserFailed'), e)
|
||||
}
|
||||
}
|
||||
|
||||
if (storedTenant) {
|
||||
try {
|
||||
tenant.value = JSON.parse(storedTenant)
|
||||
} catch (e) {
|
||||
console.error(i18n.global.t('authStore.errors.parseTenantFailed'), e)
|
||||
}
|
||||
}
|
||||
|
||||
if (storedToken) {
|
||||
token.value = storedToken
|
||||
}
|
||||
|
||||
if (storedRefreshToken) {
|
||||
refreshToken.value = storedRefreshToken
|
||||
}
|
||||
|
||||
if (storedKnowledgeBases) {
|
||||
try {
|
||||
const parsed = JSON.parse(storedKnowledgeBases)
|
||||
knowledgeBases.value = Array.isArray(parsed) ? parsed : []
|
||||
} catch (e) {
|
||||
console.error(i18n.global.t('authStore.errors.parseKnowledgeBasesFailed'), e)
|
||||
knowledgeBases.value = []
|
||||
}
|
||||
}
|
||||
|
||||
if (storedCurrentKb) {
|
||||
try {
|
||||
currentKnowledgeBase.value = JSON.parse(storedCurrentKb)
|
||||
} catch (e) {
|
||||
console.error(i18n.global.t('authStore.errors.parseCurrentKnowledgeBaseFailed'), e)
|
||||
}
|
||||
}
|
||||
|
||||
if (storedSelectedTenantId) {
|
||||
try {
|
||||
selectedTenantId.value = Number(storedSelectedTenantId)
|
||||
if (storedSelectedTenantName) {
|
||||
selectedTenantName.value = storedSelectedTenantName
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to parse selected tenant ID', e)
|
||||
selectedTenantId.value = null
|
||||
selectedTenantName.value = null
|
||||
}
|
||||
}
|
||||
|
||||
const storedMemberships = localStorage.getItem('weknora_memberships')
|
||||
if (storedMemberships) {
|
||||
try {
|
||||
const parsed = JSON.parse(storedMemberships)
|
||||
memberships.value = Array.isArray(parsed) ? parsed : []
|
||||
} catch (e) {
|
||||
console.error('Failed to parse memberships', e)
|
||||
memberships.value = []
|
||||
}
|
||||
}
|
||||
|
||||
isLiteMode.value = localStorage.getItem('weknora_lite_mode') === 'true'
|
||||
}
|
||||
|
||||
// 初始化时从localStorage恢复状态
|
||||
initFromStorage()
|
||||
|
||||
return {
|
||||
// 状态
|
||||
user,
|
||||
tenant,
|
||||
token,
|
||||
refreshToken,
|
||||
knowledgeBases,
|
||||
currentKnowledgeBase,
|
||||
selectedTenantId,
|
||||
selectedTenantName,
|
||||
allTenants,
|
||||
memberships,
|
||||
pendingInvitationCount,
|
||||
canCreateTenant,
|
||||
autoAcceptInvitation,
|
||||
|
||||
// 计算属性
|
||||
isLoggedIn,
|
||||
hasValidTenant,
|
||||
currentTenantId,
|
||||
currentTenantName,
|
||||
currentUserId,
|
||||
canAccessAllTenants,
|
||||
isSystemAdmin,
|
||||
currentTenantRole,
|
||||
hasRole,
|
||||
effectiveTenantId,
|
||||
isLiteMode,
|
||||
|
||||
// 方法
|
||||
setUser,
|
||||
setTenant,
|
||||
setToken,
|
||||
setRefreshToken,
|
||||
setKnowledgeBases,
|
||||
setCurrentKnowledgeBase,
|
||||
setSelectedTenant,
|
||||
setAllTenants,
|
||||
setMemberships,
|
||||
setPendingInvitationCount,
|
||||
setCanCreateTenant,
|
||||
setAutoAcceptInvitation,
|
||||
fetchPendingInvitationCount,
|
||||
refreshFromAuthMe,
|
||||
ensureAuthMe,
|
||||
acceptInvitationByTokenAndRefresh,
|
||||
getSelectedTenant,
|
||||
setLiteMode,
|
||||
logout,
|
||||
initFromStorage
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { after, before, test } from 'node:test'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { createServer, type ViteDevServer } from 'vite'
|
||||
import { createPinia } from 'pinia'
|
||||
|
||||
let server: ViteDevServer
|
||||
let useBrowserConnectionStore: typeof import('./browserConnection').useBrowserConnectionStore
|
||||
|
||||
before(async () => {
|
||||
server = await createServer({
|
||||
configFile: false,
|
||||
plugins: [{
|
||||
name: 'browser-connection-store-test',
|
||||
enforce: 'pre',
|
||||
resolveId(id) { if (id.endsWith('/utils/request')) return '\0offline-request' },
|
||||
load(id) {
|
||||
if (id === '\0offline-request') {
|
||||
return 'const request = () => { throw new Error("Unexpected network request") }; export { request as get, request as post, request as put, request as del };'
|
||||
}
|
||||
},
|
||||
}],
|
||||
optimizeDeps: { noDiscovery: true, entries: [] },
|
||||
resolve: { alias: { '@': fileURLToPath(new URL('../', import.meta.url)) } },
|
||||
server: { middlewareMode: true, hmr: false },
|
||||
appType: 'custom',
|
||||
})
|
||||
;({ useBrowserConnectionStore } = await server.ssrLoadModule('/src/stores/browserConnection.ts'))
|
||||
})
|
||||
after(async () => { await server?.close() })
|
||||
|
||||
test('composer keeps the browser source available until account status loads', () => {
|
||||
const store = useBrowserConnectionStore(createPinia())
|
||||
assert.equal(store.loaded, false)
|
||||
assert.equal(store.online, false)
|
||||
assert.equal(store.knownOffline, false)
|
||||
})
|
||||
|
||||
test('an offline or unpaired extension cannot stay selected as a live source', () => {
|
||||
const store = useBrowserConnectionStore(createPinia())
|
||||
store.apply({
|
||||
enabled: true,
|
||||
connected: false,
|
||||
extension_available: true,
|
||||
device: { id: 'chrome', label: 'Chrome', last_seen_at: '' },
|
||||
})
|
||||
assert.equal(store.loaded, true)
|
||||
assert.equal(store.online, false)
|
||||
assert.equal(store.knownOffline, true)
|
||||
|
||||
store.apply({ enabled: true, connected: false, extension_available: true })
|
||||
assert.equal(store.knownOffline, true)
|
||||
|
||||
store.apply({ enabled: false, connected: false, extension_available: false })
|
||||
assert.equal(store.knownOffline, true)
|
||||
|
||||
store.apply({
|
||||
enabled: true,
|
||||
connected: true,
|
||||
extension_available: true,
|
||||
device: { id: 'chrome', label: 'Chrome', last_seen_at: '' },
|
||||
})
|
||||
assert.equal(store.online, true)
|
||||
assert.equal(store.knownOffline, false)
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { get } from '@/utils/request'
|
||||
|
||||
export type BrowserAccountStatus = {
|
||||
enabled: boolean
|
||||
connected: boolean
|
||||
device?: { id: string; label: string; last_seen_at: string }
|
||||
extension_available: boolean
|
||||
}
|
||||
|
||||
type BrowserConnectionState = BrowserAccountStatus & {
|
||||
loaded: boolean
|
||||
subscribers: number
|
||||
}
|
||||
|
||||
let pollTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let pollController: AbortController | undefined
|
||||
let visibilityHandler: (() => void) | undefined
|
||||
|
||||
export const useBrowserConnectionStore = defineStore('browserConnection', {
|
||||
state: (): BrowserConnectionState => ({
|
||||
enabled: false,
|
||||
connected: false,
|
||||
extension_available: false,
|
||||
loaded: false,
|
||||
subscribers: 0,
|
||||
}),
|
||||
getters: {
|
||||
online: (state) => state.enabled && state.connected,
|
||||
knownOffline: (state) => state.loaded && !(state.enabled && state.connected),
|
||||
},
|
||||
actions: {
|
||||
apply(data: BrowserAccountStatus) {
|
||||
this.enabled = data.enabled === true
|
||||
this.connected = data.connected === true
|
||||
this.device = data.device
|
||||
this.extension_available = data.extension_available === true
|
||||
this.loaded = true
|
||||
},
|
||||
async refresh() {
|
||||
const result = await get<{ data: BrowserAccountStatus }>('/api/v1/me/browser', {
|
||||
signal: pollController?.signal,
|
||||
})
|
||||
this.apply(result.data)
|
||||
},
|
||||
watchStatus() {
|
||||
this.subscribers += 1
|
||||
if (this.subscribers !== 1) return
|
||||
pollController = new AbortController()
|
||||
visibilityHandler = () => {
|
||||
if (!document.hidden) void this.poll()
|
||||
}
|
||||
document.addEventListener('visibilitychange', visibilityHandler)
|
||||
void this.poll()
|
||||
},
|
||||
unwatchStatus() {
|
||||
this.subscribers = Math.max(0, this.subscribers - 1)
|
||||
if (this.subscribers !== 0) return
|
||||
if (visibilityHandler) {
|
||||
document.removeEventListener('visibilitychange', visibilityHandler)
|
||||
visibilityHandler = undefined
|
||||
}
|
||||
pollController?.abort()
|
||||
pollController = undefined
|
||||
clearTimeout(pollTimer)
|
||||
pollTimer = undefined
|
||||
},
|
||||
async poll() {
|
||||
try {
|
||||
if (!document.hidden) await this.refresh()
|
||||
} catch {
|
||||
// Keep the last known status; the composer stays conservative once loaded.
|
||||
}
|
||||
if (this.subscribers > 0) {
|
||||
pollTimer = setTimeout(() => { void this.poll() }, this.online ? 5000 : 3000)
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,129 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { after, before, test } from 'node:test'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { createServer, type ViteDevServer } from 'vite'
|
||||
import { createPinia } from 'pinia'
|
||||
|
||||
let server: ViteDevServer
|
||||
let useSettingsStore: typeof import('./settings').useSettingsStore
|
||||
const savedStorage = Object.getOwnPropertyDescriptor(globalThis, 'localStorage')
|
||||
const items = new Map<string, string>()
|
||||
before(async () => {
|
||||
Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: {
|
||||
getItem: (key: string) => items.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => items.set(key, value),
|
||||
removeItem: (key: string) => items.delete(key),
|
||||
} })
|
||||
server = await createServer({
|
||||
configFile: false,
|
||||
plugins: [{ name: 'offline-store-test', enforce: 'pre',
|
||||
resolveId(id) { if (id.endsWith('/utils/request')) return '\0offline-request' },
|
||||
load(id) { if (id === '\0offline-request') return 'const request = () => { throw new Error("Unexpected network request") }; export { request as get, request as post, request as put, request as del };' },
|
||||
}],
|
||||
optimizeDeps: { noDiscovery: true, entries: [] },
|
||||
resolve: { alias: { '@': fileURLToPath(new URL('../', import.meta.url)) } },
|
||||
server: { middlewareMode: true, hmr: false }, appType: 'custom',
|
||||
})
|
||||
;({ useSettingsStore } = await server.ssrLoadModule('/src/stores/settings.ts'))
|
||||
})
|
||||
after(async () => {
|
||||
await server?.close()
|
||||
if (savedStorage) Object.defineProperty(globalThis, 'localStorage', savedStorage)
|
||||
else Reflect.deleteProperty(globalThis, 'localStorage')
|
||||
})
|
||||
test('browser and web search selections are independent and persisted', () => {
|
||||
const store = useSettingsStore(createPinia())
|
||||
store.toggleWebSearch(true)
|
||||
store.toggleLocalBrowser(true)
|
||||
assert.equal(store.isLocalBrowserEnabled, true)
|
||||
assert.equal(store.settings.webSearchEnabled, true)
|
||||
assert.equal(JSON.parse(items.get('WeKnora_settings')!).localBrowserEnabled, true)
|
||||
store.toggleWebSearch(false)
|
||||
assert.equal(store.isLocalBrowserEnabled, true)
|
||||
store.toggleWebSearch(true)
|
||||
store.toggleLocalBrowser(true)
|
||||
store.toggleLocalBrowser(false)
|
||||
assert.equal(store.isLocalBrowserEnabled, false)
|
||||
assert.equal(store.settings.webSearchEnabled, true)
|
||||
})
|
||||
|
||||
test('reasoning overrides belong to the session, restore on reload and never become global defaults', () => {
|
||||
items.clear()
|
||||
const store = useSettingsStore(createPinia())
|
||||
assert.equal(store.reasoningEffortOverride, '')
|
||||
store.reasoningEffortOverride = 'high'
|
||||
store.toggleWebSearch(true)
|
||||
assert.equal(JSON.stringify(JSON.parse(items.get('WeKnora_settings')!)).includes('high'), false)
|
||||
store.hydrateSessionInputState({}, true)
|
||||
assert.equal(store.reasoningEffortOverride, 'high', 'first send keeps the createChat choice')
|
||||
store.restoreDefaultsIfSnapshotted()
|
||||
assert.equal(store.reasoningEffortOverride, '', 'leaving even a new session clears the choice')
|
||||
store.hydrateSessionInputState({ reasoning_effort: 'off' })
|
||||
assert.equal(store.reasoningEffortOverride, 'off')
|
||||
store.restoreDefaultsIfSnapshotted()
|
||||
assert.equal(store.reasoningEffortOverride, '')
|
||||
store.applyLastRequestState({ reasoning_effort: 'max' })
|
||||
assert.equal(store.reasoningEffortOverride, 'max')
|
||||
store.applyLastRequestState({})
|
||||
assert.equal(store.reasoningEffortOverride, '', 'old sessions inherit')
|
||||
store.applyLastRequestState({ reasoning_effort: 'unsupported' })
|
||||
assert.equal(store.reasoningEffortOverride, '')
|
||||
store.reasoningEffortOverride = 'high'
|
||||
store.selectAgent('another-agent')
|
||||
assert.equal(store.reasoningEffortOverride, '')
|
||||
})
|
||||
test('session restore follows saved browser choice and clears it for older sessions', () => {
|
||||
const store = useSettingsStore(createPinia())
|
||||
store.applyLastRequestState({ local_browser_enabled: true, web_search_enabled: true })
|
||||
assert.equal(store.isLocalBrowserEnabled, true)
|
||||
assert.equal(store.settings.webSearchEnabled, true)
|
||||
store.applyLastRequestState({ web_search_enabled: true })
|
||||
assert.equal(store.isLocalBrowserEnabled, false)
|
||||
assert.equal(store.settings.webSearchEnabled, true)
|
||||
})
|
||||
|
||||
test('session restore clears a stale knowledge base when the saved scope is absent', () => {
|
||||
items.clear()
|
||||
const store = useSettingsStore(createPinia())
|
||||
store.selectKnowledgeBases(['kb-default'])
|
||||
|
||||
store.hydrateSessionInputState({ knowledge_base_ids: ['kb-session-a'] })
|
||||
assert.deepEqual(store.settings.selectedKnowledgeBases, ['kb-session-a'])
|
||||
|
||||
// Switching sessions first restores the browser defaults, which may still
|
||||
// contain a KB. A last-request state with no KB field must clear that value:
|
||||
// the backend omits empty slices when it persists a request with no scope.
|
||||
store.restoreDefaultsIfSnapshotted()
|
||||
assert.deepEqual(store.settings.selectedKnowledgeBases, ['kb-default'])
|
||||
store.hydrateSessionInputState({ agent_enabled: true })
|
||||
assert.deepEqual(store.settings.selectedKnowledgeBases, [])
|
||||
|
||||
// Leaving the session still restores the user's browser-level default.
|
||||
store.restoreDefaultsIfSnapshotted()
|
||||
assert.deepEqual(store.settings.selectedKnowledgeBases, ['kb-default'])
|
||||
})
|
||||
|
||||
test('new-session hydration preserves the createChat draft after the first query is consumed', async () => {
|
||||
items.clear()
|
||||
const store = useSettingsStore(createPinia())
|
||||
store.toggleLocalBrowser(true)
|
||||
store.toggleWebSearch(true)
|
||||
let firstQuery = '用浏览器查一下'
|
||||
const preserveDraft = Boolean(firstQuery)
|
||||
let finishLoad!: (state: Record<string, boolean>) => void
|
||||
const pendingSession = new Promise<Record<string, boolean>>(resolve => { finishLoad = resolve })
|
||||
const hydration = pendingSession.then(state => store.hydrateSessionInputState(state, preserveDraft))
|
||||
firstQuery = '' // The first send consumes the pending message before GET returns.
|
||||
finishLoad({ local_browser_enabled: false, web_search_enabled: false })
|
||||
await hydration
|
||||
assert.equal(store.isLocalBrowserEnabled, true)
|
||||
assert.equal(store.settings.webSearchEnabled, true)
|
||||
assert.equal(store._defaultsSnapshot, null)
|
||||
// Returning to an existing session still restores its saved choices.
|
||||
store.hydrateSessionInputState({ local_browser_enabled: false, web_search_enabled: false })
|
||||
assert.equal(store.isLocalBrowserEnabled, false)
|
||||
assert.equal(store.settings.webSearchEnabled, false)
|
||||
store.restoreDefaultsIfSnapshotted()
|
||||
assert.equal(store.isLocalBrowserEnabled, true)
|
||||
assert.equal(store.settings.webSearchEnabled, true)
|
||||
})
|
||||
@@ -0,0 +1,86 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test, { type TestContext } from 'node:test'
|
||||
import * as vue from 'vue'
|
||||
import * as pinia from 'pinia'
|
||||
import * as resources from './resourceCache.ts'
|
||||
import * as localized from './localizedResourceCache.ts'
|
||||
import { change, fixture, flush } from '../test-utils/vueFixture.ts'
|
||||
|
||||
function setup(t: TestContext) {
|
||||
const f = fixture(t)
|
||||
const api = {
|
||||
listKnowledgeBases: t.mock.fn(async () => ({ data: [{ id: 'kb' }] })),
|
||||
getKnowledgeBaseById: t.mock.fn(async () => ({ data: { id: 'kb' } })),
|
||||
listAgents: t.mock.fn(async () => ({ data: [{ id: 'agent' }] })),
|
||||
listModels: t.mock.fn(async () => [{ id: 'model' }]),
|
||||
}
|
||||
const { useChatResourcesStore } = f.evaluate(readFileSync(new URL('./chatResources.ts', import.meta.url), 'utf8'), {
|
||||
vue, pinia, '@/utils/assistantDataChange': f.dataChange,
|
||||
'@/api/knowledge-base': api, '@/api/agent': api,
|
||||
'@/api/model': api, '@/api/web-search-provider': {}, '@/api/system': {},
|
||||
'@/utils/request': { getCurrentLanguage: () => 'en-US' },
|
||||
'@/stores/organization': { useOrganizationStore: () => ({
|
||||
async fetchSharedKnowledgeBases() {}, async fetchSharedAgents() {},
|
||||
}) },
|
||||
'./resourceCache': resources, './localizedResourceCache': localized,
|
||||
})
|
||||
const root = pinia.createPinia()
|
||||
pinia.setActivePinia(root)
|
||||
t.after(() => pinia.disposePinia(root))
|
||||
return { ...f, api, store: useChatResourcesStore() }
|
||||
}
|
||||
|
||||
test('refreshes agent selectors and invalidates per-agent KB access snapshots', async t => {
|
||||
const { store, api, emit } = setup(t)
|
||||
await store.ensureAgentKnowledgeBases('agent')
|
||||
await store.ensureAgentKnowledgeBases('agent')
|
||||
assert.equal(api.listKnowledgeBases.mock.callCount(), 1)
|
||||
emit(change('agent.update', { agent_id: ['agent'] }))
|
||||
t.mock.timers.tick(300)
|
||||
await flush()
|
||||
assert.equal(api.listAgents.mock.callCount(), 1)
|
||||
assert.equal(store.agents[0].id, 'agent')
|
||||
await store.ensureAgentKnowledgeBases('agent')
|
||||
assert.equal(api.listKnowledgeBases.mock.callCount(), 2)
|
||||
store.$dispose()
|
||||
emit(change('agent.delete'))
|
||||
t.mock.timers.tick(300)
|
||||
await flush()
|
||||
assert.equal(api.listAgents.mock.callCount(), 1)
|
||||
})
|
||||
|
||||
for (const operation of ['knowledge_base.generate_profile', 'knowledge.delete', 'faq.update_entry', 'wiki.revert']) {
|
||||
test(`refreshes KB selectors and invalidates details on ${operation}`, async t => {
|
||||
const { store, api, emit } = setup(t)
|
||||
await store.fetchKnowledgeBaseById('kb')
|
||||
await store.fetchKnowledgeBaseById('kb')
|
||||
assert.equal(api.getKnowledgeBaseById.mock.callCount(), 1)
|
||||
emit(change(operation, { knowledge_base_id: ['kb'] }))
|
||||
t.mock.timers.tick(300)
|
||||
await flush()
|
||||
assert.equal(api.listKnowledgeBases.mock.callCount(), 1)
|
||||
await store.fetchKnowledgeBaseById('kb')
|
||||
assert.equal(api.getKnowledgeBaseById.mock.callCount(), 2)
|
||||
})
|
||||
}
|
||||
|
||||
test('refreshes the model selectors on a model change', async t => {
|
||||
const { store, api, emit } = setup(t)
|
||||
emit(change('model.update'))
|
||||
t.mock.timers.tick(300)
|
||||
await flush()
|
||||
assert.equal(api.listModels.mock.callCount(), 1)
|
||||
assert.equal(store.allModels[0].id, 'model')
|
||||
assert.equal(api.listAgents.mock.callCount(), 0)
|
||||
})
|
||||
|
||||
test('ignores unknown areas', async t => {
|
||||
const { api, emit } = setup(t)
|
||||
emit(change('unknown.update'))
|
||||
t.mock.timers.tick(300)
|
||||
await flush()
|
||||
assert.equal(api.listAgents.mock.callCount(), 0)
|
||||
assert.equal(api.listKnowledgeBases.mock.callCount(), 0)
|
||||
assert.equal(api.listModels.mock.callCount(), 0)
|
||||
})
|
||||
@@ -0,0 +1,345 @@
|
||||
import { subscribeAssistantDataChange } from '@/utils/assistantDataChange'
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed, watch, onScopeDispose } from 'vue'
|
||||
import { listKnowledgeBases, getKnowledgeBaseById } from '@/api/knowledge-base'
|
||||
import { listAgents, type CustomAgent } from '@/api/agent'
|
||||
import { listModels, type ModelConfig } from '@/api/model'
|
||||
import { listWebSearchProviders, type WebSearchProviderEntity } from '@/api/web-search-provider'
|
||||
import { isNamedSandboxBackend, listSandboxConfigs, type SandboxConfigRecord } from '@/api/system'
|
||||
import { useOrganizationStore } from '@/stores/organization'
|
||||
import { getCurrentLanguage } from '@/utils/request'
|
||||
import { isLocalizedSnapshotUsable, shouldForceLocalizedRefetch } from './localizedResourceCache'
|
||||
import { createCachedResource, createKeyedSnapshotCache } from './resourceCache'
|
||||
|
||||
type ResourceKey = 'knowledgeBases' | 'agents' | 'models' | 'webSearchProviders' | 'sandboxConfigs'
|
||||
|
||||
export type ListCreatorFilter = 'all' | 'mine' | 'others'
|
||||
|
||||
function isKbModelReady(kb: any): boolean {
|
||||
if (!kb.summary_model_id || kb.summary_model_id === '') return false
|
||||
const strategy = kb.indexing_strategy
|
||||
const needsEmbedding = !strategy || strategy.vector_enabled || strategy.keyword_enabled
|
||||
if (needsEmbedding && (!kb.embedding_model_id || kb.embedding_model_id === '')) return false
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* 空间级资源(知识库 / 智能体 / 模型 / 联网搜索 / 沙箱后端)的共享快照。
|
||||
*
|
||||
* 没有 TTL:每次 `ensureX()` 都会发请求(同一时刻只有一个在飞行,挂载突发共用它),
|
||||
* 写操作之后由调用方 `ensureX(true)`、`replaceModels()` 或 `invalidate()` 显式刷新。
|
||||
* 页面直接读这里的 ref 渲染,旧快照在新数据到达前先撑着。
|
||||
*/
|
||||
export const useChatResourcesStore = defineStore('chatResources', () => {
|
||||
const rawKnowledgeBases = ref<any[]>([])
|
||||
const agents = ref<CustomAgent[]>([])
|
||||
const disabledOwnAgentIds = ref<string[]>([])
|
||||
const allModels = ref<ModelConfig[]>([])
|
||||
const webSearchProviders = ref<WebSearchProviderEntity[]>([])
|
||||
const sandboxConfigs = ref<SandboxConfigRecord[]>([])
|
||||
|
||||
const validKnowledgeBases = computed(() => rawKnowledgeBases.value.filter(isKbModelReady))
|
||||
const chatModels = computed(() => allModels.value.filter((m) => m.type === 'KnowledgeQA'))
|
||||
|
||||
const knowledgeBasesResource = createCachedResource(
|
||||
async () => {
|
||||
const res: any = await listKnowledgeBases()
|
||||
return res?.data && Array.isArray(res.data) ? (res.data as any[]) : []
|
||||
},
|
||||
(data) => {
|
||||
rawKnowledgeBases.value = data
|
||||
},
|
||||
)
|
||||
|
||||
// 内置智能体名称/描述由后端按 Accept-Language 本地化返回;快照只对拉取时的
|
||||
// UI 语言有效。agentsLoadedLocale 必须是「请求发起时」的语言,不能在 await 之后再读。
|
||||
let agentsLoadedLocale = ''
|
||||
let agentsInflightLocale = ''
|
||||
const agentsResource = createCachedResource(
|
||||
async () => {
|
||||
const locale = getCurrentLanguage()
|
||||
agentsInflightLocale = locale
|
||||
const res = (await listAgents()) as { data?: CustomAgent[]; disabled_own_agent_ids?: string[] }
|
||||
return { data: res.data || [], disabled: res.disabled_own_agent_ids || [], locale }
|
||||
},
|
||||
({ data, disabled, locale }) => {
|
||||
agents.value = data
|
||||
disabledOwnAgentIds.value = disabled
|
||||
agentsLoadedLocale = locale
|
||||
},
|
||||
)
|
||||
|
||||
watch(
|
||||
() => getCurrentLanguage(),
|
||||
(locale) => {
|
||||
if (agentsLoadedLocale && agentsLoadedLocale !== locale) {
|
||||
agentsResource.invalidate()
|
||||
agentsLoadedLocale = ''
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
const modelsResource = createCachedResource(
|
||||
async () => {
|
||||
const models = await listModels()
|
||||
return Array.isArray(models) ? models : []
|
||||
},
|
||||
(models) => {
|
||||
allModels.value = models
|
||||
},
|
||||
)
|
||||
|
||||
const webSearchProvidersResource = createCachedResource(
|
||||
async () => {
|
||||
const response = await listWebSearchProviders()
|
||||
const providers = (response as any)?.data
|
||||
return Array.isArray(providers) ? (providers as WebSearchProviderEntity[]) : []
|
||||
},
|
||||
(providers) => {
|
||||
webSearchProviders.value = providers
|
||||
},
|
||||
)
|
||||
|
||||
// 失败只吞掉不抛:这是可选资源——拿不到就只剩「不启用沙箱」一项,
|
||||
// 智能体照样能编辑保存。调用方通常把它和一堆必需资源放在同一个
|
||||
// Promise.all 里,若在这里抛出,整个编辑器的依赖加载都会连坐
|
||||
// (技能可用性拿不到 ⇒ 技能配置分组直接消失)。
|
||||
const sandboxConfigsResource = createCachedResource(
|
||||
async () => {
|
||||
try {
|
||||
const res = await listSandboxConfigs()
|
||||
const rows = Array.isArray(res?.data) ? res.data : []
|
||||
return rows.filter((cfg) => isNamedSandboxBackend(cfg.sandbox_type))
|
||||
} catch {
|
||||
return [] as SandboxConfigRecord[]
|
||||
}
|
||||
},
|
||||
(rows) => {
|
||||
sandboxConfigs.value = rows
|
||||
},
|
||||
)
|
||||
|
||||
const resources: Record<ResourceKey, ReturnType<typeof createCachedResource>> = {
|
||||
knowledgeBases: knowledgeBasesResource,
|
||||
agents: agentsResource,
|
||||
models: modelsResource,
|
||||
webSearchProviders: webSearchProvidersResource,
|
||||
sandboxConfigs: sandboxConfigsResource,
|
||||
}
|
||||
|
||||
// 智能体可见知识库、单个知识库详情:拿到过就一直用,直到显式失效。
|
||||
// @ 提及列表会逐条补 count,这类按 key 的读取不能每次都打接口。
|
||||
const agentKbCache = createKeyedSnapshotCache(async (cacheKey: string) => {
|
||||
const [agentId, sourceTenantId] = cacheKey.split(':')
|
||||
const res: any = await listKnowledgeBases({
|
||||
agent_id: agentId,
|
||||
agent_source_tenant_id: sourceTenantId === 'current' ? undefined : sourceTenantId,
|
||||
})
|
||||
return res?.data && Array.isArray(res.data) ? (res.data as any[]) : []
|
||||
})
|
||||
const kbDetailCache = createKeyedSnapshotCache(async (kbId: string) => {
|
||||
try {
|
||||
const res: any = await getKnowledgeBaseById(kbId)
|
||||
return res?.data ?? null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
})
|
||||
|
||||
/** 是否已有快照(区别于「是否新鲜」:本 store 不再有新鲜度窗口)。 */
|
||||
function isLoaded(key: ResourceKey): boolean {
|
||||
if (key === 'agents') {
|
||||
return isLocalizedSnapshotUsable(agentsResource.isLoaded(), agentsLoadedLocale, getCurrentLanguage())
|
||||
}
|
||||
return resources[key].isLoaded()
|
||||
}
|
||||
|
||||
/**
|
||||
* 知识库列表(支持 creator 筛选)。creator=all 走共享快照供对话页复用。
|
||||
*/
|
||||
async function fetchKnowledgeBasesForList(
|
||||
params?: { creator?: ListCreatorFilter },
|
||||
force = false,
|
||||
): Promise<any[]> {
|
||||
const creator = params?.creator ?? 'all'
|
||||
// 带 creator 过滤的列表是列表页专用、不进快照,直接透传请求。
|
||||
// 写操作后的强刷同时把全量快照刷一遍,否则对话输入栏会看到已删除的知识库。
|
||||
if (creator !== 'all') {
|
||||
if (force) void ensureKnowledgeBases(true).catch(() => {})
|
||||
const res: any = await listKnowledgeBases({ creator })
|
||||
return res?.data && Array.isArray(res.data) ? res.data : []
|
||||
}
|
||||
await ensureKnowledgeBases(force)
|
||||
return rawKnowledgeBases.value
|
||||
}
|
||||
|
||||
// 共享资源是附带刷新:它的接口挂了不能连坐自己的列表,否则调用方的 catch
|
||||
// 会把已经拿到的自己的知识库 / 智能体一起清掉(手动文档编辑器、API 集成页)。
|
||||
// 共享列表失败时保留上一次快照,由页面自己决定要不要单独强刷。
|
||||
const swallow = (p: Promise<unknown>) => p.catch(() => undefined)
|
||||
|
||||
async function ensureKnowledgeBases(force = false): Promise<void> {
|
||||
const orgStore = useOrganizationStore()
|
||||
await Promise.all([
|
||||
knowledgeBasesResource.ensure(force),
|
||||
swallow(orgStore.fetchSharedKnowledgeBases({ force })),
|
||||
])
|
||||
}
|
||||
|
||||
/**
|
||||
* 智能体列表(支持 creator 筛选)。creator=all 走共享快照。
|
||||
*/
|
||||
async function fetchAgentsForList(
|
||||
params?: { creator?: ListCreatorFilter },
|
||||
force = false,
|
||||
): Promise<{ data: CustomAgent[]; disabled_own_agent_ids: string[] }> {
|
||||
const creator = params?.creator ?? 'all'
|
||||
const orgStore = useOrganizationStore()
|
||||
|
||||
// 带 creator 过滤的列表不进快照,但仍需刷新共享智能体(与全量路径保持一致)。
|
||||
if (creator !== 'all') {
|
||||
if (force) void ensureAgents(true).catch(() => {})
|
||||
const [agentsRes] = await Promise.all([
|
||||
listAgents({ creator }),
|
||||
orgStore.fetchSharedAgents({ force }),
|
||||
])
|
||||
const res = agentsRes as { data?: CustomAgent[]; disabled_own_agent_ids?: string[] }
|
||||
return { data: res.data || [], disabled_own_agent_ids: res.disabled_own_agent_ids || [] }
|
||||
}
|
||||
|
||||
await ensureAgents(force)
|
||||
return { data: agents.value, disabled_own_agent_ids: disabledOwnAgentIds.value }
|
||||
}
|
||||
|
||||
async function ensureAgents(force = false): Promise<void> {
|
||||
const orgStore = useOrganizationStore()
|
||||
const locale = getCurrentLanguage()
|
||||
// 飞行中的请求是用另一种语言发起的:不能复用它,排在它后面再发一次。
|
||||
const mustForce =
|
||||
force ||
|
||||
shouldForceLocalizedRefetch(agentsResource.hasInFlightRequest(), agentsInflightLocale, locale)
|
||||
await Promise.all([
|
||||
agentsResource.ensure(mustForce),
|
||||
swallow(orgStore.fetchSharedAgents({ force })),
|
||||
])
|
||||
}
|
||||
|
||||
async function ensureModels(force = false): Promise<void> {
|
||||
return modelsResource.ensure(force)
|
||||
}
|
||||
|
||||
/** 用刚拉到的列表覆盖快照(设置页增删改模型之后调用),并作废飞行中的旧请求。 */
|
||||
function replaceModels(models: ModelConfig[]) {
|
||||
allModels.value = Array.isArray(models) ? models : []
|
||||
modelsResource.markLoaded()
|
||||
}
|
||||
|
||||
/** @deprecated 使用 ensureModels;保留别名供对话输入栏调用 */
|
||||
async function ensureChatModels(force = false): Promise<void> {
|
||||
return ensureModels(force)
|
||||
}
|
||||
|
||||
async function ensureWebSearchProviders(force = false): Promise<void> {
|
||||
return webSearchProvidersResource.ensure(force)
|
||||
}
|
||||
|
||||
/**
|
||||
* 沙箱后端配置,供智能体编辑器的后端选择器使用。
|
||||
* 不进 prefetchChatInput:只有编辑智能体时才需要,对话输入栏用不到。
|
||||
*/
|
||||
async function ensureSandboxConfigs(force = false): Promise<void> {
|
||||
return sandboxConfigsResource.ensure(force)
|
||||
}
|
||||
|
||||
/** 并行预取对话输入栏及列表页常用的空间级资源 */
|
||||
async function prefetchChatInput(force = false): Promise<void> {
|
||||
const orgStore = useOrganizationStore()
|
||||
await Promise.all([
|
||||
ensureKnowledgeBases(force),
|
||||
ensureAgents(force),
|
||||
ensureModels(force),
|
||||
ensureWebSearchProviders(force),
|
||||
orgStore.fetchOrganizations({ force }),
|
||||
])
|
||||
}
|
||||
|
||||
async function ensureAgentKnowledgeBases(agentId: string, sourceTenantId?: string, force = false): Promise<any[]> {
|
||||
return agentKbCache.ensure(`${agentId}:${sourceTenantId || 'current'}`, force)
|
||||
}
|
||||
|
||||
/** 单个知识库详情(侧栏 + 详情页共用,去重并发请求) */
|
||||
async function fetchKnowledgeBaseById(kbId: string, force = false): Promise<any | null> {
|
||||
if (!kbId) return null
|
||||
return kbDetailCache.ensure(kbId, force)
|
||||
}
|
||||
|
||||
function invalidateKnowledgeBaseDetail(kbId?: string) {
|
||||
kbDetailCache.invalidate(kbId)
|
||||
}
|
||||
|
||||
function invalidate(...keys: ResourceKey[]) {
|
||||
if (keys.length === 0) {
|
||||
;(Object.keys(resources) as ResourceKey[]).forEach((k) => resources[k].invalidate())
|
||||
rawKnowledgeBases.value = []
|
||||
agents.value = []
|
||||
disabledOwnAgentIds.value = []
|
||||
allModels.value = []
|
||||
webSearchProviders.value = []
|
||||
sandboxConfigs.value = []
|
||||
agentsLoadedLocale = ''
|
||||
agentsInflightLocale = ''
|
||||
agentKbCache.invalidate()
|
||||
invalidateKnowledgeBaseDetail()
|
||||
return
|
||||
}
|
||||
keys.forEach((k) => resources[k].invalidate())
|
||||
if (keys.includes('knowledgeBases')) {
|
||||
agentKbCache.invalidate()
|
||||
invalidateKnowledgeBaseDetail()
|
||||
}
|
||||
if (keys.includes('agents')) {
|
||||
agentsLoadedLocale = ''
|
||||
}
|
||||
}
|
||||
|
||||
onScopeDispose(subscribeAssistantDataChange((changes) => {
|
||||
if (changes.some(change => change.area === 'agent')) {
|
||||
agentKbCache.invalidate()
|
||||
void ensureAgents(true).catch(() => {})
|
||||
}
|
||||
if (changes.some(change => ['knowledge_base', 'knowledge', 'faq', 'wiki'].includes(change.area))) {
|
||||
invalidate('knowledgeBases')
|
||||
void ensureKnowledgeBases(true).catch(() => {})
|
||||
}
|
||||
if (changes.some(change => change.area === 'model')) {
|
||||
invalidate('models')
|
||||
void ensureModels(true).catch(() => {})
|
||||
}
|
||||
}, { areas: ['agent', 'knowledge_base', 'knowledge', 'faq', 'wiki', 'model'] }))
|
||||
|
||||
return {
|
||||
rawKnowledgeBases,
|
||||
validKnowledgeBases,
|
||||
agents,
|
||||
disabledOwnAgentIds,
|
||||
allModels,
|
||||
chatModels,
|
||||
webSearchProviders,
|
||||
sandboxConfigs,
|
||||
isLoaded,
|
||||
fetchKnowledgeBasesForList,
|
||||
fetchAgentsForList,
|
||||
ensureKnowledgeBases,
|
||||
ensureAgents,
|
||||
ensureModels,
|
||||
replaceModels,
|
||||
ensureChatModels,
|
||||
ensureWebSearchProviders,
|
||||
ensureSandboxConfigs,
|
||||
ensureAgentKnowledgeBases,
|
||||
prefetchChatInput,
|
||||
fetchKnowledgeBaseById,
|
||||
invalidateKnowledgeBaseDetail,
|
||||
invalidate,
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,100 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, watch } from 'vue'
|
||||
import { useAuthStore } from './auth'
|
||||
|
||||
const RECENT_KEY_PREFIX = 'weknora_cmdk_recent'
|
||||
const RECENT_LIMIT = 4
|
||||
|
||||
// recentKey scopes "recent searches" to the active (user, tenant) pair.
|
||||
// The previous global key leaked queries between users sharing a browser
|
||||
// and across tenant switches inside the same account. Falling back to
|
||||
// "anon" keeps the palette functional before login finishes hydrating.
|
||||
function recentKey(userId: string | null | undefined, tenantId: number | string | null | undefined): string {
|
||||
const u = userId ? String(userId) : 'anon'
|
||||
const t = tenantId !== null && tenantId !== undefined && tenantId !== '' ? String(tenantId) : 'none'
|
||||
return `${RECENT_KEY_PREFIX}:${u}:${t}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Pinia store for the global command palette (⌘K / Ctrl+K).
|
||||
* The palette itself is rendered once in platform/index.vue.
|
||||
* Any code (router redirect, deep link, programmatic trigger) can open it
|
||||
* by calling openPalette(q).
|
||||
*/
|
||||
export const useCommandPaletteStore = defineStore('commandPalette', () => {
|
||||
const open = ref(false)
|
||||
const initialQuery = ref('')
|
||||
const recentQueries = ref<string[]>([])
|
||||
|
||||
// Lazily resolve the auth store inside actions / watchers — at store
|
||||
// setup time pinia may not have finished registering peer stores yet.
|
||||
const currentRecentKey = (): string => {
|
||||
const auth = useAuthStore()
|
||||
return recentKey(auth.user?.id, auth.effectiveTenantId)
|
||||
}
|
||||
|
||||
const loadRecent = () => {
|
||||
try {
|
||||
const raw = localStorage.getItem(currentRecentKey())
|
||||
recentQueries.value = raw ? JSON.parse(raw) : []
|
||||
} catch {
|
||||
recentQueries.value = []
|
||||
}
|
||||
}
|
||||
|
||||
const openPalette = (query = '') => {
|
||||
initialQuery.value = query
|
||||
open.value = true
|
||||
}
|
||||
|
||||
const closePalette = () => {
|
||||
open.value = false
|
||||
initialQuery.value = ''
|
||||
}
|
||||
|
||||
const pushRecent = (q: string) => {
|
||||
const trimmed = q.trim()
|
||||
if (!trimmed) return
|
||||
recentQueries.value = [
|
||||
trimmed,
|
||||
...recentQueries.value.filter(x => x !== trimmed),
|
||||
].slice(0, RECENT_LIMIT)
|
||||
try {
|
||||
localStorage.setItem(currentRecentKey(), JSON.stringify(recentQueries.value))
|
||||
} catch {
|
||||
/* ignore quota errors */
|
||||
}
|
||||
}
|
||||
|
||||
const clearRecent = () => {
|
||||
recentQueries.value = []
|
||||
try {
|
||||
localStorage.removeItem(currentRecentKey())
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
// Reload recent queries whenever the active user or tenant changes
|
||||
// (login, logout, tenant switch). Each (user, tenant) pair has its own
|
||||
// localStorage namespace so queries don't bleed across identities.
|
||||
watch(
|
||||
() => {
|
||||
const auth = useAuthStore()
|
||||
return [auth.user?.id, auth.effectiveTenantId] as const
|
||||
},
|
||||
() => loadRecent(),
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
return {
|
||||
open,
|
||||
initialQuery,
|
||||
recentQueries,
|
||||
openPalette,
|
||||
closePalette,
|
||||
pushRecent,
|
||||
clearRecent,
|
||||
loadRecent,
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
import { ref } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import { getDeploymentCapabilities } from '@/api/system'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import {
|
||||
isDeploymentCapabilitySupported,
|
||||
type DeploymentCapabilityKey,
|
||||
type DeploymentCapabilityMap,
|
||||
} from '@/config/deploymentCapabilities'
|
||||
|
||||
export const useDeploymentCapabilitiesStore = defineStore('deploymentCapabilities', () => {
|
||||
const edition = ref('')
|
||||
const capabilities = ref<DeploymentCapabilityMap>({})
|
||||
const loaded = ref(false)
|
||||
const loadError = ref('')
|
||||
let loadingPromise: Promise<void> | null = null
|
||||
|
||||
const ensureLoaded = async (force = false): Promise<void> => {
|
||||
if (loaded.value && !force) return
|
||||
if (loadingPromise) return loadingPromise
|
||||
|
||||
loadingPromise = (async () => {
|
||||
try {
|
||||
const response = await getDeploymentCapabilities()
|
||||
edition.value = response.data?.edition || ''
|
||||
capabilities.value = response.data?.capabilities || {}
|
||||
loadError.value = ''
|
||||
} catch (error) {
|
||||
// 能力探测失败时保持 fail-open;权限仍由后端路由最终校验。
|
||||
capabilities.value = {}
|
||||
loadError.value = error instanceof Error ? error.message : String(error)
|
||||
} finally {
|
||||
loaded.value = true
|
||||
loadingPromise = null
|
||||
}
|
||||
})()
|
||||
|
||||
return loadingPromise
|
||||
}
|
||||
|
||||
const isSupported = (key?: DeploymentCapabilityKey) => {
|
||||
const authStore = useAuthStore()
|
||||
return isDeploymentCapabilitySupported(capabilities.value, key, {
|
||||
liteMode: authStore.isLiteMode,
|
||||
edition: edition.value,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
edition,
|
||||
capabilities,
|
||||
loaded,
|
||||
loadError,
|
||||
ensureLoaded,
|
||||
isSupported,
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,393 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import {
|
||||
getStorageEngineConfig,
|
||||
getStorageEngineStatus,
|
||||
getPromptTemplates,
|
||||
getParserEngines,
|
||||
getSystemInfo,
|
||||
type PromptTemplatesConfig,
|
||||
type StorageEngineStatusItem,
|
||||
type ParserEngineInfo,
|
||||
type SystemInfo,
|
||||
} from '@/api/system'
|
||||
import { listMCPServices, type MCPService } from '@/api/mcp-service'
|
||||
import {
|
||||
listSkillCatalog,
|
||||
listSkills,
|
||||
type AgentScope,
|
||||
type SkillCatalogItem,
|
||||
type SkillInfo,
|
||||
} from '@/api/skill'
|
||||
import { getAgentTools, getAgentTypePresets, getPlaceholders, type AgentToolCatalog, type AgentTypePreset, type PlaceholdersResponse } from '@/api/agent'
|
||||
import { getTenantRetrievalConfig } from '@/api/retrieval'
|
||||
import { isStorageConfigDenied } from './storageEngineAccess'
|
||||
import { createCachedResource } from './resourceCache'
|
||||
|
||||
export function pickUsableStorageProvider(
|
||||
candidate: string | undefined,
|
||||
engines: StorageEngineStatusItem[],
|
||||
allowedProviders: string[],
|
||||
): string {
|
||||
const provider = candidate?.trim() || ''
|
||||
const isUsable = (name: string) => {
|
||||
if (!name) return false
|
||||
const status = engines.find((item) => item.name === name)
|
||||
if (status) return status.allowed !== false && status.available !== false
|
||||
if (engines.length > 0) return false
|
||||
if (allowedProviders.length > 0) return allowedProviders.includes(name)
|
||||
return false
|
||||
}
|
||||
|
||||
if (isUsable(provider)) return provider
|
||||
const fallback = engines.find((item) => item.allowed !== false && item.available !== false)?.name
|
||||
if (fallback) return fallback
|
||||
return allowedProviders[0] || provider || 'local'
|
||||
}
|
||||
|
||||
type EditorResourceKey =
|
||||
| 'storageEngine'
|
||||
| 'mcpServices'
|
||||
| 'skills'
|
||||
| 'skillCatalog'
|
||||
| 'agentTypePresets'
|
||||
| 'agentTools'
|
||||
| 'promptTemplates'
|
||||
| 'placeholders'
|
||||
| 'tenantRetrievalConfig'
|
||||
| 'parserEngines'
|
||||
| 'systemInfo'
|
||||
|
||||
/**
|
||||
* 智能体编辑器 / 知识库页面共用的配置类资源快照。
|
||||
* 与 chatResources 同一套约定:无 TTL,每次 ensure 发一次请求(并发共用),
|
||||
* 写操作后显式 `ensureX(true)` 或 `invalidate()`。
|
||||
*/
|
||||
export const useEditorResourcesStore = defineStore('editorResources', () => {
|
||||
const storageConfig = ref<Awaited<ReturnType<typeof getStorageEngineConfig>>['data'] | null>(null)
|
||||
const storageStatus = ref<StorageEngineStatusItem[]>([])
|
||||
const storageAllowedProviders = ref<string[]>([])
|
||||
const mcpServices = ref<MCPService[]>([])
|
||||
const mcpServicesScope = ref('')
|
||||
const skills = ref<SkillInfo[]>([])
|
||||
const skillsAvailable = ref(false)
|
||||
const skillsConfigId = ref('')
|
||||
const skillCatalog = ref<SkillCatalogItem[]>([])
|
||||
const agentTypePresets = ref<AgentTypePreset[]>([])
|
||||
const agentTools = ref<AgentToolCatalog | null>(null)
|
||||
const promptTemplates = ref<PromptTemplatesConfig | null>(null)
|
||||
const placeholders = ref<PlaceholdersResponse | null>(null)
|
||||
const tenantRetrievalConfig = ref<Record<string, unknown> | null>(null)
|
||||
const parserEngines = ref<ParserEngineInfo[]>([])
|
||||
const systemInfo = ref<SystemInfo | null>(null)
|
||||
|
||||
const storageEngineResource = createCachedResource(
|
||||
async () => {
|
||||
const [configRes, statusRes] = await Promise.all([
|
||||
// The config endpoint is admin-only (it carries integration secrets),
|
||||
// while every creator — Contributors included — needs the status list
|
||||
// to pick a usable provider. A permission rejection on the config
|
||||
// call must therefore degrade to "no admin config", not break the
|
||||
// whole editor dependency chain (#2991).
|
||||
getStorageEngineConfig().catch((error: unknown) => {
|
||||
if (isStorageConfigDenied(error)) return null
|
||||
throw error
|
||||
}),
|
||||
getStorageEngineStatus(),
|
||||
])
|
||||
return { configRes, statusRes }
|
||||
},
|
||||
({ configRes, statusRes }) => {
|
||||
storageConfig.value = configRes?.data ?? null
|
||||
storageStatus.value = statusRes?.data?.engines ?? []
|
||||
storageAllowedProviders.value = statusRes?.data?.allowed_providers ?? []
|
||||
},
|
||||
)
|
||||
|
||||
// A shared agent's skills and MCP services live in its owner's workspace and
|
||||
// are an entirely different set from this workspace's. The cache key has to
|
||||
// carry the agent, or switching agents would leave another workspace's
|
||||
// entries in the @ picker.
|
||||
function scopeKey(configId: string, agent?: AgentScope): string {
|
||||
if (!agent?.agentId || !agent?.sourceTenantId) return configId
|
||||
return `${configId}@${agent.sourceTenantId}:${agent.agentId}`
|
||||
}
|
||||
|
||||
let mcpServicesRequestScope: { key: string; agent?: AgentScope } = { key: '' }
|
||||
const mcpServicesResource = createCachedResource(
|
||||
async () => {
|
||||
const scope = mcpServicesRequestScope
|
||||
const list = await listMCPServices(scope.agent)
|
||||
return { key: scope.key, list: Array.isArray(list) ? list : [] }
|
||||
},
|
||||
({ key, list }) => {
|
||||
mcpServicesScope.value = key
|
||||
mcpServices.value = list
|
||||
},
|
||||
)
|
||||
|
||||
let skillsRequestScope: { key: string; configId: string; agent?: AgentScope } = { key: '', configId: '' }
|
||||
const skillsResource = createCachedResource(
|
||||
async () => {
|
||||
const scope = skillsRequestScope
|
||||
// No sandbox config means no skills, for a shared agent too: its config
|
||||
// id is part of the agent config this caller already holds. The backend
|
||||
// re-reads it from the agent, so what is sent here only has to be
|
||||
// non-empty when the agent actually has one.
|
||||
if (!scope.configId) {
|
||||
return { key: scope.key, available: false, list: [] as SkillInfo[] }
|
||||
}
|
||||
try {
|
||||
const skillsRes = await listSkills(scope.configId, scope.agent)
|
||||
return {
|
||||
key: scope.key,
|
||||
available: skillsRes.skills_available !== false,
|
||||
list: skillsRes.data && skillsRes.data.length > 0 ? skillsRes.data : [],
|
||||
}
|
||||
} catch {
|
||||
return { key: scope.key, available: false, list: [] as SkillInfo[] }
|
||||
}
|
||||
},
|
||||
({ key, available, list }) => {
|
||||
skillsConfigId.value = key
|
||||
skillsAvailable.value = available
|
||||
skills.value = list
|
||||
},
|
||||
)
|
||||
|
||||
const skillCatalogResource = createCachedResource(
|
||||
async () => {
|
||||
const res = await listSkillCatalog()
|
||||
return Array.isArray(res?.data) ? res.data : []
|
||||
},
|
||||
(rows) => {
|
||||
skillCatalog.value = rows
|
||||
},
|
||||
)
|
||||
|
||||
const agentTypePresetsResource = createCachedResource(
|
||||
async () => {
|
||||
const presetsRes: any = await getAgentTypePresets()
|
||||
return presetsRes?.data && Array.isArray(presetsRes.data) ? (presetsRes.data as AgentTypePreset[]) : []
|
||||
},
|
||||
(rows) => {
|
||||
agentTypePresets.value = rows
|
||||
},
|
||||
)
|
||||
|
||||
const agentToolsResource = createCachedResource(
|
||||
async () => {
|
||||
const res: any = await getAgentTools()
|
||||
return res?.data && Array.isArray(res.data.tools) ? (res.data as AgentToolCatalog) : null
|
||||
},
|
||||
(catalog) => {
|
||||
agentTools.value = catalog
|
||||
},
|
||||
)
|
||||
|
||||
const promptTemplatesResource = createCachedResource(
|
||||
async () => {
|
||||
const tmplRes = await getPromptTemplates()
|
||||
return tmplRes?.data ?? null
|
||||
},
|
||||
(config) => {
|
||||
promptTemplates.value = config
|
||||
},
|
||||
)
|
||||
|
||||
const placeholdersResource = createCachedResource(
|
||||
async () => {
|
||||
const placeholdersRes = await getPlaceholders()
|
||||
return placeholdersRes?.data ?? null
|
||||
},
|
||||
(data) => {
|
||||
placeholders.value = data
|
||||
},
|
||||
)
|
||||
|
||||
const tenantRetrievalConfigResource = createCachedResource(
|
||||
async () => {
|
||||
const retrievalRes: any = await getTenantRetrievalConfig()
|
||||
return (retrievalRes?.data ?? null) as Record<string, unknown> | null
|
||||
},
|
||||
(config) => {
|
||||
tenantRetrievalConfig.value = config
|
||||
},
|
||||
)
|
||||
|
||||
const parserEnginesResource = createCachedResource(
|
||||
async () => {
|
||||
const resp = await getParserEngines()
|
||||
return resp?.data && Array.isArray(resp.data) ? resp.data : []
|
||||
},
|
||||
(rows) => {
|
||||
parserEngines.value = rows
|
||||
},
|
||||
)
|
||||
|
||||
const systemInfoResource = createCachedResource(
|
||||
async () => {
|
||||
const response = await getSystemInfo()
|
||||
return response?.data ?? null
|
||||
},
|
||||
(info) => {
|
||||
systemInfo.value = info
|
||||
},
|
||||
)
|
||||
|
||||
const resources: Record<EditorResourceKey, ReturnType<typeof createCachedResource>> = {
|
||||
storageEngine: storageEngineResource,
|
||||
mcpServices: mcpServicesResource,
|
||||
skills: skillsResource,
|
||||
skillCatalog: skillCatalogResource,
|
||||
agentTypePresets: agentTypePresetsResource,
|
||||
agentTools: agentToolsResource,
|
||||
promptTemplates: promptTemplatesResource,
|
||||
placeholders: placeholdersResource,
|
||||
tenantRetrievalConfig: tenantRetrievalConfigResource,
|
||||
parserEngines: parserEnginesResource,
|
||||
systemInfo: systemInfoResource,
|
||||
}
|
||||
|
||||
async function ensureStorageEngine(force = false): Promise<void> {
|
||||
return storageEngineResource.ensure(force)
|
||||
}
|
||||
|
||||
function resolveUsableStorageProvider(candidate?: string): string {
|
||||
return pickUsableStorageProvider(
|
||||
candidate,
|
||||
storageStatus.value || [],
|
||||
storageAllowedProviders.value || [],
|
||||
)
|
||||
}
|
||||
|
||||
async function ensureMcpServices(agent?: AgentScope, force = false): Promise<void> {
|
||||
const key = scopeKey('', agent)
|
||||
// 换了作用域:作废飞行中的旧请求,且必须排在它后面重新发。
|
||||
if (key !== mcpServicesRequestScope.key) {
|
||||
mcpServicesResource.invalidate()
|
||||
force = true
|
||||
}
|
||||
mcpServicesRequestScope = { key, agent }
|
||||
return mcpServicesResource.ensure(force)
|
||||
}
|
||||
|
||||
async function ensureSkills(
|
||||
sandboxConfigId?: string,
|
||||
agent?: AgentScope,
|
||||
force = false,
|
||||
): Promise<void> {
|
||||
const configId = sandboxConfigId?.trim() || ''
|
||||
const key = scopeKey(configId, agent)
|
||||
if (key !== skillsRequestScope.key) {
|
||||
skillsResource.invalidate()
|
||||
force = true
|
||||
}
|
||||
skillsRequestScope = { key, configId, agent }
|
||||
return skillsResource.ensure(force)
|
||||
}
|
||||
|
||||
async function ensureSkillCatalog(force = false): Promise<void> {
|
||||
return skillCatalogResource.ensure(force)
|
||||
}
|
||||
|
||||
async function ensureAgentTypePresets(force = false): Promise<void> {
|
||||
return agentTypePresetsResource.ensure(force)
|
||||
}
|
||||
|
||||
async function ensureAgentTools(force = false): Promise<void> {
|
||||
return agentToolsResource.ensure(force)
|
||||
}
|
||||
|
||||
async function ensurePromptTemplates(force = false): Promise<void> {
|
||||
return promptTemplatesResource.ensure(force)
|
||||
}
|
||||
|
||||
async function ensurePlaceholders(force = false): Promise<void> {
|
||||
return placeholdersResource.ensure(force)
|
||||
}
|
||||
|
||||
async function ensureTenantRetrievalConfig(force = false): Promise<void> {
|
||||
return tenantRetrievalConfigResource.ensure(force)
|
||||
}
|
||||
|
||||
async function ensureParserEngines(force = false): Promise<void> {
|
||||
return parserEnginesResource.ensure(force)
|
||||
}
|
||||
|
||||
async function ensureSystemInfo(force = false): Promise<void> {
|
||||
return systemInfoResource.ensure(force)
|
||||
}
|
||||
|
||||
/** 智能体编辑器打开时预取的依赖(不含 IM channels / 单 KB shares) */
|
||||
async function prefetchAgentEditorDeps(force = false): Promise<void> {
|
||||
await Promise.all([
|
||||
// The editor only edits this workspace's agents, so its MCP services
|
||||
// are this workspace's too.
|
||||
ensureMcpServices(undefined, force),
|
||||
ensureAgentTypePresets(force),
|
||||
ensureAgentTools(force),
|
||||
ensurePromptTemplates(force),
|
||||
ensureStorageEngine(force),
|
||||
ensurePlaceholders(force),
|
||||
ensureTenantRetrievalConfig(force),
|
||||
])
|
||||
}
|
||||
|
||||
function invalidate(...keys: EditorResourceKey[]) {
|
||||
if (keys.length === 0) {
|
||||
;(Object.keys(resources) as EditorResourceKey[]).forEach((k) => resources[k].invalidate())
|
||||
storageConfig.value = null
|
||||
storageStatus.value = []
|
||||
storageAllowedProviders.value = []
|
||||
mcpServices.value = []
|
||||
mcpServicesScope.value = ''
|
||||
mcpServicesRequestScope = { key: '' }
|
||||
skills.value = []
|
||||
skillsAvailable.value = false
|
||||
skillsConfigId.value = ''
|
||||
skillsRequestScope = { key: '', configId: '' }
|
||||
skillCatalog.value = []
|
||||
agentTypePresets.value = []
|
||||
agentTools.value = null
|
||||
promptTemplates.value = null
|
||||
placeholders.value = null
|
||||
tenantRetrievalConfig.value = null
|
||||
parserEngines.value = []
|
||||
systemInfo.value = null
|
||||
return
|
||||
}
|
||||
keys.forEach((k) => resources[k].invalidate())
|
||||
}
|
||||
|
||||
return {
|
||||
storageConfig,
|
||||
storageStatus,
|
||||
storageAllowedProviders,
|
||||
mcpServices,
|
||||
skills,
|
||||
skillsAvailable,
|
||||
skillCatalog,
|
||||
agentTypePresets,
|
||||
agentTools,
|
||||
promptTemplates,
|
||||
placeholders,
|
||||
tenantRetrievalConfig,
|
||||
parserEngines,
|
||||
systemInfo,
|
||||
ensureStorageEngine,
|
||||
resolveUsableStorageProvider,
|
||||
ensureMcpServices,
|
||||
ensureSkills,
|
||||
ensureSkillCatalog,
|
||||
ensureAgentTypePresets,
|
||||
ensureAgentTools,
|
||||
ensurePromptTemplates,
|
||||
ensurePlaceholders,
|
||||
ensureTenantRetrievalConfig,
|
||||
ensureParserEngines,
|
||||
ensureSystemInfo,
|
||||
prefetchAgentEditorDeps,
|
||||
invalidate,
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,11 @@
|
||||
import { ref, computed, reactive } from "vue";
|
||||
|
||||
import { defineStore } from "pinia";
|
||||
|
||||
export const knowledgeStore = defineStore("knowledge", {
|
||||
state: () => ({
|
||||
cardList: ref<any[]>([]),
|
||||
total: ref<number>(0),
|
||||
}),
|
||||
actions: {},
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
isLocalizedSnapshotUsable,
|
||||
shouldForceLocalizedRefetch,
|
||||
shouldReuseLocalizedInflight,
|
||||
} from './localizedResourceCache.ts'
|
||||
|
||||
test('localized snapshot is usable only for the locale it was fetched in', () => {
|
||||
assert.equal(isLocalizedSnapshotUsable(true, 'zh-CN', 'zh-CN'), true)
|
||||
assert.equal(isLocalizedSnapshotUsable(true, 'zh-CN', 'en-US'), false)
|
||||
assert.equal(isLocalizedSnapshotUsable(false, 'zh-CN', 'zh-CN'), false)
|
||||
assert.equal(isLocalizedSnapshotUsable(true, '', 'zh-CN'), false)
|
||||
})
|
||||
|
||||
test('landing prefetch must not be reused after the UI language changes', () => {
|
||||
// Request started as zh-CN; user switched to en-US before it settled.
|
||||
assert.equal(shouldReuseLocalizedInflight(true, 'zh-CN', 'en-US'), false)
|
||||
assert.equal(shouldForceLocalizedRefetch(true, 'zh-CN', 'en-US'), true)
|
||||
|
||||
assert.equal(shouldReuseLocalizedInflight(true, 'en-US', 'en-US'), true)
|
||||
assert.equal(shouldForceLocalizedRefetch(true, 'en-US', 'en-US'), false)
|
||||
assert.equal(shouldReuseLocalizedInflight(false, 'zh-CN', 'zh-CN'), false)
|
||||
assert.equal(shouldReuseLocalizedInflight(true, '', 'en-US'), false)
|
||||
})
|
||||
|
||||
test('stamping the request locale keeps a late zh-CN payload from looking usable for en-US', () => {
|
||||
const requestLocale = 'zh-CN'
|
||||
// Wrong (old bug): stamp getCurrentLanguage() after await → 'en-US'.
|
||||
assert.equal(isLocalizedSnapshotUsable(true, 'en-US', 'en-US'), true)
|
||||
// Correct: stamp the locale the HTTP call was started with.
|
||||
assert.equal(isLocalizedSnapshotUsable(true, requestLocale, 'en-US'), false)
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Helpers for cached API payloads that vary by Accept-Language
|
||||
* (built-in agent names/descriptions, shared-agent lists, …).
|
||||
*
|
||||
* The request must stamp the locale it was *started* with. Stamping
|
||||
* getCurrentLanguage() after await lets a zh-CN response be marked as the
|
||||
* en-US snapshot when the user switches language while the call is in flight.
|
||||
*/
|
||||
|
||||
/** A localized snapshot is only usable for the UI language it was fetched in. */
|
||||
export function isLocalizedSnapshotUsable(
|
||||
loaded: boolean,
|
||||
loadedLocale: string,
|
||||
currentLocale: string,
|
||||
): boolean {
|
||||
return loaded && loadedLocale !== '' && loadedLocale === currentLocale
|
||||
}
|
||||
|
||||
/** Reuse an in-flight list request only when it was started for this UI language. */
|
||||
export function shouldReuseLocalizedInflight(
|
||||
hasInflight: boolean,
|
||||
inflightLocale: string,
|
||||
currentLocale: string,
|
||||
): boolean {
|
||||
return hasInflight && inflightLocale !== '' && inflightLocale === currentLocale
|
||||
}
|
||||
|
||||
/**
|
||||
* Force a follow-up fetch when the in-flight request was started for a
|
||||
* different UI language. versionedRequestCoordinator reuses in-flight on
|
||||
* non-force fetch, so locale mismatch must opt into force.
|
||||
*/
|
||||
export function shouldForceLocalizedRefetch(
|
||||
hasInflight: boolean,
|
||||
inflightLocale: string,
|
||||
currentLocale: string,
|
||||
): boolean {
|
||||
return hasInflight && inflightLocale !== '' && inflightLocale !== currentLocale
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { reactive, ref, computed, watch } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import i18n from '@/i18n'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities'
|
||||
import type { DeploymentCapabilityKey } from '@/config/deploymentCapabilities'
|
||||
import type { QuestionOrigin } from '@/utils/questionOrigin'
|
||||
|
||||
type MenuChild = Record<string, any>
|
||||
|
||||
interface MenuItem {
|
||||
title: string
|
||||
titleKey?: string
|
||||
icon: string
|
||||
path: string
|
||||
childrenPath?: string
|
||||
children?: MenuChild[]
|
||||
requiredCapability?: DeploymentCapabilityKey
|
||||
}
|
||||
|
||||
const createMenuChildren = () => reactive<MenuChild[]>([])
|
||||
|
||||
export const useMenuStore = defineStore('menuStore', () => {
|
||||
const menuArr = reactive<MenuItem[]>([
|
||||
{
|
||||
title: '',
|
||||
titleKey: 'menu.overview',
|
||||
icon: 'overview',
|
||||
path: 'overview'
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
titleKey: 'menu.newChat',
|
||||
icon: 'prefixIcon',
|
||||
path: 'creatChat',
|
||||
childrenPath: 'chat',
|
||||
children: createMenuChildren()
|
||||
},
|
||||
{ title: '', titleKey: 'menu.knowledgeBase', icon: 'zhishiku', path: 'knowledge-bases' },
|
||||
// Artifacts only exist where skills run in a sandbox.
|
||||
{ title: '', titleKey: 'menu.artifacts', icon: 'artifact', path: 'artifacts', requiredCapability: 'settings.sandbox' },
|
||||
{ title: '', titleKey: 'menu.agents', icon: 'agent', path: 'agents', requiredCapability: 'agents' },
|
||||
{ title: '', titleKey: 'menu.automations', icon: 'automation', path: 'automations' },
|
||||
{ title: '', titleKey: 'menu.training', icon: 'training', path: 'training' },
|
||||
{ title: '', titleKey: 'toolbox.title', icon: 'toolbox', path: 'toolbox' },
|
||||
{ title: '', titleKey: 'menu.organizations', icon: 'organization', path: 'organizations', requiredCapability: 'organizations' },
|
||||
{ title: '', titleKey: 'menu.settings', icon: 'setting', path: 'settings' },
|
||||
{ title: '', titleKey: 'menu.logout', icon: 'logout', path: 'logout' }
|
||||
])
|
||||
|
||||
const isFirstSession = ref(false)
|
||||
const firstQuery = ref('')
|
||||
const firstMentionedItems = ref<any[]>([])
|
||||
const firstModelId = ref('')
|
||||
const firstImageFiles = ref<any[]>([])
|
||||
const firstAttachmentFiles = ref<any[]>([])
|
||||
const firstQuestionOrigin = ref<QuestionOrigin | null>(null)
|
||||
const prefillQuery = ref('')
|
||||
|
||||
const applyMenuTranslations = () => {
|
||||
menuArr.forEach(item => {
|
||||
if (item.titleKey) {
|
||||
item.title = i18n.global.t(item.titleKey)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
applyMenuTranslations()
|
||||
|
||||
watch(
|
||||
() => i18n.global.locale.value,
|
||||
() => {
|
||||
applyMenuTranslations()
|
||||
}
|
||||
)
|
||||
|
||||
const liteHiddenPaths = new Set(['logout', 'organizations'])
|
||||
|
||||
// 共享空间 (organizations) 仅对当前空间的 admin / owner 暴露入口。
|
||||
// viewer / contributor 即便在共享空间里拥有资源,也无需自行管理共享关系,
|
||||
// 入口在侧栏只会徒增噪音;后端 RBAC 才是权限的最终来源(见 middleware/rbac.go)。
|
||||
const visibleMenuArr = computed(() => {
|
||||
const authStore = useAuthStore()
|
||||
const deploymentCapabilities = useDeploymentCapabilitiesStore()
|
||||
return menuArr.filter(item => {
|
||||
if (authStore.isLiteMode && liteHiddenPaths.has(item.path)) {
|
||||
return false
|
||||
}
|
||||
if (item.path === 'organizations' && !authStore.hasRole('admin')) {
|
||||
return false
|
||||
}
|
||||
if (!deploymentCapabilities.isSupported(item.requiredCapability)) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
})
|
||||
|
||||
const chatMenuIndex = menuArr.findIndex(item => item.path === 'creatChat')
|
||||
|
||||
const clearMenuArr = () => {
|
||||
const chatMenu = menuArr[chatMenuIndex]
|
||||
if (chatMenu && chatMenu.children) {
|
||||
chatMenu.children = createMenuChildren()
|
||||
}
|
||||
}
|
||||
|
||||
const updatemenuArr = (obj: any) => {
|
||||
const chatMenu = menuArr[chatMenuIndex]
|
||||
if (!chatMenu.children) {
|
||||
chatMenu.children = createMenuChildren()
|
||||
}
|
||||
const exists = chatMenu.children.some((item: MenuChild) => item.id === obj.id)
|
||||
if (!exists) {
|
||||
chatMenu.children.push(obj)
|
||||
}
|
||||
}
|
||||
|
||||
const updataMenuChildren = (item: MenuChild) => {
|
||||
const chatMenu = menuArr[chatMenuIndex]
|
||||
if (!chatMenu.children) {
|
||||
chatMenu.children = createMenuChildren()
|
||||
}
|
||||
chatMenu.children.unshift(item)
|
||||
}
|
||||
|
||||
const updatasessionTitle = (sessionId: string, title: string) => {
|
||||
const chatMenu = menuArr[chatMenuIndex]
|
||||
chatMenu.children?.forEach((item: MenuChild) => {
|
||||
if (item.id === sessionId) {
|
||||
item.title = title
|
||||
item.isNoTitle = false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const changeIsFirstSession = (payload: boolean) => {
|
||||
isFirstSession.value = payload
|
||||
}
|
||||
|
||||
const changeFirstQuery = (payload: string, mentionedItems: any[] = [], modelId: string = '', imageFiles: any[] = [], attachmentFiles: any[] = [], questionOrigin: QuestionOrigin | null = null) => {
|
||||
firstQuery.value = payload
|
||||
firstMentionedItems.value = mentionedItems
|
||||
firstModelId.value = modelId
|
||||
firstImageFiles.value = imageFiles
|
||||
firstAttachmentFiles.value = attachmentFiles
|
||||
firstQuestionOrigin.value = questionOrigin
|
||||
}
|
||||
|
||||
const setPrefillQuery = (q: string) => {
|
||||
prefillQuery.value = q
|
||||
}
|
||||
|
||||
const consumePrefillQuery = () => {
|
||||
const q = prefillQuery.value
|
||||
prefillQuery.value = ''
|
||||
return q
|
||||
}
|
||||
|
||||
return {
|
||||
menuArr,
|
||||
visibleMenuArr,
|
||||
isFirstSession,
|
||||
firstQuery,
|
||||
firstMentionedItems,
|
||||
firstModelId,
|
||||
firstImageFiles,
|
||||
firstAttachmentFiles,
|
||||
firstQuestionOrigin,
|
||||
prefillQuery,
|
||||
clearMenuArr,
|
||||
updatemenuArr,
|
||||
updataMenuChildren,
|
||||
updatasessionTitle,
|
||||
changeIsFirstSession,
|
||||
changeFirstQuery,
|
||||
setPrefillQuery,
|
||||
consumePrefillQuery
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,116 @@
|
||||
import { computed, ref } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import i18n from '@/i18n'
|
||||
import { listModelProviders, type ModelProviderOption } from '@/api/initialization'
|
||||
import {
|
||||
loadProvidersForType,
|
||||
mergeProviderIndex,
|
||||
providerDescription,
|
||||
providerIcon,
|
||||
providerLabel,
|
||||
} from '@/stores/modelProvidersState'
|
||||
|
||||
/**
|
||||
* Vendor catalog cache. Every component that renders a vendor (model
|
||||
* editor, model cards, debug drawer) reads through this store so the
|
||||
* frontend keeps no vendor table or naming heuristics of its own — the
|
||||
* backend catalog (GET /api/v1/models/providers) is the single source.
|
||||
*
|
||||
* Providers are fetched once per model type (the backend filters the
|
||||
* built-in model list by type) and merged into an id index so lookups by
|
||||
* provider id work regardless of which type loaded them first.
|
||||
*/
|
||||
export const useModelProvidersStore = defineStore('modelProviders', () => {
|
||||
const byType = ref<Record<string, ModelProviderOption[]>>({})
|
||||
const byId = ref<Record<string, ModelProviderOption>>({})
|
||||
const loadingByType = ref<Record<string, boolean>>({})
|
||||
let generation = 0
|
||||
const requestTokens = new Map<string, symbol>()
|
||||
const pending = new Map<string, Promise<ModelProviderOption[]>>()
|
||||
|
||||
const currentLocale = computed(() => String(i18n.global.locale.value || ''))
|
||||
|
||||
const normalizeType = (modelType?: string) => (modelType || '').trim().toLowerCase()
|
||||
|
||||
/**
|
||||
* Load providers for one model type (once); concurrent callers share the
|
||||
* request. Never rejects: a failed fetch resolves to [] and is NOT cached,
|
||||
* so the next component to mount retries instead of rendering an empty
|
||||
* vendor dropdown for the rest of the session.
|
||||
*/
|
||||
const ensureLoaded = async (modelType?: string, force = false): Promise<ModelProviderOption[]> => {
|
||||
const key = normalizeType(modelType)
|
||||
if (!force && byType.value[key]) return byType.value[key]
|
||||
const inflight = pending.get(key)
|
||||
if (inflight && !force) return inflight
|
||||
|
||||
const requestGeneration = generation
|
||||
const token = Symbol(key)
|
||||
requestTokens.set(key, token)
|
||||
const request = (async () => {
|
||||
loadingByType.value = { ...loadingByType.value, [key]: true }
|
||||
try {
|
||||
const { providers, cacheable } = await loadProvidersForType(listModelProviders, key)
|
||||
if (!cacheable || requestGeneration !== generation || requestTokens.get(key) !== token) return providers
|
||||
byType.value = { ...byType.value, [key]: providers }
|
||||
// The freshest list is merged first so its metadata wins over older types.
|
||||
byId.value = [providers, ...Object.entries(byType.value).filter(([type]) => type !== key).map(([, entries]) => entries)]
|
||||
.reduce((index, entries) => mergeProviderIndex(index, entries), {} as Record<string, ModelProviderOption>)
|
||||
return providers
|
||||
} finally {
|
||||
if (requestGeneration === generation && requestTokens.get(key) === token) {
|
||||
loadingByType.value = { ...loadingByType.value, [key]: false }
|
||||
}
|
||||
}
|
||||
})()
|
||||
pending.set(key, request)
|
||||
// Only drop our own entry: a concurrent force-reload may have replaced it.
|
||||
void request.finally(() => {
|
||||
if (pending.get(key) === request) pending.delete(key)
|
||||
})
|
||||
return request
|
||||
}
|
||||
|
||||
const providersFor = (modelType?: string): ModelProviderOption[] => byType.value[normalizeType(modelType)] || []
|
||||
|
||||
const isLoading = (modelType?: string): boolean => !!loadingByType.value[normalizeType(modelType)]
|
||||
|
||||
const providerById = (id?: string | null): ModelProviderOption | undefined => {
|
||||
if (!id) return undefined
|
||||
return byId.value[id]
|
||||
}
|
||||
|
||||
const iconFor = (id?: string | null): string => providerIcon(providerById(id))
|
||||
|
||||
const labelFor = (id?: string | null, locale?: string): string => {
|
||||
const provider = providerById(id)
|
||||
if (!provider) return id || ''
|
||||
return providerLabel(provider, locale ?? currentLocale.value)
|
||||
}
|
||||
|
||||
const descriptionFor = (id?: string | null, locale?: string): string =>
|
||||
providerDescription(providerById(id), locale ?? currentLocale.value)
|
||||
|
||||
const reset = () => {
|
||||
generation++
|
||||
requestTokens.clear()
|
||||
byType.value = {}
|
||||
byId.value = {}
|
||||
loadingByType.value = {}
|
||||
pending.clear()
|
||||
}
|
||||
|
||||
return {
|
||||
byType,
|
||||
byId,
|
||||
currentLocale,
|
||||
ensureLoaded,
|
||||
providersFor,
|
||||
isLoading,
|
||||
providerById,
|
||||
iconFor,
|
||||
labelFor,
|
||||
descriptionFor,
|
||||
reset,
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,260 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import type { ModelProviderOption } from '@/api/initialization'
|
||||
|
||||
import {
|
||||
credentialLabelForModelType,
|
||||
extraFieldLabel,
|
||||
extraFieldOptionLabel,
|
||||
extraFieldPlaceholder,
|
||||
extraFieldsForModelType,
|
||||
loadProvidersForType,
|
||||
mergeProviderIndex,
|
||||
normalizeModelType,
|
||||
pickLocalized,
|
||||
providerDescription,
|
||||
providerIcon,
|
||||
providerLabel,
|
||||
sortProviders,
|
||||
} from './modelProvidersState.ts'
|
||||
|
||||
/** loadProvidersForType logs failures; keep the test output readable. */
|
||||
async function withoutConsoleError<T>(run: () => Promise<T>): Promise<T> {
|
||||
const original = console.error
|
||||
console.error = () => {}
|
||||
try {
|
||||
return await run()
|
||||
} finally {
|
||||
console.error = original
|
||||
}
|
||||
}
|
||||
|
||||
const svgIcon = 'data:image/svg+xml;base64,PHN2Zy8+'
|
||||
|
||||
function provider(overrides: Partial<ModelProviderOption> & Pick<ModelProviderOption, 'value'>): ModelProviderOption {
|
||||
return {
|
||||
label: overrides.value,
|
||||
description: '',
|
||||
defaultUrls: {},
|
||||
modelTypes: ['chat'],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
test('providerLabel uses labels[locale], then the same language, then label', () => {
|
||||
const lkeap = provider({
|
||||
value: 'lkeap',
|
||||
label: 'Tencent Cloud LKEAP',
|
||||
labels: { 'zh-CN': '腾讯云 LKEAP' },
|
||||
})
|
||||
assert.equal(providerLabel(lkeap, 'zh-CN'), '腾讯云 LKEAP')
|
||||
assert.equal(providerLabel(lkeap, 'zh-TW'), '腾讯云 LKEAP', 'language match without exact region')
|
||||
assert.equal(providerLabel(lkeap, 'en-US'), 'Tencent Cloud LKEAP')
|
||||
assert.equal(providerLabel(lkeap, 'ja-JP'), 'Tencent Cloud LKEAP')
|
||||
assert.equal(providerLabel(lkeap), 'Tencent Cloud LKEAP')
|
||||
assert.equal(providerLabel(null, 'zh-CN'), '')
|
||||
})
|
||||
|
||||
test('providerLabel falls back to the id when the vendor ships no label', () => {
|
||||
assert.equal(providerLabel(provider({ value: 'custom', label: '' }), 'en-US'), 'custom')
|
||||
})
|
||||
|
||||
test('pickLocalized ignores empty localized strings', () => {
|
||||
assert.equal(pickLocalized({ 'zh-CN': ' ' }, 'zh-CN', 'fallback'), 'fallback')
|
||||
assert.equal(pickLocalized(undefined, 'zh-CN', 'fallback'), 'fallback')
|
||||
assert.equal(pickLocalized({ 'zh-CN': 'x' }, undefined, 'fallback'), 'fallback')
|
||||
})
|
||||
|
||||
test('providerDescription mirrors the label lookup', () => {
|
||||
const p = provider({ value: 'x', description: 'gpt-4o, o3', descriptions: { 'zh-CN': 'gpt-4o、o3 等' } })
|
||||
assert.equal(providerDescription(p, 'zh-CN'), 'gpt-4o、o3 等')
|
||||
assert.equal(providerDescription(p, 'ru-RU'), 'gpt-4o, o3')
|
||||
})
|
||||
|
||||
test('providerIcon only accepts data image URIs', () => {
|
||||
assert.equal(providerIcon(provider({ value: 'a', icon: svgIcon })), svgIcon)
|
||||
assert.equal(providerIcon(provider({ value: 'b' })), '')
|
||||
assert.equal(providerIcon(provider({ value: 'c', icon: 'https://evil.example/x.svg' })), '')
|
||||
assert.equal(providerIcon(undefined), '')
|
||||
})
|
||||
|
||||
test('extraFieldsForModelType honours model_types in either naming scheme', () => {
|
||||
const fields = [
|
||||
{ key: 'api_version', label: 'API Version', type: 'string' },
|
||||
{ key: 'secret_key', label: 'Secret Key', type: 'password', model_types: ['Rerank'], secret: true },
|
||||
{ key: 'region', label: 'Region', type: 'string', model_types: ['rerank'] },
|
||||
{ key: '', label: 'broken', type: 'string' },
|
||||
]
|
||||
assert.deepEqual(extraFieldsForModelType(fields, 'rerank').map((f) => f.key), ['api_version', 'secret_key', 'region'])
|
||||
assert.deepEqual(extraFieldsForModelType(fields, 'chat').map((f) => f.key), ['api_version'])
|
||||
assert.deepEqual(extraFieldsForModelType(fields, 'KnowledgeQA').map((f) => f.key), ['api_version'])
|
||||
assert.deepEqual(extraFieldsForModelType(undefined, 'chat'), [])
|
||||
})
|
||||
|
||||
test('normalizeModelType maps backend names onto editor names', () => {
|
||||
assert.equal(normalizeModelType('KnowledgeQA'), 'chat')
|
||||
assert.equal(normalizeModelType('VLLM'), 'vllm')
|
||||
assert.equal(normalizeModelType('embedding'), 'embedding')
|
||||
assert.equal(normalizeModelType(''), '')
|
||||
})
|
||||
|
||||
test('extraFieldLabel localizes with the same fallback chain', () => {
|
||||
const field = { key: 'region', label: 'Region', labels: { 'zh-CN': '地域' }, type: 'string' }
|
||||
assert.equal(extraFieldLabel(field, 'zh-CN'), '地域')
|
||||
assert.equal(extraFieldLabel(field, 'en-US'), 'Region')
|
||||
assert.equal(extraFieldLabel({ key: 'k', label: '', type: 'string' }), 'k')
|
||||
})
|
||||
|
||||
test('sortProviders orders by backend order then label', () => {
|
||||
const sorted = sortProviders([
|
||||
provider({ value: 'generic', label: 'Custom', order: 99 }),
|
||||
provider({ value: 'openai', label: 'OpenAI', order: 30 }),
|
||||
provider({ value: 'zeta', label: 'Zeta' }),
|
||||
provider({ value: 'aliyun', label: 'Aliyun', order: 30 }),
|
||||
])
|
||||
assert.deepEqual(sorted.map((p) => p.value), ['aliyun', 'openai', 'generic', 'zeta'])
|
||||
})
|
||||
|
||||
test('sortProviders survives rows with neither label nor value', () => {
|
||||
const sorted = sortProviders([
|
||||
{ description: '', defaultUrls: {}, modelTypes: [] } as unknown as ModelProviderOption,
|
||||
provider({ value: 'openai', label: 'OpenAI' }),
|
||||
])
|
||||
assert.equal(sorted.length, 2)
|
||||
})
|
||||
|
||||
test('loadProvidersForType caches a successful list, sorted and id-filtered', async () => {
|
||||
const seen: Array<string | undefined> = []
|
||||
const result = await loadProvidersForType(async (type) => {
|
||||
seen.push(type)
|
||||
return [
|
||||
provider({ value: 'zeta', label: 'Zeta' }),
|
||||
{ value: '', label: 'broken' },
|
||||
null,
|
||||
provider({ value: 'openai', label: 'OpenAI', order: 1 }),
|
||||
]
|
||||
}, 'chat')
|
||||
assert.deepEqual(seen, ['chat'])
|
||||
assert.equal(result.cacheable, true)
|
||||
assert.deepEqual(result.providers.map((p) => p.value), ['openai', 'zeta'])
|
||||
})
|
||||
|
||||
test('loadProvidersForType passes undefined for the all-types key', async () => {
|
||||
const seen: Array<string | undefined> = []
|
||||
await loadProvidersForType(async (type) => { seen.push(type); return [] }, '')
|
||||
assert.deepEqual(seen, [undefined])
|
||||
})
|
||||
|
||||
test('loadProvidersForType caches a genuinely empty catalog', async () => {
|
||||
const result = await loadProvidersForType(async () => [], 'rerank')
|
||||
assert.deepEqual(result, { providers: [], cacheable: true })
|
||||
})
|
||||
|
||||
test('loadProvidersForType never caches a failed or malformed response', async () => {
|
||||
await withoutConsoleError(async () => {
|
||||
const failed = await loadProvidersForType(async () => { throw new Error('502') }, 'chat')
|
||||
assert.deepEqual(failed, { providers: [], cacheable: false }, 'a transient failure must be retried')
|
||||
})
|
||||
for (const malformed of [null, undefined, { data: [] }, 'nope']) {
|
||||
const result = await loadProvidersForType(async () => malformed, 'chat')
|
||||
assert.deepEqual(result, { providers: [], cacheable: false })
|
||||
}
|
||||
})
|
||||
|
||||
test('mergeProviderIndex keeps catalog models collected across model types', () => {
|
||||
const chat = provider({ value: 'openai', models: [{ id: 'gpt-4o', name: 'GPT-4o', type: 'chat' }] })
|
||||
const embedding = provider({
|
||||
value: 'openai',
|
||||
models: [
|
||||
{ id: 'text-embedding-3-large', name: 'Embedding 3 Large', type: 'embedding' },
|
||||
{ id: 'gpt-4o', name: 'GPT-4o', type: 'chat' },
|
||||
],
|
||||
})
|
||||
const index = mergeProviderIndex(mergeProviderIndex({}, [chat]), [embedding])
|
||||
assert.deepEqual(index.openai.models?.map((m) => m.id), ['gpt-4o', 'text-embedding-3-large'])
|
||||
assert.equal(Object.keys(index).length, 1)
|
||||
})
|
||||
|
||||
test('mergeProviderIndex tolerates missing values and model lists', () => {
|
||||
const base = mergeProviderIndex({}, [
|
||||
provider({ value: 'openai' }),
|
||||
{ label: 'no id' } as unknown as ModelProviderOption,
|
||||
])
|
||||
assert.deepEqual(Object.keys(base), ['openai'])
|
||||
// A later fetch without `models` must not wipe what an earlier one collected.
|
||||
const withModels = mergeProviderIndex(
|
||||
mergeProviderIndex({}, [provider({ value: 'openai', models: [{ id: 'gpt-4o', name: 'GPT-4o', type: 'chat' }] })]),
|
||||
[provider({ value: 'openai', label: 'OpenAI' })],
|
||||
)
|
||||
assert.deepEqual(withModels.openai.models?.map((m) => m.id), ['gpt-4o'])
|
||||
assert.equal(withModels.openai.label, 'OpenAI', 'fresh metadata still wins')
|
||||
})
|
||||
|
||||
test('credentialLabelForModelType follows the vendor declaration, not a hardcoded table', () => {
|
||||
const labels = [
|
||||
{
|
||||
label: 'SecretId',
|
||||
labels: { 'zh-CN': 'SecretId(TC3 签名)' },
|
||||
placeholder: 'AKID...',
|
||||
hint: 'not an sk- key',
|
||||
model_types: ['Rerank'],
|
||||
required: true,
|
||||
},
|
||||
]
|
||||
// The signed rerank API renames the field; chat on the same vendor does not.
|
||||
const rerank = credentialLabelForModelType(labels, 'rerank')
|
||||
assert.equal(rerank?.label, 'SecretId')
|
||||
assert.equal(rerank?.required, true)
|
||||
assert.equal(credentialLabelForModelType(labels, 'chat'), null)
|
||||
assert.equal(credentialLabelForModelType(labels, 'embedding'), null)
|
||||
|
||||
// Backend spelling of the model type resolves the same way.
|
||||
assert.equal(credentialLabelForModelType(labels, 'Rerank')?.label, 'SecretId')
|
||||
|
||||
// Vendors that take a plain API key declare nothing.
|
||||
assert.equal(credentialLabelForModelType(undefined, 'rerank'), null)
|
||||
assert.equal(credentialLabelForModelType([], 'rerank'), null)
|
||||
|
||||
// An entry without a model_types filter applies to every type.
|
||||
const everywhere = [{ label: 'Access Key' }]
|
||||
assert.equal(credentialLabelForModelType(everywhere, 'chat')?.label, 'Access Key')
|
||||
|
||||
// Localization goes through the same picker as every other vendor string.
|
||||
assert.equal(pickLocalized(rerank?.labels, 'zh-CN', rerank!.label), 'SecretId(TC3 签名)')
|
||||
assert.equal(pickLocalized(rerank?.labels, 'en-US', rerank!.label), 'SecretId')
|
||||
})
|
||||
|
||||
// Select options and placeholders used to render their raw English string.
|
||||
// That was invisible while every option was an identifier — LKEAP's region
|
||||
// codes — and became a gap as soon as one was prose.
|
||||
test('extraFieldOptionLabel resolves the locale, falling back to label then value', () => {
|
||||
const option = {
|
||||
label: '0..1 relevance (BGE class)',
|
||||
labels: { 'zh-CN': '0~1 相关度(BGE 一类)' },
|
||||
value: 'probability',
|
||||
}
|
||||
assert.equal(extraFieldOptionLabel(option, 'zh-CN'), '0~1 相关度(BGE 一类)')
|
||||
assert.equal(extraFieldOptionLabel(option, 'en'), '0..1 relevance (BGE class)')
|
||||
assert.equal(
|
||||
extraFieldOptionLabel({ label: 'ap-guangzhou', value: 'ap-guangzhou' }, 'zh-CN'),
|
||||
'ap-guangzhou',
|
||||
)
|
||||
assert.equal(extraFieldOptionLabel({ value: 'logit' }, 'zh-CN'), 'logit')
|
||||
})
|
||||
|
||||
test('extraFieldPlaceholder resolves the locale and tolerates no placeholder', () => {
|
||||
const field = {
|
||||
key: 'score_scale',
|
||||
label: 'Rerank score scale',
|
||||
type: 'select',
|
||||
placeholder: 'match the reranker actually deployed behind this endpoint',
|
||||
placeholders: { 'zh-CN': '按这个端点后面实际部署的重排模型选择' },
|
||||
}
|
||||
assert.equal(extraFieldPlaceholder(field, 'zh-CN'), '按这个端点后面实际部署的重排模型选择')
|
||||
assert.equal(
|
||||
extraFieldPlaceholder(field, 'en'),
|
||||
'match the reranker actually deployed behind this endpoint',
|
||||
)
|
||||
assert.equal(extraFieldPlaceholder({ key: 'k', label: 'k', type: 'string' }, 'zh-CN'), '')
|
||||
})
|
||||
@@ -0,0 +1,183 @@
|
||||
/**
|
||||
* Pure helpers behind the modelProviders store. Kept free of Pinia / API
|
||||
* imports so they can be unit-tested under node:test.
|
||||
*
|
||||
* Every vendor fact the UI renders (name, description, icon, extra fields,
|
||||
* catalog models) comes from the backend catalog (internal/handler/
|
||||
* model_catalog.go); these helpers only pick the right locale / model type.
|
||||
*/
|
||||
import type {
|
||||
ModelProviderCredentialLabel,
|
||||
ModelProviderExtraField,
|
||||
ModelProviderOption,
|
||||
} from '@/api/initialization'
|
||||
|
||||
/** Editor model types → backend ModelType names used by ExtraField.model_types. */
|
||||
const FRONTEND_TO_BACKEND_MODEL_TYPE: Record<string, string> = {
|
||||
chat: 'KnowledgeQA',
|
||||
embedding: 'Embedding',
|
||||
rerank: 'Rerank',
|
||||
vllm: 'VLLM',
|
||||
asr: 'ASR',
|
||||
}
|
||||
|
||||
const BACKEND_TO_FRONTEND_MODEL_TYPE: Record<string, string> = Object.fromEntries(
|
||||
Object.entries(FRONTEND_TO_BACKEND_MODEL_TYPE).map(([front, back]) => [back, front]),
|
||||
)
|
||||
|
||||
/** Normalize either naming ("chat" / "KnowledgeQA") to the editor's lowercase form. */
|
||||
export function normalizeModelType(type: string | null | undefined): string {
|
||||
if (!type) return ''
|
||||
const trimmed = String(type).trim()
|
||||
if (FRONTEND_TO_BACKEND_MODEL_TYPE[trimmed]) return trimmed
|
||||
return BACKEND_TO_FRONTEND_MODEL_TYPE[trimmed] || trimmed.toLowerCase()
|
||||
}
|
||||
|
||||
/** Whether a field's model_types filter admits the given editor model type. */
|
||||
export function extraFieldAppliesTo(field: Pick<ModelProviderExtraField, 'model_types'>, modelType: string): boolean {
|
||||
const restricted = field.model_types
|
||||
if (!restricted || restricted.length === 0) return true
|
||||
const wanted = normalizeModelType(modelType)
|
||||
return restricted.some((entry) => normalizeModelType(entry) === wanted)
|
||||
}
|
||||
|
||||
/** Extra fields to render for a provider at one model type. */
|
||||
export function extraFieldsForModelType(
|
||||
fields: ReadonlyArray<ModelProviderExtraField> | null | undefined,
|
||||
modelType: string,
|
||||
): ModelProviderExtraField[] {
|
||||
if (!fields || fields.length === 0) return []
|
||||
return fields.filter((field) => !!field?.key && extraFieldAppliesTo(field, modelType))
|
||||
}
|
||||
|
||||
/**
|
||||
* The credential naming to use at one model type, or null when the vendor
|
||||
* takes a plain API key. First match wins, and an entry without a
|
||||
* `model_types` filter applies everywhere — same rule as extra fields.
|
||||
*/
|
||||
export function credentialLabelForModelType(
|
||||
labels: ReadonlyArray<ModelProviderCredentialLabel> | null | undefined,
|
||||
modelType: string,
|
||||
): ModelProviderCredentialLabel | null {
|
||||
if (!labels || labels.length === 0) return null
|
||||
return labels.find((label) => !!label?.label && extraFieldAppliesTo(label, modelType)) || null
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick a localized string from a `labels`-style map.
|
||||
*
|
||||
* Order: exact locale (`zh-CN`) → same language with any region (`zh-*`) →
|
||||
* the plain fallback. Empty strings never win.
|
||||
*/
|
||||
export function pickLocalized(
|
||||
localized: Record<string, string> | null | undefined,
|
||||
locale: string | null | undefined,
|
||||
fallback: string,
|
||||
): string {
|
||||
if (localized && locale) {
|
||||
const exact = localized[locale]
|
||||
if (typeof exact === 'string' && exact.trim()) return exact
|
||||
const language = locale.split(/[-_]/)[0]?.toLowerCase()
|
||||
if (language) {
|
||||
for (const [key, value] of Object.entries(localized)) {
|
||||
if (key.split(/[-_]/)[0]?.toLowerCase() === language && typeof value === 'string' && value.trim()) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
export function providerLabel(provider: ModelProviderOption | null | undefined, locale?: string): string {
|
||||
if (!provider) return ''
|
||||
return pickLocalized(provider.labels, locale, provider.label || provider.value || '')
|
||||
}
|
||||
|
||||
export function providerDescription(provider: ModelProviderOption | null | undefined, locale?: string): string {
|
||||
if (!provider) return ''
|
||||
return pickLocalized(provider.descriptions, locale, provider.description || '')
|
||||
}
|
||||
|
||||
/** `<img src>`-ready icon, or '' when the vendor ships none. */
|
||||
export function providerIcon(provider: ModelProviderOption | null | undefined): string {
|
||||
const icon = provider?.icon
|
||||
return typeof icon === 'string' && icon.startsWith('data:image/') ? icon : ''
|
||||
}
|
||||
|
||||
export function extraFieldLabel(field: ModelProviderExtraField, locale?: string): string {
|
||||
return pickLocalized(field.labels, locale, field.label || field.key)
|
||||
}
|
||||
|
||||
/** Placeholder for the current locale, falling back to the default string. */
|
||||
export function extraFieldPlaceholder(field: ModelProviderExtraField, locale?: string): string {
|
||||
return pickLocalized(field.placeholders, locale, field.placeholder || '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Option label for the current locale. Select options used to render their
|
||||
* raw `label`, which was fine while every option was an identifier (a region
|
||||
* code) and wrong as soon as one was prose.
|
||||
*/
|
||||
export function extraFieldOptionLabel(
|
||||
option: { label?: string; labels?: Record<string, string>; value: string },
|
||||
locale?: string,
|
||||
): string {
|
||||
return pickLocalized(option.labels, locale, option.label || option.value)
|
||||
}
|
||||
|
||||
/** Stable display order: backend `order`, then label. */
|
||||
export function sortProviders(providers: ReadonlyArray<ModelProviderOption>): ModelProviderOption[] {
|
||||
return [...providers].sort((a, b) => {
|
||||
const orderA = typeof a.order === 'number' ? a.order : Number.MAX_SAFE_INTEGER
|
||||
const orderB = typeof b.order === 'number' ? b.order : Number.MAX_SAFE_INTEGER
|
||||
if (orderA !== orderB) return orderA - orderB
|
||||
return String(a.label || a.value || '').localeCompare(String(b.label || b.value || ''))
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch + normalize the vendor list for one model type.
|
||||
*
|
||||
* `cacheable` is false for a failed or malformed response so the caller keeps
|
||||
* no cache entry and the next component to mount retries; caching a transient
|
||||
* failure would blank the vendor dropdown for the rest of the session.
|
||||
* An empty-but-valid list IS cacheable — that is a real answer.
|
||||
*/
|
||||
export async function loadProvidersForType(
|
||||
fetcher: (modelType?: string) => Promise<unknown>,
|
||||
modelType: string,
|
||||
): Promise<{ providers: ModelProviderOption[]; cacheable: boolean }> {
|
||||
try {
|
||||
const raw = await fetcher(modelType || undefined)
|
||||
if (!Array.isArray(raw)) return { providers: [], cacheable: false }
|
||||
const providers = (raw as ModelProviderOption[]).filter((p) => !!p && typeof p.value === 'string' && !!p.value)
|
||||
return { providers: sortProviders(providers), cacheable: true }
|
||||
} catch (error) {
|
||||
console.error('Failed to load model providers', error)
|
||||
return { providers: [], cacheable: false }
|
||||
}
|
||||
}
|
||||
|
||||
/** Merge a freshly fetched list into the id index without dropping models seen for other types. */
|
||||
export function mergeProviderIndex(
|
||||
index: Record<string, ModelProviderOption>,
|
||||
providers: ReadonlyArray<ModelProviderOption>,
|
||||
): Record<string, ModelProviderOption> {
|
||||
const next = { ...index }
|
||||
for (const provider of providers) {
|
||||
if (!provider?.value) continue
|
||||
const existing = next[provider.value]
|
||||
if (!existing) {
|
||||
next[provider.value] = provider
|
||||
continue
|
||||
}
|
||||
const seen = new Set((existing.models || []).filter((model) => !!model?.id).map((model) => model.id))
|
||||
const mergedModels = [
|
||||
...(existing.models || []),
|
||||
...(provider.models || []).filter((model) => !!model?.id && !seen.has(model.id)),
|
||||
]
|
||||
next[provider.value] = { ...existing, ...provider, models: mergedModels }
|
||||
}
|
||||
return next
|
||||
}
|
||||
@@ -0,0 +1,852 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import type {
|
||||
Organization,
|
||||
OrganizationMember,
|
||||
SharedKnowledgeBase,
|
||||
SharedAgentInfo,
|
||||
OrganizationPreview,
|
||||
ResourceCountsByOrg,
|
||||
SearchableOrganizationItem,
|
||||
UpdateOrganizationRequest,
|
||||
ShareKnowledgeBaseRequest,
|
||||
UpdateSharePermissionRequest,
|
||||
InviteMemberRequest,
|
||||
ReviewJoinRequestRequest,
|
||||
RequestRoleUpgradeRequest,
|
||||
ApiResponse,
|
||||
KnowledgeBaseShare,
|
||||
AgentShareResponse
|
||||
} from '@/api/organization'
|
||||
import {
|
||||
listMyOrganizations,
|
||||
createOrganization,
|
||||
updateOrganization as updateOrganizationApi,
|
||||
deleteOrganization,
|
||||
joinOrganization as joinOrganizationApi,
|
||||
joinOrganizationById as joinOrganizationByIdApi,
|
||||
previewOrganization,
|
||||
leaveOrganization,
|
||||
generateInviteCode,
|
||||
listMembers,
|
||||
updateMemberRole,
|
||||
removeMember,
|
||||
listSharedKnowledgeBases,
|
||||
listSharedAgents,
|
||||
searchSearchableOrganizations,
|
||||
shareKnowledgeBase as shareKnowledgeBaseApi,
|
||||
removeShare as removeShareApi,
|
||||
updateSharePermission as updateSharePermissionApi,
|
||||
shareAgent as shareAgentApi,
|
||||
removeAgentShare as removeAgentShareApi,
|
||||
inviteMember as inviteMemberApi,
|
||||
reviewJoinRequest as reviewJoinRequestApi,
|
||||
requestRoleUpgrade as requestRoleUpgradeApi
|
||||
} from '@/api/organization'
|
||||
import { getCurrentLanguage } from '@/utils/request'
|
||||
import { createVersionedRequestCoordinator } from './versionedRequest'
|
||||
import { shouldForceLocalizedRefetch } from './localizedResourceCache'
|
||||
import {
|
||||
applyOrganizationResourceDelta,
|
||||
upsertById,
|
||||
mergeById,
|
||||
reviewMemberCountDelta
|
||||
} from './organizationState'
|
||||
|
||||
export const useOrganizationStore = defineStore('organization', () => {
|
||||
// State
|
||||
const organizations = ref<Organization[]>([])
|
||||
const currentOrganization = ref<Organization | null>(null)
|
||||
const currentMembers = ref<OrganizationMember[]>([])
|
||||
const sharedKnowledgeBases = ref<SharedKnowledgeBase[]>([])
|
||||
const sharedAgents = ref<SharedAgentInfo[]>([])
|
||||
const searchableOrganizations = ref<SearchableOrganizationItem[]>([])
|
||||
const previewData = ref<OrganizationPreview | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
/** 各空间内知识库/智能体数量(由 GET /organizations 的 resource_counts 填充,供列表侧栏使用) */
|
||||
const resourceCounts = ref<ResourceCountsByOrg | null>(null)
|
||||
// 组织 / 共享资源列表不设 TTL:每次 fetch 都发请求(并发共用同一个),
|
||||
// 写操作后 `fetch({ force: true })` 排在飞行中的请求之后再拉一次。
|
||||
// 输入联想的搜索结果例外,按查询串短期记忆,写操作时整体清空。
|
||||
const SEARCHABLE_ORGANIZATION_TTL_MS = 5 * 60_000
|
||||
/** 共享智能体含按请求语言本地化的内置名称;切换 UI 语言后快照随之失效 */
|
||||
let sharedAgentsLoadedLocale = ''
|
||||
let sharedAgentsInflightLocale = ''
|
||||
let searchableOrganizationsQuery = ''
|
||||
const searchableOrganizationCache = new Map<
|
||||
string,
|
||||
{ data: SearchableOrganizationItem[]; loadedAt: number }
|
||||
>()
|
||||
|
||||
// Computed
|
||||
const myOrganizations = computed(() => organizations.value)
|
||||
|
||||
const ownedOrganizations = computed(() =>
|
||||
organizations.value.filter(org => org.is_owner)
|
||||
)
|
||||
|
||||
const joinedOrganizations = computed(() =>
|
||||
organizations.value.filter(org => !org.is_owner)
|
||||
)
|
||||
|
||||
/** 当前用户作为管理员/创建者可见的待审批加入申请总数(用于侧栏提醒) */
|
||||
const totalPendingJoinRequestCount = computed(() =>
|
||||
organizations.value.reduce((sum, org) => sum + (org.pending_join_request_count ?? 0), 0)
|
||||
)
|
||||
|
||||
// Actions
|
||||
|
||||
/**
|
||||
* Fetch all organizations the user belongs to.
|
||||
* 并发去重,列表页与侧栏等多处共用。
|
||||
*/
|
||||
const organizationsRequest = createVersionedRequestCoordinator(
|
||||
async () => {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
return await listMyOrganizations()
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
},
|
||||
(response) => {
|
||||
if (response.success && response.data) {
|
||||
organizations.value = response.data.organizations
|
||||
resourceCounts.value = response.data.resource_counts ?? null
|
||||
} else {
|
||||
resourceCounts.value = null
|
||||
error.value = response.message || 'Failed to fetch organizations'
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
async function fetchOrganizations(options?: { force?: boolean }) {
|
||||
return organizationsRequest.fetch(options?.force ?? false)
|
||||
}
|
||||
|
||||
function patchOrganization(id: string, patch: Partial<Organization>) {
|
||||
organizationsRequest.invalidate()
|
||||
organizations.value = organizations.value.map(org =>
|
||||
org.id === id ? { ...org, ...patch } : org
|
||||
)
|
||||
if (currentOrganization.value?.id === id) {
|
||||
currentOrganization.value = { ...currentOrganization.value, ...patch }
|
||||
}
|
||||
}
|
||||
|
||||
function upsertOrganization(organization: Organization) {
|
||||
organizationsRequest.invalidate()
|
||||
organizations.value = upsertById(organizations.value, organization)
|
||||
if (currentOrganization.value?.id === organization.id) {
|
||||
currentOrganization.value = organization
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge a detail payload (which may omit list-only aggregate fields) onto the
|
||||
* existing card instead of replacing it, so badges like share_count survive.
|
||||
*/
|
||||
function mergeOrganizationDetail(organization: Organization) {
|
||||
organizationsRequest.invalidate()
|
||||
const next = mergeById(organizations.value, organization)
|
||||
organizations.value = next
|
||||
currentOrganization.value =
|
||||
next.find(org => org.id === organization.id) ?? organization
|
||||
}
|
||||
|
||||
function adjustOrganizationResourceCount(
|
||||
organizationId: string,
|
||||
resource: 'knowledge_bases' | 'agents',
|
||||
delta: number
|
||||
) {
|
||||
organizationsRequest.invalidate()
|
||||
const result = applyOrganizationResourceDelta(
|
||||
organizations.value,
|
||||
resourceCounts.value,
|
||||
organizationId,
|
||||
resource,
|
||||
delta
|
||||
)
|
||||
organizations.value = result.organizations
|
||||
resourceCounts.value = result.resourceCounts
|
||||
if (currentOrganization.value?.id === organizationId) {
|
||||
currentOrganization.value =
|
||||
result.organizations.find(org => org.id === organizationId) ?? currentOrganization.value
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new organization
|
||||
*/
|
||||
async function create(name: string, description?: string, avatar?: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await createOrganization({ name, description, avatar })
|
||||
if (response.success && response.data) {
|
||||
upsertOrganization(response.data)
|
||||
// 创建接口不返回 resource_counts 等聚合字段,强刷一次列表补齐。
|
||||
void fetchOrganizations({ force: true })
|
||||
return response.data
|
||||
} else {
|
||||
error.value = response.message || 'Failed to create organization'
|
||||
return null
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to create organization'
|
||||
return null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an organization
|
||||
*/
|
||||
async function updateOrganization(id: string, updates: UpdateOrganizationRequest) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await updateOrganizationApi(id, updates)
|
||||
if (response.success && response.data) {
|
||||
upsertOrganization(response.data)
|
||||
void fetchOrganizations({ force: true })
|
||||
return response.data
|
||||
} else {
|
||||
error.value = response.message || 'Failed to update organization'
|
||||
return null
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to update organization'
|
||||
return null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function update(id: string, name?: string, description?: string) {
|
||||
return updateOrganization(id, { name, description })
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an organization
|
||||
*/
|
||||
async function remove(id: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await deleteOrganization(id)
|
||||
if (response.success) {
|
||||
organizationsRequest.invalidate()
|
||||
organizations.value = organizations.value.filter(o => o.id !== id)
|
||||
if (currentOrganization.value?.id === id) {
|
||||
currentOrganization.value = null
|
||||
}
|
||||
return true
|
||||
} else {
|
||||
error.value = response.message || 'Failed to delete organization'
|
||||
return false
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to delete organization'
|
||||
return false
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Preview an organization by invite code (without joining)
|
||||
*/
|
||||
async function preview(inviteCode: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
previewData.value = null
|
||||
try {
|
||||
const response = await previewOrganization(inviteCode)
|
||||
if (response.success && response.data) {
|
||||
previewData.value = response.data
|
||||
return response.data
|
||||
} else {
|
||||
error.value = response.message || 'Failed to preview organization'
|
||||
return null
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to preview organization'
|
||||
return null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Join an organization by invite code
|
||||
*/
|
||||
async function join(inviteCode: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await joinOrganizationApi({ invite_code: inviteCode })
|
||||
if (response.success && response.data) {
|
||||
upsertOrganization(response.data)
|
||||
invalidateSearchableOrganizations(response.data.id)
|
||||
void fetchOrganizations({ force: true })
|
||||
return response.data
|
||||
} else {
|
||||
error.value = response.message || 'Failed to join organization'
|
||||
return null
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to join organization'
|
||||
return null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Leave an organization
|
||||
*/
|
||||
async function leave(id: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await leaveOrganization(id)
|
||||
if (response.success) {
|
||||
organizationsRequest.invalidate()
|
||||
organizations.value = organizations.value.filter(o => o.id !== id)
|
||||
if (currentOrganization.value?.id === id) {
|
||||
currentOrganization.value = null
|
||||
}
|
||||
return true
|
||||
} else {
|
||||
error.value = response.message || 'Failed to leave organization'
|
||||
return false
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to leave organization'
|
||||
return false
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new invite code
|
||||
*/
|
||||
async function refreshInviteCode(id: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await generateInviteCode(id)
|
||||
if (response.success && response.data) {
|
||||
patchOrganization(id, { invite_code: response.data.invite_code })
|
||||
void fetchOrganizations({ force: true })
|
||||
return response.data.invite_code
|
||||
} else {
|
||||
error.value = response.message || 'Failed to generate invite code'
|
||||
return null
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to generate invite code'
|
||||
return null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch members of an organization
|
||||
*/
|
||||
async function fetchMembers(orgId: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await listMembers(orgId)
|
||||
if (response.success && response.data) {
|
||||
currentMembers.value = response.data.members
|
||||
return response.data.members
|
||||
} else {
|
||||
error.value = response.message || 'Failed to fetch members'
|
||||
return []
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to fetch members'
|
||||
return []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a member's role (member identified by tenant_id)
|
||||
*/
|
||||
async function changeMemberRole(orgId: string, tenantId: number, role: 'admin' | 'editor' | 'viewer') {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await updateMemberRole(orgId, tenantId, { role })
|
||||
if (response.success) {
|
||||
const member = currentMembers.value.find(m => m.tenant_id === tenantId)
|
||||
if (member) {
|
||||
member.role = role
|
||||
}
|
||||
return true
|
||||
} else {
|
||||
error.value = response.message || 'Failed to update member role'
|
||||
return false
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to update member role'
|
||||
return false
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a member from organization (member identified by tenant_id)
|
||||
*/
|
||||
async function kickMember(orgId: string, tenantId: number) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await removeMember(orgId, tenantId)
|
||||
if (response.success) {
|
||||
currentMembers.value = currentMembers.value.filter(m => m.tenant_id !== tenantId)
|
||||
const organization = organizations.value.find(org => org.id === orgId)
|
||||
patchOrganization(orgId, {
|
||||
member_count: Math.max(0, (organization?.member_count ?? 0) - 1)
|
||||
})
|
||||
void fetchOrganizations({ force: true })
|
||||
return true
|
||||
} else {
|
||||
error.value = response.message || 'Failed to remove member'
|
||||
return false
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to remove member'
|
||||
return false
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch shared knowledge bases.
|
||||
* 并发去重,避免对话页等多处同时重复请求。
|
||||
*/
|
||||
const sharedKnowledgeBasesRequest = createVersionedRequestCoordinator(
|
||||
async () => {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
return await listSharedKnowledgeBases()
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
},
|
||||
(response) => {
|
||||
if (response.success && response.data) {
|
||||
sharedKnowledgeBases.value = response.data.filter(s => s.knowledge_base != null)
|
||||
} else {
|
||||
error.value = response.message || 'Failed to fetch shared knowledge bases'
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
async function fetchSharedKnowledgeBases(options?: { force?: boolean }) {
|
||||
await sharedKnowledgeBasesRequest.fetch(options?.force ?? false)
|
||||
return sharedKnowledgeBases.value
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch shared agents (shared to me through organizations).
|
||||
* 并发去重;快照只对拉取时的 UI 语言有效。
|
||||
*/
|
||||
const sharedAgentsRequest = createVersionedRequestCoordinator(
|
||||
async () => {
|
||||
const locale = getCurrentLanguage()
|
||||
sharedAgentsInflightLocale = locale
|
||||
const response = await listSharedAgents()
|
||||
return { response, locale }
|
||||
},
|
||||
({ response, locale }) => {
|
||||
if (response.success && response.data) {
|
||||
sharedAgents.value = response.data.filter(s => s.agent != null)
|
||||
sharedAgentsLoadedLocale = locale
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
watch(
|
||||
() => getCurrentLanguage(),
|
||||
(locale) => {
|
||||
if (sharedAgentsLoadedLocale && sharedAgentsLoadedLocale !== locale) {
|
||||
sharedAgentsRequest.invalidate()
|
||||
sharedAgentsLoadedLocale = ''
|
||||
sharedAgentsInflightLocale = ''
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
async function fetchSharedAgents(options?: { force?: boolean }) {
|
||||
const locale = getCurrentLanguage()
|
||||
const force = options?.force ?? false
|
||||
// 飞行中的请求是用另一种语言发起的:不能复用它,排在它后面再发一次。
|
||||
const mustForce =
|
||||
force ||
|
||||
shouldForceLocalizedRefetch(
|
||||
sharedAgentsRequest.hasInFlightRequest(),
|
||||
sharedAgentsInflightLocale,
|
||||
locale,
|
||||
)
|
||||
await sharedAgentsRequest.fetch(mustForce)
|
||||
return sharedAgents.value
|
||||
}
|
||||
|
||||
interface InvalidateOrganizationDataOptions {
|
||||
organizations?: boolean
|
||||
sharedKnowledgeBases?: boolean
|
||||
sharedAgents?: boolean
|
||||
searchableOrganizations?: boolean
|
||||
excludeSearchableOrganizationId?: string
|
||||
}
|
||||
|
||||
function invalidateSearchableOrganizations(organizationId?: string) {
|
||||
searchableOrganizationCache.clear()
|
||||
if (organizationId) {
|
||||
searchableOrganizations.value = searchableOrganizations.value.filter(
|
||||
organization => organization.id !== organizationId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function invalidateOrganizationData(options: InvalidateOrganizationDataOptions) {
|
||||
if (options.organizations) {
|
||||
organizationsRequest.invalidate()
|
||||
}
|
||||
if (options.sharedKnowledgeBases) {
|
||||
sharedKnowledgeBasesRequest.invalidate()
|
||||
}
|
||||
if (options.sharedAgents) {
|
||||
sharedAgentsRequest.invalidate()
|
||||
sharedAgentsLoadedLocale = ''
|
||||
sharedAgentsInflightLocale = ''
|
||||
}
|
||||
if (options.searchableOrganizations) {
|
||||
invalidateSearchableOrganizations(options.excludeSearchableOrganizationId)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchSearchableOrganizations(
|
||||
query: string,
|
||||
options?: { force?: boolean; limit?: number }
|
||||
) {
|
||||
const normalizedQuery = query.trim()
|
||||
searchableOrganizationsQuery = normalizedQuery
|
||||
const cached = searchableOrganizationCache.get(normalizedQuery)
|
||||
if (
|
||||
!options?.force &&
|
||||
cached &&
|
||||
Date.now() - cached.loadedAt < SEARCHABLE_ORGANIZATION_TTL_MS
|
||||
) {
|
||||
searchableOrganizations.value = cached.data
|
||||
return cached.data
|
||||
}
|
||||
|
||||
const response = await searchSearchableOrganizations(normalizedQuery, options?.limit ?? 20)
|
||||
if (response.success && response.data) {
|
||||
const data = response.data.data.filter(organization => !organization.is_already_member)
|
||||
searchableOrganizationCache.set(normalizedQuery, { data, loadedAt: Date.now() })
|
||||
if (searchableOrganizationsQuery === normalizedQuery) {
|
||||
searchableOrganizations.value = data
|
||||
}
|
||||
return data
|
||||
}
|
||||
if (searchableOrganizationsQuery === normalizedQuery) {
|
||||
searchableOrganizations.value = []
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
function clearSearchableOrganizations() {
|
||||
searchableOrganizationsQuery = ''
|
||||
searchableOrganizations.value = []
|
||||
}
|
||||
|
||||
async function joinById(
|
||||
organizationId: string,
|
||||
message?: string,
|
||||
role?: 'admin' | 'editor' | 'viewer',
|
||||
options?: { requiresApproval?: boolean }
|
||||
) {
|
||||
const response = await joinOrganizationByIdApi(organizationId, message, role)
|
||||
if (response.success) {
|
||||
invalidateOrganizationData({
|
||||
searchableOrganizations: true,
|
||||
excludeSearchableOrganizationId: organizationId
|
||||
})
|
||||
if (!options?.requiresApproval && response.data) {
|
||||
upsertOrganization(response.data)
|
||||
void fetchOrganizations({ force: true })
|
||||
}
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
async function shareKnowledgeBase(
|
||||
knowledgeBaseId: string,
|
||||
request: ShareKnowledgeBaseRequest
|
||||
): Promise<ApiResponse<KnowledgeBaseShare>> {
|
||||
const response = await shareKnowledgeBaseApi(knowledgeBaseId, request)
|
||||
if (response.success) {
|
||||
adjustOrganizationResourceCount(request.organization_id, 'knowledge_bases', 1)
|
||||
invalidateOrganizationData({ sharedKnowledgeBases: true })
|
||||
void Promise.all([
|
||||
fetchOrganizations({ force: true }),
|
||||
fetchSharedKnowledgeBases({ force: true })
|
||||
])
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
async function unshareKnowledgeBase(
|
||||
knowledgeBaseId: string,
|
||||
shareId: string,
|
||||
organizationId: string
|
||||
): Promise<ApiResponse<void>> {
|
||||
const response = await removeShareApi(knowledgeBaseId, shareId)
|
||||
if (response.success) {
|
||||
adjustOrganizationResourceCount(organizationId, 'knowledge_bases', -1)
|
||||
invalidateOrganizationData({ sharedKnowledgeBases: true })
|
||||
void Promise.all([
|
||||
fetchOrganizations({ force: true }),
|
||||
fetchSharedKnowledgeBases({ force: true })
|
||||
])
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
async function changeKnowledgeBaseSharePermission(
|
||||
knowledgeBaseId: string,
|
||||
shareId: string,
|
||||
request: UpdateSharePermissionRequest
|
||||
): Promise<ApiResponse<void>> {
|
||||
const response = await updateSharePermissionApi(knowledgeBaseId, shareId, request)
|
||||
if (response.success) {
|
||||
invalidateOrganizationData({ sharedKnowledgeBases: true })
|
||||
void fetchSharedKnowledgeBases({ force: true })
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
async function shareAgent(
|
||||
agentId: string,
|
||||
request: ShareKnowledgeBaseRequest
|
||||
): Promise<ApiResponse<AgentShareResponse>> {
|
||||
const response = await shareAgentApi(agentId, request)
|
||||
if (response.success) {
|
||||
adjustOrganizationResourceCount(request.organization_id, 'agents', 1)
|
||||
invalidateOrganizationData({ sharedAgents: true, sharedKnowledgeBases: true })
|
||||
void Promise.all([
|
||||
fetchOrganizations({ force: true }),
|
||||
fetchSharedAgents({ force: true }),
|
||||
fetchSharedKnowledgeBases({ force: true })
|
||||
])
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
async function unshareAgent(
|
||||
agentId: string,
|
||||
shareId: string,
|
||||
organizationId: string
|
||||
): Promise<ApiResponse<void>> {
|
||||
const response = await removeAgentShareApi(agentId, shareId)
|
||||
if (response.success) {
|
||||
adjustOrganizationResourceCount(organizationId, 'agents', -1)
|
||||
invalidateOrganizationData({ sharedAgents: true, sharedKnowledgeBases: true })
|
||||
void Promise.all([
|
||||
fetchOrganizations({ force: true }),
|
||||
fetchSharedAgents({ force: true }),
|
||||
fetchSharedKnowledgeBases({ force: true })
|
||||
])
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
async function inviteOrganizationMember(
|
||||
organizationId: string,
|
||||
request: InviteMemberRequest
|
||||
): Promise<ApiResponse<void>> {
|
||||
const response = await inviteMemberApi(organizationId, request)
|
||||
if (response.success) {
|
||||
const organization = organizations.value.find(org => org.id === organizationId)
|
||||
patchOrganization(organizationId, {
|
||||
member_count: (organization?.member_count ?? 0) + 1
|
||||
})
|
||||
void fetchOrganizations({ force: true })
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
async function reviewOrganizationJoinRequest(
|
||||
organizationId: string,
|
||||
requestId: string,
|
||||
request: ReviewJoinRequestRequest,
|
||||
options?: { requestType?: 'join' | 'upgrade' }
|
||||
): Promise<ApiResponse<void>> {
|
||||
const response = await reviewJoinRequestApi(organizationId, requestId, request)
|
||||
if (response.success) {
|
||||
const organization = organizations.value.find(org => org.id === organizationId)
|
||||
patchOrganization(organizationId, {
|
||||
member_count:
|
||||
(organization?.member_count ?? 0) +
|
||||
reviewMemberCountDelta(request.approved, options?.requestType),
|
||||
pending_join_request_count: Math.max(
|
||||
0,
|
||||
(organization?.pending_join_request_count ?? 0) - 1
|
||||
)
|
||||
})
|
||||
void fetchOrganizations({ force: true })
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
async function requestOrganizationRoleUpgrade(
|
||||
organizationId: string,
|
||||
request: RequestRoleUpgradeRequest
|
||||
) {
|
||||
const response = await requestRoleUpgradeApi(organizationId, request)
|
||||
if (response.success) {
|
||||
patchOrganization(organizationId, { has_pending_upgrade: true })
|
||||
void fetchOrganizations({ force: true })
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
/**
|
||||
* Set current organization for detail view
|
||||
*/
|
||||
function setCurrentOrganization(org: Organization | null) {
|
||||
if (org) {
|
||||
mergeOrganizationDetail(org)
|
||||
void fetchOrganizations({ force: true })
|
||||
} else {
|
||||
currentOrganization.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function clearCurrentOrganizationContext() {
|
||||
currentOrganization.value = null
|
||||
currentMembers.value = []
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user's permission for a specific knowledge base
|
||||
* Returns 'owner' if user owns the KB, or the share permission ('admin' | 'editor' | 'viewer'), or null if no access
|
||||
*/
|
||||
function getKBPermission(kbId: string): 'owner' | 'admin' | 'editor' | 'viewer' | null {
|
||||
const shared = sharedKnowledgeBases.value.find(
|
||||
s => s.knowledge_base?.id === kbId
|
||||
)
|
||||
return shared?.permission || null
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if user can edit a knowledge base (owner, admin, or editor)
|
||||
*/
|
||||
function canEditKB(kbId: string, isOwner: boolean): boolean {
|
||||
if (isOwner) return true
|
||||
const permission = getKBPermission(kbId)
|
||||
return permission === 'admin' || permission === 'editor'
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if user can delete/manage a knowledge base (owner or admin only)
|
||||
*/
|
||||
function canManageKB(kbId: string, isOwner: boolean): boolean {
|
||||
if (isOwner) return true
|
||||
const permission = getKBPermission(kbId)
|
||||
return permission === 'admin'
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all state
|
||||
*/
|
||||
function clearState() {
|
||||
organizations.value = []
|
||||
currentOrganization.value = null
|
||||
currentMembers.value = []
|
||||
sharedKnowledgeBases.value = []
|
||||
sharedAgents.value = []
|
||||
searchableOrganizations.value = []
|
||||
resourceCounts.value = null
|
||||
previewData.value = null
|
||||
error.value = null
|
||||
sharedAgentsLoadedLocale = ''
|
||||
sharedAgentsInflightLocale = ''
|
||||
searchableOrganizationsQuery = ''
|
||||
searchableOrganizationCache.clear()
|
||||
organizationsRequest.invalidate()
|
||||
sharedKnowledgeBasesRequest.invalidate()
|
||||
sharedAgentsRequest.invalidate()
|
||||
}
|
||||
|
||||
return {
|
||||
// State
|
||||
organizations,
|
||||
currentOrganization,
|
||||
currentMembers,
|
||||
sharedKnowledgeBases,
|
||||
sharedAgents,
|
||||
searchableOrganizations,
|
||||
resourceCounts,
|
||||
previewData,
|
||||
loading,
|
||||
error,
|
||||
|
||||
// Computed
|
||||
myOrganizations,
|
||||
ownedOrganizations,
|
||||
joinedOrganizations,
|
||||
totalPendingJoinRequestCount,
|
||||
|
||||
// Actions
|
||||
fetchOrganizations,
|
||||
create,
|
||||
updateOrganization,
|
||||
update,
|
||||
remove,
|
||||
preview,
|
||||
join,
|
||||
leave,
|
||||
refreshInviteCode,
|
||||
fetchMembers,
|
||||
changeMemberRole,
|
||||
kickMember,
|
||||
fetchSharedKnowledgeBases,
|
||||
fetchSharedAgents,
|
||||
fetchSearchableOrganizations,
|
||||
clearSearchableOrganizations,
|
||||
invalidateOrganizationData,
|
||||
joinById,
|
||||
shareKnowledgeBase,
|
||||
unshareKnowledgeBase,
|
||||
changeKnowledgeBaseSharePermission,
|
||||
shareAgent,
|
||||
unshareAgent,
|
||||
inviteOrganizationMember,
|
||||
reviewOrganizationJoinRequest,
|
||||
requestOrganizationRoleUpgrade,
|
||||
setCurrentOrganization,
|
||||
clearCurrentOrganizationContext,
|
||||
getKBPermission,
|
||||
canEditKB,
|
||||
canManageKB,
|
||||
clearState
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
applyOrganizationResourceDelta,
|
||||
upsertById,
|
||||
mergeById,
|
||||
reviewMemberCountDelta
|
||||
} from './organizationState.ts'
|
||||
|
||||
test('upsert adds a newly joined organization to the front', () => {
|
||||
const result = upsertById(
|
||||
[{ id: 'existing', name: 'Existing' }],
|
||||
{ id: 'joined', name: 'Joined' }
|
||||
)
|
||||
|
||||
assert.deepEqual(result.map(organization => organization.id), ['joined', 'existing'])
|
||||
})
|
||||
|
||||
test('upsert replaces edited organization data without duplicating the card', () => {
|
||||
const result = upsertById(
|
||||
[{ id: 'space-1', name: 'Old name' }],
|
||||
{ id: 'space-1', name: 'New name' }
|
||||
)
|
||||
|
||||
assert.deepEqual(result, [{ id: 'space-1', name: 'New name' }])
|
||||
})
|
||||
|
||||
test('knowledge base sharing updates card and resource counts immediately', () => {
|
||||
const result = applyOrganizationResourceDelta(
|
||||
[{ id: 'space-1', share_count: 2 }],
|
||||
{
|
||||
knowledge_bases: { by_organization: { 'space-1': 2 } },
|
||||
agents: { by_organization: { 'space-1': 1 } }
|
||||
},
|
||||
'space-1',
|
||||
'knowledge_bases',
|
||||
1
|
||||
)
|
||||
|
||||
assert.equal(result.organizations[0].share_count, 3)
|
||||
assert.equal(result.resourceCounts?.knowledge_bases.by_organization['space-1'], 3)
|
||||
})
|
||||
|
||||
test('resource counts never become negative when a share is removed', () => {
|
||||
const result = applyOrganizationResourceDelta(
|
||||
[{ id: 'space-1', agent_share_count: 0 }],
|
||||
{
|
||||
knowledge_bases: { by_organization: {} },
|
||||
agents: { by_organization: { 'space-1': 0 } }
|
||||
},
|
||||
'space-1',
|
||||
'agents',
|
||||
-1
|
||||
)
|
||||
|
||||
assert.equal(result.organizations[0].agent_share_count, 0)
|
||||
assert.equal(result.resourceCounts?.agents.by_organization['space-1'], 0)
|
||||
})
|
||||
|
||||
test('merge keeps list-only aggregate fields when a detail payload omits them', () => {
|
||||
const result = mergeById(
|
||||
[{ id: 'space-1', name: 'Old name', share_count: 5, agent_share_count: 2 }],
|
||||
{ id: 'space-1', name: 'New name' }
|
||||
)
|
||||
|
||||
assert.deepEqual(result, [
|
||||
{ id: 'space-1', name: 'New name', share_count: 5, agent_share_count: 2 }
|
||||
])
|
||||
})
|
||||
|
||||
test('merge inserts a brand-new organization at the front', () => {
|
||||
const result = mergeById(
|
||||
[{ id: 'existing', name: 'Existing' }],
|
||||
{ id: 'new', name: 'New' }
|
||||
)
|
||||
|
||||
assert.deepEqual(result.map(organization => organization.id), ['new', 'existing'])
|
||||
})
|
||||
|
||||
test('approving a new join request adds one member', () => {
|
||||
assert.equal(reviewMemberCountDelta(true, 'join'), 1)
|
||||
})
|
||||
|
||||
test('approving a role upgrade does not change member_count', () => {
|
||||
assert.equal(reviewMemberCountDelta(true, 'upgrade'), 0)
|
||||
})
|
||||
|
||||
test('rejecting any request does not change member_count', () => {
|
||||
assert.equal(reviewMemberCountDelta(false, 'join'), 0)
|
||||
assert.equal(reviewMemberCountDelta(false, 'upgrade'), 0)
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
export function upsertById<T extends { id: string }>(items: T[], item: T): T[] {
|
||||
const exists = items.some(existing => existing.id === item.id)
|
||||
return exists
|
||||
? items.map(existing => existing.id === item.id ? item : existing)
|
||||
: [item, ...items]
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge a (possibly partial) organization payload onto the existing card.
|
||||
*
|
||||
* Detail endpoints (e.g. GET /organizations/:id) may omit list-only aggregate
|
||||
* fields such as share_count / agent_share_count / pending_join_request_count.
|
||||
* A plain replace would blank those badges until the background refresh lands,
|
||||
* so when a card already exists we shallow-merge instead of overwriting it.
|
||||
*/
|
||||
export function mergeById<T extends { id: string }>(items: T[], item: T): T[] {
|
||||
const existing = items.find(entry => entry.id === item.id)
|
||||
const merged = existing ? { ...existing, ...item } : item
|
||||
return upsertById(items, merged)
|
||||
}
|
||||
|
||||
/**
|
||||
* How much a join-request review changes the organization's member_count.
|
||||
*
|
||||
* Only brand-new "join" approvals add a member. Approving an "upgrade" request
|
||||
* (an existing member asking for a higher role) must not change member_count.
|
||||
*/
|
||||
export function reviewMemberCountDelta(
|
||||
approved: boolean,
|
||||
requestType: 'join' | 'upgrade' | undefined
|
||||
): number {
|
||||
return approved && requestType !== 'upgrade' ? 1 : 0
|
||||
}
|
||||
|
||||
interface OrganizationResourceCounts {
|
||||
knowledge_bases: { by_organization: Record<string, number> }
|
||||
agents: { by_organization: Record<string, number> }
|
||||
}
|
||||
|
||||
interface CountedOrganization {
|
||||
id: string
|
||||
share_count?: number
|
||||
agent_share_count?: number
|
||||
}
|
||||
|
||||
export function applyOrganizationResourceDelta<T extends CountedOrganization>(
|
||||
organizations: T[],
|
||||
resourceCounts: OrganizationResourceCounts | null,
|
||||
organizationId: string,
|
||||
resource: 'knowledge_bases' | 'agents',
|
||||
delta: number
|
||||
): { organizations: T[]; resourceCounts: OrganizationResourceCounts | null } {
|
||||
const field = resource === 'knowledge_bases' ? 'share_count' : 'agent_share_count'
|
||||
const organizationsAfterUpdate = organizations.map(organization => {
|
||||
if (organization.id !== organizationId) return organization
|
||||
return {
|
||||
...organization,
|
||||
[field]: Math.max(0, (organization[field] ?? 0) + delta)
|
||||
}
|
||||
})
|
||||
|
||||
if (!resourceCounts) {
|
||||
return { organizations: organizationsAfterUpdate, resourceCounts }
|
||||
}
|
||||
|
||||
const counts = resourceCounts[resource].by_organization
|
||||
return {
|
||||
organizations: organizationsAfterUpdate,
|
||||
resourceCounts: {
|
||||
...resourceCounts,
|
||||
[resource]: {
|
||||
by_organization: {
|
||||
...counts,
|
||||
[organizationId]: Math.max(0, (counts[organizationId] ?? 0) + delta)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { createCachedResource, createKeyedSnapshotCache } from './resourceCache.ts'
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
let reject!: (reason?: unknown) => void
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res
|
||||
reject = rej
|
||||
})
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
test('concurrent ensure calls share one request; a later ensure issues a new one', async () => {
|
||||
const calls: Array<ReturnType<typeof deferred<number>>> = []
|
||||
const applied: number[] = []
|
||||
const resource = createCachedResource(
|
||||
() => {
|
||||
const d = deferred<number>()
|
||||
calls.push(d)
|
||||
return d.promise
|
||||
},
|
||||
(v) => applied.push(v),
|
||||
)
|
||||
|
||||
const a = resource.ensure()
|
||||
const b = resource.ensure()
|
||||
assert.equal(calls.length, 1, 'mount burst is deduplicated')
|
||||
calls[0].resolve(1)
|
||||
await Promise.all([a, b])
|
||||
assert.deepEqual(applied, [1])
|
||||
assert.equal(resource.isLoaded(), true)
|
||||
|
||||
// No TTL: the next ensure after the first one settled fetches again.
|
||||
const c = resource.ensure()
|
||||
assert.equal(calls.length, 2)
|
||||
calls[1].resolve(2)
|
||||
await c
|
||||
assert.deepEqual(applied, [1, 2])
|
||||
})
|
||||
|
||||
test('invalidate discards the in-flight response and the next ensure waits for a fresh one', async () => {
|
||||
const calls: Array<ReturnType<typeof deferred<number>>> = []
|
||||
const applied: number[] = []
|
||||
const resource = createCachedResource(
|
||||
() => {
|
||||
const d = deferred<number>()
|
||||
calls.push(d)
|
||||
return d.promise
|
||||
},
|
||||
(v) => applied.push(v),
|
||||
)
|
||||
|
||||
const stale = resource.ensure()
|
||||
resource.invalidate()
|
||||
const fresh = resource.ensure()
|
||||
assert.equal(calls.length, 1, 'fresh request is queued behind the in-flight one')
|
||||
calls[0].resolve(1)
|
||||
await stale
|
||||
assert.deepEqual(applied, [], 'stale response is not applied')
|
||||
assert.equal(calls.length, 2)
|
||||
calls[1].resolve(2)
|
||||
await fresh
|
||||
assert.deepEqual(applied, [2])
|
||||
assert.equal(resource.isLoaded(), true)
|
||||
})
|
||||
|
||||
test('markLoaded keeps an older in-flight response from overwriting the replaced snapshot', async () => {
|
||||
const calls: Array<ReturnType<typeof deferred<number>>> = []
|
||||
const applied: number[] = []
|
||||
const resource = createCachedResource(
|
||||
() => {
|
||||
const d = deferred<number>()
|
||||
calls.push(d)
|
||||
return d.promise
|
||||
},
|
||||
(v) => applied.push(v),
|
||||
)
|
||||
|
||||
const inflight = resource.ensure()
|
||||
resource.markLoaded()
|
||||
calls[0].resolve(1)
|
||||
await inflight
|
||||
assert.deepEqual(applied, [])
|
||||
assert.equal(resource.isLoaded(), true)
|
||||
})
|
||||
|
||||
test('keyed snapshot cache loads each key once until invalidated', async () => {
|
||||
let loads = 0
|
||||
const cache = createKeyedSnapshotCache(async (key: string) => {
|
||||
loads += 1
|
||||
return `${key}:${loads}`
|
||||
})
|
||||
|
||||
const [a, b] = await Promise.all([cache.ensure('kb1'), cache.ensure('kb1')])
|
||||
assert.equal(a, 'kb1:1')
|
||||
assert.equal(b, 'kb1:1')
|
||||
assert.equal(await cache.ensure('kb1'), 'kb1:1', 'snapshot reused without a request')
|
||||
assert.equal(loads, 1)
|
||||
|
||||
cache.invalidate('kb1')
|
||||
assert.equal(await cache.ensure('kb1'), 'kb1:2')
|
||||
assert.equal(await cache.ensure('kb1', true), 'kb1:3', 'force bypasses the snapshot')
|
||||
})
|
||||
|
||||
test('keyed snapshot: a response that lands after invalidate is not written back', async () => {
|
||||
const pending = new Map<string, ReturnType<typeof deferred<string>>>()
|
||||
let seq = 0
|
||||
const cache = createKeyedSnapshotCache((key: string) => {
|
||||
const d = deferred<string>()
|
||||
pending.set(`${key}#${++seq}`, d)
|
||||
return d.promise
|
||||
})
|
||||
|
||||
// Sidebar read in flight; the editor saves, invalidates and forces a fresh read.
|
||||
const stale = cache.ensure('kb1')
|
||||
cache.invalidate('kb1')
|
||||
const fresh = cache.ensure('kb1', true)
|
||||
assert.equal(pending.size, 2)
|
||||
|
||||
pending.get('kb1#2')!.resolve('saved')
|
||||
assert.equal(await fresh, 'saved')
|
||||
pending.get('kb1#1')!.resolve('before-save')
|
||||
assert.equal(await stale, 'before-save', 'caller of the stale read still gets its value')
|
||||
|
||||
// The snapshot must be the post-save detail, so a later non-force read is correct.
|
||||
assert.equal(await cache.ensure('kb1'), 'saved')
|
||||
assert.equal(pending.size, 2, 'served from snapshot')
|
||||
})
|
||||
|
||||
test('keyed snapshot: a force read overlapping an in-flight read wins regardless of order', async () => {
|
||||
const pending: Array<ReturnType<typeof deferred<string>>> = []
|
||||
const cache = createKeyedSnapshotCache((_key: string) => {
|
||||
const d = deferred<string>()
|
||||
pending.push(d)
|
||||
return d.promise
|
||||
})
|
||||
|
||||
const first = cache.ensure('kb1')
|
||||
const forced = cache.ensure('kb1', true)
|
||||
pending[1].resolve('fresh')
|
||||
pending[0].resolve('old')
|
||||
await Promise.all([first, forced])
|
||||
assert.equal(await cache.ensure('kb1'), 'fresh')
|
||||
|
||||
// invalidate() without a key must also fence every in-flight read.
|
||||
const late = cache.ensure('kb2')
|
||||
cache.invalidate()
|
||||
pending[2].resolve('kb2-stale')
|
||||
await late
|
||||
const reloaded = cache.ensure('kb2')
|
||||
assert.equal(pending.length, 4, 'kb2 is reloaded rather than served from the stale write')
|
||||
pending[3].resolve('kb2-fresh')
|
||||
assert.equal(await reloaded, 'kb2-fresh')
|
||||
})
|
||||
@@ -0,0 +1,111 @@
|
||||
import { createVersionedRequestCoordinator } from './versionedRequest'
|
||||
|
||||
/**
|
||||
* 空间级资源的读取原语。不设 TTL:
|
||||
*
|
||||
* - `ensure()`:同一资源同一时刻只有一个请求在飞行,并发调用共用它;没有在飞行的
|
||||
* 就发一个新请求。返回的 Promise 在最新数据写入 store 后才 resolve,所以
|
||||
* `await ensure()` 之后读到的一定是本次请求的结果,而不是旧快照。
|
||||
* - `ensure(true)`:写操作之后调用。若此刻有请求在飞行,会在其结束后再发一次,
|
||||
* 保证拿到的是写操作之后的数据。
|
||||
* - `invalidate()`:丢弃快照并让飞行中的旧响应作废;下一次 `ensure()` 必然发新请求。
|
||||
* - `markLoaded()`:调用方已经用别的接口拿到了最新列表并写回 store(如设置页
|
||||
* `replaceModels`),把飞行中的旧请求作废,避免它把旧数据写回来。
|
||||
*
|
||||
* 旧快照仍然留在 store 的 ref 里供页面立即渲染;数据的新鲜度只由「是否刚发过请求」
|
||||
* 和显式失效决定,不再有 60s 内一律读缓存的窗口。
|
||||
*/
|
||||
export interface CachedResource {
|
||||
ensure: (force?: boolean) => Promise<void>
|
||||
invalidate: () => void
|
||||
markLoaded: () => void
|
||||
isLoaded: () => boolean
|
||||
hasInFlightRequest: () => boolean
|
||||
}
|
||||
|
||||
export function createCachedResource<T>(
|
||||
request: () => Promise<T>,
|
||||
apply: (value: T) => void,
|
||||
): CachedResource {
|
||||
let loaded = false
|
||||
// invalidate 之后若仍有旧请求在飞行,下一次 ensure 必须排在它之后重新发,
|
||||
// 否则调用方会 await 到一个结果已被作废的 Promise。
|
||||
let needsFreshRequest = false
|
||||
|
||||
const coordinator = createVersionedRequestCoordinator(request, (value) => {
|
||||
apply(value)
|
||||
loaded = true
|
||||
})
|
||||
|
||||
return {
|
||||
ensure(force = false) {
|
||||
const mustForce = force || needsFreshRequest
|
||||
needsFreshRequest = false
|
||||
return coordinator.fetch(mustForce)
|
||||
},
|
||||
invalidate() {
|
||||
loaded = false
|
||||
coordinator.invalidate()
|
||||
needsFreshRequest = coordinator.hasInFlightRequest()
|
||||
},
|
||||
markLoaded() {
|
||||
coordinator.invalidate()
|
||||
needsFreshRequest = false
|
||||
loaded = true
|
||||
},
|
||||
isLoaded: () => loaded,
|
||||
hasInFlightRequest: () => coordinator.hasInFlightRequest(),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 key 缓存的单条资源(知识库详情、智能体可见知识库等)。
|
||||
* 这类数据不随每次 ensure 重新拉取:拿到过就一直用,直到显式失效。
|
||||
* 调用方在循环里逐条 ensure(如 @ 提及列表补 count),不能每次都打接口。
|
||||
*/
|
||||
export function createKeyedSnapshotCache<T>(load: (key: string) => Promise<T>) {
|
||||
const snapshots = new Map<string, T>()
|
||||
const inflight = new Map<string, { promise: Promise<T>; revision: number }>()
|
||||
// 每个 key 一个代际;invalidate / force 都会推进它。请求返回时代际已变,
|
||||
// 说明中途发生过失效或有更新的请求,这次响应只交给调用方,不落快照。
|
||||
const revisions = new Map<string, number>()
|
||||
|
||||
const bump = (key: string) => {
|
||||
const next = (revisions.get(key) ?? 0) + 1
|
||||
revisions.set(key, next)
|
||||
return next
|
||||
}
|
||||
|
||||
return {
|
||||
async ensure(key: string, force = false): Promise<T> {
|
||||
if (!force && snapshots.has(key)) return snapshots.get(key) as T
|
||||
const existing = inflight.get(key)
|
||||
if (existing && !force) return existing.promise
|
||||
const revision = force ? bump(key) : (revisions.get(key) ?? 0)
|
||||
const promise = (async () => {
|
||||
try {
|
||||
const value = await load(key)
|
||||
const stillCurrent = (revisions.get(key) ?? 0) === revision
|
||||
// 加载失败以 null 表示时不落快照,下次读取会重试。
|
||||
if (stillCurrent && value != null) snapshots.set(key, value)
|
||||
return value
|
||||
} finally {
|
||||
if (inflight.get(key)?.revision === revision) inflight.delete(key)
|
||||
}
|
||||
})()
|
||||
inflight.set(key, { promise, revision })
|
||||
return promise
|
||||
},
|
||||
invalidate(key?: string) {
|
||||
if (key === undefined) {
|
||||
for (const k of new Set([...snapshots.keys(), ...inflight.keys()])) bump(k)
|
||||
snapshots.clear()
|
||||
inflight.clear()
|
||||
return
|
||||
}
|
||||
bump(key)
|
||||
snapshots.delete(key)
|
||||
inflight.delete(key)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { createSequencedRefresh } from './sequencedRefresh.ts'
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
let reject!: (reason?: unknown) => void
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res
|
||||
reject = rej
|
||||
})
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
function setup() {
|
||||
const calls: Array<{ d: ReturnType<typeof deferred<string>>; isCurrent: () => boolean }> = []
|
||||
const applied: string[] = []
|
||||
const sequencer = createSequencedRefresh<boolean>(async (isCurrent) => {
|
||||
const d = deferred<string>()
|
||||
calls.push({ d, isCurrent })
|
||||
const value = await d.promise
|
||||
if (!isCurrent()) return false
|
||||
applied.push(value)
|
||||
return true
|
||||
})
|
||||
return { calls, applied, sequencer }
|
||||
}
|
||||
|
||||
test('share reuses the in-flight request; refresh waits for a request issued after the call', async () => {
|
||||
const { calls, applied, sequencer } = setup()
|
||||
|
||||
const first = sequencer.share()
|
||||
const shared = sequencer.share()
|
||||
assert.equal(calls.length, 1)
|
||||
|
||||
// A write happened while the first request was in flight: its response is
|
||||
// pre-change, so refresh must not settle on it.
|
||||
const refreshed = sequencer.refresh()
|
||||
const refreshedAgain = sequencer.refresh()
|
||||
assert.equal(calls.length, 1, 'the fresh request is queued behind the in-flight one')
|
||||
|
||||
calls[0].d.resolve('before-write')
|
||||
assert.deepEqual([await first, await shared], [true, true])
|
||||
assert.deepEqual(applied, ['before-write'])
|
||||
assert.equal(calls.length, 2, 'queued refresh started after the first settled')
|
||||
|
||||
calls[1].d.resolve('after-write')
|
||||
assert.deepEqual([await refreshed, await refreshedAgain], [true, true])
|
||||
assert.deepEqual(applied, ['before-write', 'after-write'])
|
||||
assert.equal(sequencer.hasInFlightRequest(), false)
|
||||
})
|
||||
|
||||
test('a response that arrives after invalidate (logout) is not applied', async () => {
|
||||
const { calls, applied, sequencer } = setup()
|
||||
|
||||
const late = sequencer.share()
|
||||
sequencer.invalidate()
|
||||
calls[0].d.resolve('stale-session')
|
||||
assert.equal(await late, false)
|
||||
assert.deepEqual(applied, [])
|
||||
|
||||
// The next read is a fresh request under the new revision.
|
||||
const next = sequencer.share()
|
||||
assert.equal(calls.length, 2)
|
||||
calls[1].d.resolve('new-session')
|
||||
assert.equal(await next, true)
|
||||
assert.deepEqual(applied, ['new-session'])
|
||||
})
|
||||
|
||||
test('a queued refresh still runs when the in-flight request rejects', async () => {
|
||||
const { calls, applied, sequencer } = setup()
|
||||
|
||||
const failing = sequencer.share()
|
||||
const refreshed = sequencer.refresh()
|
||||
calls[0].d.reject(new Error('network'))
|
||||
await assert.rejects(failing)
|
||||
assert.equal(calls.length, 2)
|
||||
calls[1].d.resolve('recovered')
|
||||
assert.equal(await refreshed, true)
|
||||
assert.deepEqual(applied, ['recovered'])
|
||||
})
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* 「刷新」语义的请求排序器(/auth/me 这类单例读取用)。
|
||||
*
|
||||
* - `refresh()`:结果必须来自本次调用之后发出的请求。已有请求在飞行时,
|
||||
* 排一个新请求在它之后,多次并发的 refresh 共用同一个排队请求。
|
||||
* - `share()`:只要有请求在飞行就直接复用,否则发一个新的。首屏多个消费者
|
||||
* 同时要同一份数据时用它。
|
||||
* - `invalidate()`:让飞行中的请求作废。`run` 拿到的 `isCurrent()` 在 await 之后
|
||||
* 返回 false,调用方据此跳过落库;登出时用,避免迟到的响应把会话写回来。
|
||||
*/
|
||||
export interface SequencedRefresh<T> {
|
||||
refresh: () => Promise<T>
|
||||
share: () => Promise<T>
|
||||
invalidate: () => void
|
||||
hasInFlightRequest: () => boolean
|
||||
}
|
||||
|
||||
export function createSequencedRefresh<T>(
|
||||
run: (isCurrent: () => boolean) => Promise<T>,
|
||||
): SequencedRefresh<T> {
|
||||
let revision = 0
|
||||
let inflight: Promise<T> | null = null
|
||||
let queued: Promise<T> | null = null
|
||||
|
||||
const start = (): Promise<T> => {
|
||||
const requestRevision = revision
|
||||
const current = run(() => requestRevision === revision).finally(() => {
|
||||
if (inflight === current) inflight = null
|
||||
})
|
||||
inflight = current
|
||||
return current
|
||||
}
|
||||
|
||||
const refresh = (): Promise<T> => {
|
||||
if (!inflight) return start()
|
||||
if (!queued) {
|
||||
const waitingFor = inflight
|
||||
queued = waitingFor.then(
|
||||
() => {
|
||||
queued = null
|
||||
return start()
|
||||
},
|
||||
() => {
|
||||
queued = null
|
||||
return start()
|
||||
},
|
||||
)
|
||||
}
|
||||
return queued
|
||||
}
|
||||
|
||||
return {
|
||||
refresh,
|
||||
share: () => inflight ?? start(),
|
||||
invalidate: () => {
|
||||
revision += 1
|
||||
},
|
||||
hasInFlightRequest: () => inflight !== null,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { reactive, watch } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import { getMessageList } from '@/api/chat/index'
|
||||
import { useAuthStore } from './auth'
|
||||
import {
|
||||
createSessionActivityState,
|
||||
restoreSessionActivity,
|
||||
serializeSessionActivity,
|
||||
type SessionActivity,
|
||||
} from './sessionActivityState'
|
||||
|
||||
const STORAGE_PREFIX = 'weknora:session-activity'
|
||||
|
||||
export const useSessionActivityStore = defineStore('sessionActivity', () => {
|
||||
const entries = reactive<Record<string, SessionActivity>>({})
|
||||
const unread = reactive<Record<string, true>>({})
|
||||
const activity = createSessionActivityState(entries, async sessionId => {
|
||||
const result = await getMessageList({ session_id: sessionId, limit: 20, created_at: '' })
|
||||
return result.data || []
|
||||
}, unread)
|
||||
const auth = useAuthStore()
|
||||
|
||||
const storageKey = () => {
|
||||
const userId = auth.user?.id
|
||||
return userId ? `${STORAGE_PREFIX}:${userId}:${auth.effectiveTenantId ?? ''}` : ''
|
||||
}
|
||||
|
||||
// clear() only resets memory (unmount, account switch); writes happen after
|
||||
// real transitions so an unmount cannot wipe what the next mount restores.
|
||||
function persist() {
|
||||
const key = storageKey()
|
||||
if (!key) return
|
||||
try {
|
||||
localStorage.setItem(key, serializeSessionActivity(entries, unread))
|
||||
} catch {
|
||||
// Storage full or disabled: the in-memory markers still work.
|
||||
}
|
||||
}
|
||||
|
||||
function restore() {
|
||||
const key = storageKey()
|
||||
if (!key) return
|
||||
try {
|
||||
restoreSessionActivity(localStorage.getItem(key), entries, unread)
|
||||
} catch {
|
||||
// Storage disabled.
|
||||
}
|
||||
}
|
||||
|
||||
const persisting = <A extends unknown[], R>(fn: (...args: A) => R) => (...args: A): R => {
|
||||
const result = fn(...args)
|
||||
if (result instanceof Promise) void result.finally(persist)
|
||||
else persist()
|
||||
return result
|
||||
}
|
||||
|
||||
watch(() => [auth.user?.id, auth.effectiveTenantId], () => {
|
||||
activity.clear()
|
||||
restore()
|
||||
}, { flush: 'sync' })
|
||||
restore()
|
||||
|
||||
return {
|
||||
entries,
|
||||
unread,
|
||||
update: persisting(activity.update),
|
||||
detach: persisting(activity.detach),
|
||||
setViewing: persisting(activity.setViewing),
|
||||
dismiss: persisting(activity.dismiss),
|
||||
refresh: persisting(activity.refresh),
|
||||
clear: activity.clear,
|
||||
restore,
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,176 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { reactive } from 'vue'
|
||||
import {
|
||||
createSessionActivityState,
|
||||
restoreSessionActivity,
|
||||
serializeSessionActivity,
|
||||
type SessionActivity,
|
||||
} from './sessionActivityState.ts'
|
||||
|
||||
test('tracks multiple sessions and keeps detached replies until completion', async () => {
|
||||
const entries = reactive<Record<string, SessionActivity>>({})
|
||||
let completed = false
|
||||
const requested: string[] = []
|
||||
const state = createSessionActivityState(entries, async id => {
|
||||
requested.push(id)
|
||||
return [{ id: 'reply-a', role: 'assistant', is_completed: completed }]
|
||||
})
|
||||
state.update('a', true, 'reply-a')
|
||||
state.update('b', true, 'reply-b')
|
||||
state.detach('a')
|
||||
await state.refresh()
|
||||
assert.deepEqual(requested, ['a'])
|
||||
assert.ok(entries.a)
|
||||
assert.ok(entries.b)
|
||||
completed = true
|
||||
await state.refresh()
|
||||
assert.equal(entries.a, undefined)
|
||||
state.update('b', false)
|
||||
assert.deepEqual(Object.keys(entries), [])
|
||||
})
|
||||
|
||||
test('a stale poll cannot clear a reattached stream or a new turn', async () => {
|
||||
const entries = reactive<Record<string, SessionActivity>>({})
|
||||
let resolve!: (messages: any[]) => void
|
||||
const state = createSessionActivityState(entries, () => new Promise(done => { resolve = done }))
|
||||
state.update('a', true, 'old')
|
||||
state.detach('a')
|
||||
const poll = state.refresh()
|
||||
state.update('a', true, 'new')
|
||||
resolve([{ id: 'old', role: 'assistant', is_completed: true }])
|
||||
await poll
|
||||
assert.equal(entries.a?.messageId, 'new')
|
||||
assert.equal(entries.a?.detached, false)
|
||||
})
|
||||
|
||||
test('handles navigation before the assistant message arrives and clears deleted sessions', async () => {
|
||||
const entries = reactive<Record<string, SessionActivity>>({})
|
||||
let messages: any[] = []
|
||||
const state = createSessionActivityState(entries, async () => messages)
|
||||
state.update('a', true)
|
||||
state.detach('a')
|
||||
await state.refresh()
|
||||
assert.ok(entries.a)
|
||||
messages = [{ id: 'reply', role: 'assistant', is_completed: false }]
|
||||
await state.refresh()
|
||||
assert.equal(entries.a?.messageId, 'reply')
|
||||
messages = []
|
||||
await state.refresh()
|
||||
assert.equal(entries.a, undefined)
|
||||
})
|
||||
|
||||
test('transient failures preserve the marker and repeated failures clear it', async () => {
|
||||
const entries = reactive<Record<string, SessionActivity>>({})
|
||||
const state = createSessionActivityState(entries, async () => { throw new Error('offline') })
|
||||
state.update('a', true)
|
||||
state.detach('a')
|
||||
await state.refresh()
|
||||
assert.ok(entries.a)
|
||||
await state.refresh()
|
||||
await state.refresh()
|
||||
assert.equal(entries.a, undefined)
|
||||
})
|
||||
|
||||
test('a detached reply that finishes off-screen stays unread until the session is opened', async () => {
|
||||
const entries = reactive<Record<string, SessionActivity>>({})
|
||||
const unread = reactive<Record<string, true>>({})
|
||||
const state = createSessionActivityState(entries, async () => [
|
||||
{ id: 'reply', role: 'assistant', is_completed: true },
|
||||
], unread)
|
||||
state.update('a', true, 'reply')
|
||||
state.detach('a')
|
||||
state.setViewing('b')
|
||||
await state.refresh()
|
||||
assert.equal(entries.a, undefined)
|
||||
assert.equal(unread.a, true)
|
||||
state.setViewing('a')
|
||||
assert.equal(unread.a, undefined)
|
||||
})
|
||||
|
||||
test('no unread marker for the session in view, a vanished reply, or a new turn', async () => {
|
||||
const entries = reactive<Record<string, SessionActivity>>({})
|
||||
const unread = reactive<Record<string, true>>({})
|
||||
let messages: any[] = [{ id: 'reply', role: 'assistant', is_completed: true }]
|
||||
const state = createSessionActivityState(entries, async () => messages, unread)
|
||||
state.update('a', true, 'reply')
|
||||
state.detach('a')
|
||||
state.setViewing('a')
|
||||
await state.refresh()
|
||||
assert.equal(unread.a, undefined, 'already looking at it')
|
||||
|
||||
state.setViewing('')
|
||||
state.update('b', true, 'gone')
|
||||
state.detach('b')
|
||||
messages = []
|
||||
await state.refresh()
|
||||
assert.equal(unread.b, undefined, 'a reply that disappeared is not news')
|
||||
|
||||
unread.c = true
|
||||
state.update('c', true, 'next')
|
||||
assert.equal(unread.c, undefined, 'a new turn supersedes the old unread')
|
||||
unread.d = true
|
||||
state.clear()
|
||||
assert.deepEqual(Object.keys(unread), [])
|
||||
})
|
||||
|
||||
test('a reload restores unread markers and resumes polling every running turn as detached', async () => {
|
||||
const saved = serializeSessionActivity(
|
||||
{
|
||||
live: { messageId: 'r1', detached: false, failures: 0 },
|
||||
away: { messageId: 'r2', detached: true, failures: 2 },
|
||||
},
|
||||
{ done: true },
|
||||
)
|
||||
const entries = reactive<Record<string, SessionActivity>>({})
|
||||
const unread = reactive<Record<string, true>>({})
|
||||
restoreSessionActivity(saved, entries, unread)
|
||||
assert.deepEqual({ ...entries }, {
|
||||
live: { messageId: 'r1', detached: true, failures: 0 },
|
||||
away: { messageId: 'r2', detached: true, failures: 0 },
|
||||
})
|
||||
assert.deepEqual(Object.keys(unread), ['done'])
|
||||
|
||||
const state = createSessionActivityState(entries, async id => [
|
||||
{ id: id === 'live' ? 'r1' : 'r2', role: 'assistant', is_completed: true },
|
||||
], unread)
|
||||
await state.refresh()
|
||||
assert.deepEqual(Object.keys(unread).sort(), ['away', 'done', 'live'])
|
||||
})
|
||||
|
||||
test('restoring ignores corrupt storage and never overrides a live entry', () => {
|
||||
const entries = reactive<Record<string, SessionActivity>>({
|
||||
a: { messageId: 'new', detached: false, failures: 0 },
|
||||
})
|
||||
const unread = reactive<Record<string, true>>({})
|
||||
restoreSessionActivity('{not json', entries, unread)
|
||||
restoreSessionActivity(null, entries, unread)
|
||||
restoreSessionActivity(JSON.stringify({ running: { a: 'old' }, unread: [1, '', 'b'] }), entries, unread)
|
||||
assert.equal(entries.a.messageId, 'new')
|
||||
assert.equal(entries.a.detached, false)
|
||||
assert.deepEqual(Object.keys(unread), ['b'])
|
||||
})
|
||||
|
||||
test('dismissing a removed session drops both markers', () => {
|
||||
const entries = reactive<Record<string, SessionActivity>>({})
|
||||
const unread = reactive<Record<string, true>>({ a: true })
|
||||
const state = createSessionActivityState(entries, async () => [], unread)
|
||||
state.update('a', true, 'r')
|
||||
unread.a = true
|
||||
state.dismiss('a')
|
||||
assert.equal(entries.a, undefined)
|
||||
assert.equal(unread.a, undefined)
|
||||
})
|
||||
|
||||
test('clearing activity while a poll is in flight cannot restore old account state', async () => {
|
||||
const entries = reactive<Record<string, SessionActivity>>({})
|
||||
let resolve!: (messages: any[]) => void
|
||||
const state = createSessionActivityState(entries, () => new Promise(done => { resolve = done }))
|
||||
state.update('a', true, 'reply')
|
||||
state.detach('a')
|
||||
const poll = state.refresh()
|
||||
state.clear()
|
||||
resolve([{ id: 'reply', role: 'assistant', is_completed: false }])
|
||||
await poll
|
||||
assert.deepEqual(Object.keys(entries), [])
|
||||
})
|
||||
@@ -0,0 +1,132 @@
|
||||
export interface SessionActivity {
|
||||
messageId: string
|
||||
detached: boolean
|
||||
failures: number
|
||||
}
|
||||
|
||||
interface ActivityMessage {
|
||||
id: string
|
||||
role: string
|
||||
is_completed: boolean
|
||||
}
|
||||
|
||||
interface PersistedSessionActivity {
|
||||
running: Record<string, string>
|
||||
unread: string[]
|
||||
}
|
||||
|
||||
const MAX_PERSISTED_UNREAD = 100
|
||||
|
||||
// A reload drops every live stream, so whatever was running is saved as
|
||||
// detached: polling then decides whether it finished while the page was gone.
|
||||
export function serializeSessionActivity(
|
||||
entries: Record<string, SessionActivity>,
|
||||
unread: Record<string, true>,
|
||||
): string {
|
||||
const running: Record<string, string> = {}
|
||||
for (const [sessionId, entry] of Object.entries(entries)) running[sessionId] = entry.messageId
|
||||
const data: PersistedSessionActivity = { running, unread: Object.keys(unread).slice(-MAX_PERSISTED_UNREAD) }
|
||||
return JSON.stringify(data)
|
||||
}
|
||||
|
||||
export function restoreSessionActivity(
|
||||
raw: string | null,
|
||||
entries: Record<string, SessionActivity>,
|
||||
unread: Record<string, true>,
|
||||
) {
|
||||
if (!raw) return
|
||||
let data: Partial<PersistedSessionActivity>
|
||||
try {
|
||||
data = JSON.parse(raw)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
if (data.running && typeof data.running === 'object') {
|
||||
for (const [sessionId, messageId] of Object.entries(data.running)) {
|
||||
if (sessionId && !entries[sessionId]) {
|
||||
entries[sessionId] = { messageId: typeof messageId === 'string' ? messageId : '', detached: true, failures: 0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Array.isArray(data.unread)) {
|
||||
for (const sessionId of data.unread) {
|
||||
if (typeof sessionId === 'string' && sessionId) unread[sessionId] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Entries are replaced on every local update so stale polling responses cannot
|
||||
// clear a newer turn or a stream that has since reattached.
|
||||
export function createSessionActivityState(
|
||||
entries: Record<string, SessionActivity>,
|
||||
fetchMessages: (sessionId: string) => Promise<ActivityMessage[]>,
|
||||
unread: Record<string, true> = {},
|
||||
) {
|
||||
const pending = new Set<string>()
|
||||
let viewingSessionId = ''
|
||||
|
||||
function update(sessionId: string, running: boolean, messageId = '') {
|
||||
if (!sessionId) return
|
||||
if (running) {
|
||||
entries[sessionId] = { messageId, detached: false, failures: 0 }
|
||||
delete unread[sessionId]
|
||||
} else {
|
||||
delete entries[sessionId]
|
||||
}
|
||||
}
|
||||
|
||||
function detach(sessionId: string) {
|
||||
const entry = entries[sessionId]
|
||||
if (entry) entries[sessionId] = { ...entry, detached: true }
|
||||
}
|
||||
|
||||
function setViewing(sessionId: string) {
|
||||
viewingSessionId = sessionId
|
||||
if (sessionId) delete unread[sessionId]
|
||||
}
|
||||
|
||||
function dismiss(sessionId: string) {
|
||||
delete entries[sessionId]
|
||||
delete unread[sessionId]
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
await Promise.all(Object.entries(entries).map(async ([sessionId, entry]) => {
|
||||
if (!entry.detached || pending.has(sessionId)) return
|
||||
pending.add(sessionId)
|
||||
try {
|
||||
const messages = await fetchMessages(sessionId)
|
||||
if (entries[sessionId] !== entry) return
|
||||
const message = entry.messageId
|
||||
? messages.find(message => message.id === entry.messageId)
|
||||
: messages.find(message => message.role === 'assistant' && !message.is_completed)
|
||||
if (message?.is_completed) {
|
||||
delete entries[sessionId]
|
||||
if (sessionId !== viewingSessionId) unread[sessionId] = true
|
||||
} else if (!message && entry.messageId) {
|
||||
delete entries[sessionId]
|
||||
} else if (message) {
|
||||
entries[sessionId] = { messageId: message.id, detached: true, failures: 0 }
|
||||
} else if (++entry.failures >= 3) {
|
||||
// A request abandoned before creating its assistant message.
|
||||
delete entries[sessionId]
|
||||
}
|
||||
} catch (error) {
|
||||
if (entries[sessionId] !== entry) return
|
||||
const status = (error as { status?: number })?.status
|
||||
if (status === 403 || status === 404 || ++entry.failures >= 3) {
|
||||
delete entries[sessionId]
|
||||
}
|
||||
} finally {
|
||||
pending.delete(sessionId)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
function clear() {
|
||||
for (const sessionId of Object.keys(entries)) delete entries[sessionId]
|
||||
for (const sessionId of Object.keys(unread)) delete unread[sessionId]
|
||||
}
|
||||
|
||||
return { update, detach, setViewing, dismiss, refresh, clear }
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { after, before, beforeEach, test } from 'node:test'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { createServer, type ViteDevServer } from 'vite'
|
||||
import { createPinia } from 'pinia'
|
||||
import type { SessionLastRequestStatePayload } from './settings'
|
||||
|
||||
let server: ViteDevServer
|
||||
let useSettingsStore: typeof import('./settings').useSettingsStore
|
||||
const savedStorage = Object.getOwnPropertyDescriptor(globalThis, 'localStorage')
|
||||
const items = new Map<string, string>()
|
||||
|
||||
before(async () => {
|
||||
Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: {
|
||||
getItem: (key: string) => items.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => items.set(key, value),
|
||||
removeItem: (key: string) => items.delete(key),
|
||||
} })
|
||||
server = await createServer({
|
||||
configFile: false,
|
||||
plugins: [{ name: 'offline-store-test', enforce: 'pre',
|
||||
resolveId(id) { if (id.endsWith('/utils/request')) return '\0offline-request' },
|
||||
load(id) { if (id === '\0offline-request') return 'const request = () => { throw new Error("Unexpected network request") }; export { request as get, request as post, request as put, request as del };' },
|
||||
}],
|
||||
optimizeDeps: { noDiscovery: true, entries: [] },
|
||||
resolve: { alias: { '@': fileURLToPath(new URL('../', import.meta.url)) } },
|
||||
server: { middlewareMode: true, hmr: false }, appType: 'custom',
|
||||
})
|
||||
;({ useSettingsStore } = await server.ssrLoadModule('/src/stores/settings.ts'))
|
||||
})
|
||||
|
||||
beforeEach(() => items.clear())
|
||||
|
||||
after(async () => {
|
||||
await server?.close()
|
||||
if (savedStorage) Object.defineProperty(globalThis, 'localStorage', savedStorage)
|
||||
else Reflect.deleteProperty(globalThis, 'localStorage')
|
||||
})
|
||||
|
||||
function selectDefaults(store: ReturnType<typeof useSettingsStore>) {
|
||||
store.settings.selectedFiles = ['default-file']
|
||||
store.settings.selectedFileKbMap = { 'default-file': 'default-kb' }
|
||||
store.settings.selectedTags = [{ id: 'default-tag', name: 'Default tag', kbId: 'default-kb' }]
|
||||
store.settings.selectedMCPServices = ['default-mcp']
|
||||
store.settings.selectedSkills = ['default-skill']
|
||||
store.selectKnowledgeBases(['default-kb'])
|
||||
}
|
||||
|
||||
const emptySelections: SessionLastRequestStatePayload = {
|
||||
knowledge_base_ids: [], knowledge_ids: [], tag_ids: [], mcp_service_ids: [], skill_names: [],
|
||||
}
|
||||
|
||||
for (const state of [{ agent_enabled: true, knowledge_base_ids: [] }, emptySelections]) {
|
||||
test(`session hydration clears stale file, tag, and tool selections when saved lists are ${'knowledge_ids' in state ? 'empty' : 'omitted'}`, () => {
|
||||
const store = useSettingsStore(createPinia())
|
||||
selectDefaults(store)
|
||||
const storedDefaults = items.get('WeKnora_settings')
|
||||
|
||||
store.hydrateSessionInputState(state)
|
||||
|
||||
assert.deepEqual(store.getSelectedKnowledgeBases(), [])
|
||||
assert.deepEqual(store.getSelectedFiles(), [])
|
||||
assert.deepEqual(store.settings.selectedFileKbMap, {})
|
||||
assert.deepEqual(store.settings.selectedTags, [])
|
||||
assert.deepEqual(store.settings.selectedMCPServices, [])
|
||||
assert.deepEqual(store.settings.selectedSkills, [])
|
||||
assert.deepEqual(store.getSuggestedQuestionsParams(), {
|
||||
knowledge_base_ids: undefined, knowledge_ids: undefined, tag_scopes: undefined, limit: undefined,
|
||||
})
|
||||
assert.equal(items.get('WeKnora_settings'), storedDefaults, 'hydration must not overwrite browser defaults')
|
||||
store.restoreDefaultsIfSnapshotted()
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(store.settings)), JSON.parse(storedDefaults!))
|
||||
})
|
||||
}
|
||||
|
||||
test('switching back to a session without mentions clears file and tool selections from browser defaults', () => {
|
||||
const store = useSettingsStore(createPinia())
|
||||
selectDefaults(store)
|
||||
store.hydrateSessionInputState({ knowledge_base_ids: [] })
|
||||
|
||||
// The chat route restores defaults before loading every other session.
|
||||
store.restoreDefaultsIfSnapshotted()
|
||||
store.hydrateSessionInputState({
|
||||
knowledge_ids: ['other-session-file'], mcp_service_ids: ['other-session-mcp'], skill_names: ['other-session-skill'],
|
||||
})
|
||||
assert.deepEqual(store.getSelectedFiles(), ['other-session-file'])
|
||||
assert.deepEqual(store.settings.selectedMCPServices, ['other-session-mcp'])
|
||||
assert.deepEqual(store.settings.selectedSkills, ['other-session-skill'])
|
||||
store.restoreDefaultsIfSnapshotted()
|
||||
store.hydrateSessionInputState({ knowledge_base_ids: [] })
|
||||
|
||||
assert.deepEqual(store.getSelectedFiles(), [])
|
||||
assert.deepEqual(store.settings.selectedTags, [])
|
||||
assert.deepEqual(store.settings.selectedMCPServices, [])
|
||||
assert.deepEqual(store.settings.selectedSkills, [])
|
||||
store.restoreDefaultsIfSnapshotted()
|
||||
assert.deepEqual(store.getSelectedFiles(), ['default-file'])
|
||||
assert.deepEqual(store.settings.selectedTags, [{ id: 'default-tag', name: 'Default tag', kbId: 'default-kb' }])
|
||||
assert.deepEqual(store.settings.selectedMCPServices, ['default-mcp'])
|
||||
assert.deepEqual(store.settings.selectedSkills, ['default-skill'])
|
||||
})
|
||||
|
||||
test('session hydration copies explicit selections and retains only selected files in the KB map', () => {
|
||||
const store = useSettingsStore(createPinia())
|
||||
selectDefaults(store)
|
||||
const state = {
|
||||
knowledge_base_ids: ['session-kb'], knowledge_ids: ['session-file', 'default-file'],
|
||||
mcp_service_ids: ['session-mcp'], skill_names: ['session-skill'],
|
||||
}
|
||||
store.settings.selectedFileKbMap['unselected-file'] = 'another-kb'
|
||||
|
||||
store.hydrateSessionInputState(state)
|
||||
assert.deepEqual(store.getSelectedKnowledgeBases(), ['session-kb'])
|
||||
assert.deepEqual(store.getSelectedFiles(), ['session-file', 'default-file'])
|
||||
assert.deepEqual(store.settings.selectedFileKbMap, { 'default-file': 'default-kb' })
|
||||
assert.deepEqual(store.settings.selectedMCPServices, ['session-mcp'])
|
||||
assert.deepEqual(store.settings.selectedSkills, ['session-skill'])
|
||||
store.settings.selectedKnowledgeBases.push('another-kb')
|
||||
store.settings.selectedFiles.push('another-file')
|
||||
store.settings.selectedMCPServices.push('another-mcp')
|
||||
store.settings.selectedSkills.push('another-skill')
|
||||
|
||||
assert.deepEqual(state.knowledge_base_ids, ['session-kb'])
|
||||
assert.deepEqual(state.knowledge_ids, ['session-file', 'default-file'])
|
||||
assert.deepEqual(state.mcp_service_ids, ['session-mcp'])
|
||||
assert.deepEqual(state.skill_names, ['session-skill'])
|
||||
store.restoreDefaultsIfSnapshotted()
|
||||
assert.deepEqual(store.getSelectedKnowledgeBases(), ['default-kb'])
|
||||
})
|
||||
|
||||
test('session hydration restores tags and tool selections from mentions when ID lists are omitted', () => {
|
||||
const store = useSettingsStore(createPinia())
|
||||
selectDefaults(store)
|
||||
store.hydrateSessionInputState({
|
||||
knowledge_base_ids: ['session-kb'],
|
||||
mentioned_items: [
|
||||
{ id: 'tag', type: 'tag', name: 'Saved tag', kb_id: 'session-kb', kb_name: 'Saved KB' },
|
||||
{ id: 'mcp', type: 'mcp' },
|
||||
{ id: 'skill-id', type: 'skill', skill_name: 'saved-skill' },
|
||||
],
|
||||
})
|
||||
|
||||
assert.deepEqual(store.settings.selectedTags, [{ id: 'tag', name: 'Saved tag', kbId: 'session-kb', kbName: 'Saved KB' }])
|
||||
assert.deepEqual(store.settings.selectedMCPServices, ['mcp'])
|
||||
assert.deepEqual(store.settings.selectedSkills, ['saved-skill'])
|
||||
})
|
||||
|
||||
test('explicit empty ID lists override stale tag and tool mentions', () => {
|
||||
const store = useSettingsStore(createPinia())
|
||||
selectDefaults(store)
|
||||
store.hydrateSessionInputState({
|
||||
...emptySelections,
|
||||
mentioned_items: [
|
||||
{ id: 'tag', type: 'tag', kb_id: 'old-kb' },
|
||||
{ id: 'mcp', type: 'mcp' },
|
||||
{ id: 'skill', type: 'skill' },
|
||||
],
|
||||
})
|
||||
|
||||
assert.deepEqual(store.settings.selectedTags, [])
|
||||
assert.deepEqual(store.settings.selectedMCPServices, [])
|
||||
assert.deepEqual(store.settings.selectedSkills, [])
|
||||
})
|
||||
|
||||
test('explicit tag IDs filter mentions and preserve the single-KB fallback for missing metadata', () => {
|
||||
const store = useSettingsStore(createPinia())
|
||||
store.hydrateSessionInputState({
|
||||
knowledge_base_ids: ['session-kb'], tag_ids: ['selected-tag', 'orphan-tag'],
|
||||
mentioned_items: [
|
||||
{ id: 'selected-tag', type: 'tag', name: 'Saved tag', kb_id: 'session-kb' },
|
||||
{ id: 'unselected-tag', type: 'tag', kb_id: 'other-kb' },
|
||||
],
|
||||
})
|
||||
|
||||
assert.deepEqual(store.settings.selectedTags, [
|
||||
{ id: 'selected-tag', name: 'Saved tag', kbId: 'session-kb', kbName: undefined },
|
||||
{ id: 'orphan-tag', name: 'orphan-tag', kbId: 'session-kb', kbName: undefined },
|
||||
])
|
||||
})
|
||||
|
||||
test('missing session state and first-send hydration preserve the current draft selections', () => {
|
||||
const store = useSettingsStore(createPinia())
|
||||
selectDefaults(store)
|
||||
const draft = JSON.stringify(store.settings)
|
||||
|
||||
store.hydrateSessionInputState(null)
|
||||
store.hydrateSessionInputState(undefined)
|
||||
store.hydrateSessionInputState({ agent_enabled: true }, true)
|
||||
|
||||
assert.equal(JSON.stringify(store.settings), draft)
|
||||
assert.equal(store._defaultsSnapshot, null)
|
||||
})
|
||||
@@ -0,0 +1,641 @@
|
||||
import { defineStore } from "pinia";
|
||||
import { nextTick } from "vue";
|
||||
import { BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from "@/api/agent";
|
||||
import { getApiBaseUrl } from "@/utils/api-base";
|
||||
import { isAgentStreamAgentId } from "@/utils/agent-mode";
|
||||
import { loadAndReconcileSettings } from "@/stores/settingsStorage";
|
||||
import { isReasoningLevel, type ReasoningLevel } from "@/utils/reasoningEffort";
|
||||
|
||||
// 定义设置接口
|
||||
interface Settings {
|
||||
endpoint: string;
|
||||
apiKey: string;
|
||||
knowledgeBaseId: string;
|
||||
isAgentEnabled: boolean;
|
||||
agentConfig: AgentConfig;
|
||||
selectedKnowledgeBases: string[]; // 当前选中的知识库ID列表
|
||||
selectedFiles: string[]; // 当前选中的文件ID列表
|
||||
selectedFileKbMap: Record<string, string>; // 文件ID -> 知识库ID,用于刷新后带 kb_id 拉取共享知识库文件
|
||||
selectedTags: Array<{ id: string; name: string; kbId: string; kbName?: string }>;
|
||||
selectedMCPServices: string[];
|
||||
selectedSkills: string[];
|
||||
selectedTools?: string[];
|
||||
modelConfig: ModelConfig; // 模型配置
|
||||
ollamaConfig: OllamaConfig; // Ollama配置
|
||||
localBrowserEnabled: boolean; // Explicit source preference; composer activates it only while the extension is online
|
||||
webSearchEnabled: boolean; // 网络搜索是否启用
|
||||
conversationModels: ConversationModels;
|
||||
selectedAgentId: string; // 当前选中的智能体ID
|
||||
selectedAgentSourceTenantId: string | null; // 当使用共享智能体时,来源空间 ID(用于后端 model/KB/MCP 解析)
|
||||
autoCheckUpdate?: boolean; // 是否自动检查并下载更新
|
||||
}
|
||||
|
||||
// Agent 配置接口
|
||||
interface AgentConfig {
|
||||
maxIterations: number;
|
||||
temperature: number;
|
||||
allowedTools: string[];
|
||||
system_prompt?: string; // Unified system prompt (uses {{web_search_status}} placeholder)
|
||||
}
|
||||
|
||||
interface ConversationModels {
|
||||
summaryModelId: string;
|
||||
rerankModelId: string;
|
||||
selectedChatModelId: string; // 用户当前选择的对话模型ID
|
||||
}
|
||||
|
||||
// 单个模型项接口
|
||||
interface ModelItem {
|
||||
id: string; // 唯一ID
|
||||
name: string; // 显示名称
|
||||
source: 'local' | 'remote'; // 模型来源
|
||||
modelName: string; // 模型标识
|
||||
baseUrl?: string; // 远程API URL
|
||||
apiKey?: string; // 远程API Key
|
||||
dimension?: number; // Embedding专用:向量维度
|
||||
interfaceType?: 'ollama' | 'openai'; // VLLM专用:接口类型
|
||||
isDefault?: boolean; // 是否为默认模型
|
||||
}
|
||||
|
||||
// 模型配置接口 - 支持多模型
|
||||
interface ModelConfig {
|
||||
chatModels: ModelItem[];
|
||||
embeddingModels: ModelItem[];
|
||||
rerankModels: ModelItem[];
|
||||
vllmModels: ModelItem[]; // VLLM视觉模型
|
||||
}
|
||||
|
||||
// Ollama 配置接口
|
||||
interface OllamaConfig {
|
||||
baseUrl: string; // Ollama 服务地址
|
||||
enabled: boolean; // 是否启用
|
||||
}
|
||||
|
||||
// 默认设置
|
||||
const defaultSettings: Settings = {
|
||||
endpoint: getApiBaseUrl(),
|
||||
apiKey: "",
|
||||
knowledgeBaseId: "",
|
||||
isAgentEnabled: false,
|
||||
agentConfig: {
|
||||
maxIterations: 5,
|
||||
temperature: 0.7,
|
||||
allowedTools: [], // 默认为空,需要通过 API 从后端加载
|
||||
system_prompt: "",
|
||||
},
|
||||
selectedKnowledgeBases: [], // 默认为空数组
|
||||
selectedFiles: [], // 默认为空数组
|
||||
selectedFileKbMap: {}, // 文件ID -> 知识库ID
|
||||
selectedTags: [],
|
||||
selectedMCPServices: [],
|
||||
selectedSkills: [],
|
||||
modelConfig: {
|
||||
chatModels: [],
|
||||
embeddingModels: [],
|
||||
rerankModels: [],
|
||||
vllmModels: []
|
||||
},
|
||||
ollamaConfig: {
|
||||
baseUrl: "http://localhost:11434",
|
||||
enabled: true
|
||||
},
|
||||
localBrowserEnabled: false,
|
||||
webSearchEnabled: false, // 默认关闭网络搜索
|
||||
conversationModels: {
|
||||
summaryModelId: "",
|
||||
rerankModelId: "",
|
||||
selectedChatModelId: "", // 用户当前选择的对话模型ID
|
||||
},
|
||||
selectedAgentId: BUILTIN_QUICK_ANSWER_ID, // 默认选中快速问答模式
|
||||
selectedAgentSourceTenantId: null as string | null, // 共享智能体来源空间 ID
|
||||
autoCheckUpdate: true,
|
||||
};
|
||||
|
||||
export const useSettingsStore = defineStore("settings", {
|
||||
state: () => ({
|
||||
// 从本地存储加载设置,如果没有则使用默认设置
|
||||
settings: loadAndReconcileSettings(defaultSettings),
|
||||
// 进入会话时拍下"全局默认"的快照;离开会话时还原。非持久化字段:
|
||||
// 刷新页面相当于重新走"进入会话"流程,自然会重新拍快照。
|
||||
_defaultsSnapshot: null as Settings | null,
|
||||
/** 正在从 session.last_request_state 恢复输入栏,避免 agent 切换 watch 覆盖 KB 选择 */
|
||||
_isApplyingSessionState: false,
|
||||
// Session-only preference: never written into global settings/localStorage.
|
||||
reasoningEffortOverride: '' as ReasoningLevel | '',
|
||||
}),
|
||||
|
||||
getters: {
|
||||
// Agent 是否启用
|
||||
isAgentEnabled: (state) => state.settings.isAgentEnabled || false,
|
||||
|
||||
// 当前是否为内置快速问答(优先看 selectedAgentId,避免与 isAgentEnabled 漂移)
|
||||
isQuickAnswerMode: (state) =>
|
||||
(state.settings.selectedAgentId || BUILTIN_QUICK_ANSWER_ID) === BUILTIN_QUICK_ANSWER_ID,
|
||||
|
||||
// 是否走 Agent 流式管线(智能推理 / 自定义 Agent);快速问答走 RAG 管线
|
||||
isAgentStreamMode: (state) =>
|
||||
isAgentStreamAgentId(
|
||||
state.settings.selectedAgentId,
|
||||
state.settings.isAgentEnabled || false,
|
||||
),
|
||||
|
||||
// Agent 是否就绪(配置完整)
|
||||
// 需要满足:1) 配置了允许的工具 2) 设置了对话模型 3) 设置了重排模型
|
||||
isAgentReady: (state) => {
|
||||
const config = state.settings.agentConfig || defaultSettings.agentConfig
|
||||
const models = state.settings.conversationModels || defaultSettings.conversationModels
|
||||
return Boolean(
|
||||
config.allowedTools && config.allowedTools.length > 0 &&
|
||||
models.summaryModelId && models.summaryModelId.trim() !== '' &&
|
||||
models.rerankModelId && models.rerankModelId.trim() !== ''
|
||||
)
|
||||
},
|
||||
|
||||
// 普通模式(快速回答)是否就绪
|
||||
// 需要满足:1) 设置了对话模型 2) 设置了重排模型
|
||||
isNormalModeReady: (state) => {
|
||||
const models = state.settings.conversationModels || defaultSettings.conversationModels
|
||||
return Boolean(
|
||||
models.summaryModelId && models.summaryModelId.trim() !== '' &&
|
||||
models.rerankModelId && models.rerankModelId.trim() !== ''
|
||||
)
|
||||
},
|
||||
|
||||
// 获取 Agent 配置
|
||||
agentConfig: (state) => state.settings.agentConfig || defaultSettings.agentConfig,
|
||||
|
||||
conversationModels: (state) => state.settings.conversationModels || defaultSettings.conversationModels,
|
||||
|
||||
// 获取模型配置
|
||||
modelConfig: (state) => state.settings.modelConfig || defaultSettings.modelConfig,
|
||||
|
||||
// 本轮查询来源
|
||||
isLocalBrowserEnabled: (state) => state.settings.localBrowserEnabled === true,
|
||||
isWebSearchEnabled: (state) => state.settings.webSearchEnabled || false,
|
||||
|
||||
// 是否自动检查并下载更新
|
||||
isAutoCheckUpdateEnabled: (state) => state.settings.autoCheckUpdate ?? true,
|
||||
|
||||
// 当前选中的智能体ID
|
||||
selectedAgentId: (state) => state.settings.selectedAgentId || BUILTIN_QUICK_ANSWER_ID,
|
||||
// 共享智能体来源空间 ID(可选)
|
||||
selectedAgentSourceTenantId: (state) => state.settings.selectedAgentSourceTenantId ?? null,
|
||||
},
|
||||
|
||||
actions: {
|
||||
// 保存设置
|
||||
saveSettings(settings: Settings) {
|
||||
this.settings = { ...settings };
|
||||
// 保存到localStorage
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
// 获取设置
|
||||
getSettings(): Settings {
|
||||
return this.settings;
|
||||
},
|
||||
|
||||
// 获取API端点
|
||||
getEndpoint(): string {
|
||||
return this.settings.endpoint || defaultSettings.endpoint;
|
||||
},
|
||||
|
||||
// 获取API Key
|
||||
getApiKey(): string {
|
||||
return this.settings.apiKey;
|
||||
},
|
||||
|
||||
// 获取知识库ID
|
||||
getKnowledgeBaseId(): string {
|
||||
return this.settings.knowledgeBaseId;
|
||||
},
|
||||
|
||||
// 启用/禁用 Agent
|
||||
toggleAgent(enabled: boolean) {
|
||||
this.settings.isAgentEnabled = enabled;
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
// 更新 Agent 配置
|
||||
updateAgentConfig(config: Partial<AgentConfig>) {
|
||||
this.settings.agentConfig = { ...this.settings.agentConfig, ...config };
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
updateConversationModels(models: Partial<ConversationModels>) {
|
||||
const current = this.settings.conversationModels || defaultSettings.conversationModels;
|
||||
this.settings.conversationModels = { ...current, ...models };
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
// 更新模型配置
|
||||
updateModelConfig(config: Partial<ModelConfig>) {
|
||||
this.settings.modelConfig = { ...this.settings.modelConfig, ...config };
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
// 添加模型
|
||||
addModel(type: 'chat' | 'embedding' | 'rerank' | 'vllm', model: ModelItem) {
|
||||
const key = `${type}Models` as keyof ModelConfig;
|
||||
const models = [...this.settings.modelConfig[key]] as ModelItem[];
|
||||
// 如果设为默认,取消其他模型的默认状态
|
||||
if (model.isDefault) {
|
||||
models.forEach(m => m.isDefault = false);
|
||||
}
|
||||
// 如果是第一个模型,自动设为默认
|
||||
if (models.length === 0) {
|
||||
model.isDefault = true;
|
||||
}
|
||||
models.push(model);
|
||||
this.settings.modelConfig[key] = models as any;
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
// 更新模型
|
||||
updateModel(type: 'chat' | 'embedding' | 'rerank' | 'vllm', modelId: string, updates: Partial<ModelItem>) {
|
||||
const key = `${type}Models` as keyof ModelConfig;
|
||||
const models = [...this.settings.modelConfig[key]] as ModelItem[];
|
||||
const index = models.findIndex(m => m.id === modelId);
|
||||
if (index !== -1) {
|
||||
// 如果要设为默认,取消其他模型的默认状态
|
||||
if (updates.isDefault) {
|
||||
models.forEach(m => m.isDefault = false);
|
||||
}
|
||||
models[index] = { ...models[index], ...updates };
|
||||
this.settings.modelConfig[key] = models as any;
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
}
|
||||
},
|
||||
|
||||
// 删除模型
|
||||
deleteModel(type: 'chat' | 'embedding' | 'rerank' | 'vllm', modelId: string) {
|
||||
const key = `${type}Models` as keyof ModelConfig;
|
||||
let models = [...this.settings.modelConfig[key]] as ModelItem[];
|
||||
const deletedModel = models.find(m => m.id === modelId);
|
||||
models = models.filter(m => m.id !== modelId);
|
||||
// 如果删除的是默认模型,设置第一个为默认
|
||||
if (deletedModel?.isDefault && models.length > 0) {
|
||||
models[0].isDefault = true;
|
||||
}
|
||||
this.settings.modelConfig[key] = models as any;
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
// 设置默认模型
|
||||
setDefaultModel(type: 'chat' | 'embedding' | 'rerank' | 'vllm', modelId: string) {
|
||||
const key = `${type}Models` as keyof ModelConfig;
|
||||
const models = [...this.settings.modelConfig[key]] as ModelItem[];
|
||||
models.forEach(m => m.isDefault = (m.id === modelId));
|
||||
this.settings.modelConfig[key] = models as any;
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
// 更新 Ollama 配置
|
||||
updateOllamaConfig(config: Partial<OllamaConfig>) {
|
||||
this.settings.ollamaConfig = { ...this.settings.ollamaConfig, ...config };
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
// 选择知识库(替换整个列表)
|
||||
selectKnowledgeBases(kbIds: string[]) {
|
||||
this.settings.selectedKnowledgeBases = kbIds;
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
// 添加单个知识库
|
||||
addKnowledgeBase(kbId: string) {
|
||||
if (!this.settings.selectedKnowledgeBases.includes(kbId)) {
|
||||
this.settings.selectedKnowledgeBases.push(kbId);
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
}
|
||||
},
|
||||
|
||||
// 移除单个知识库
|
||||
removeKnowledgeBase(kbId: string) {
|
||||
this.settings.selectedKnowledgeBases =
|
||||
this.settings.selectedKnowledgeBases.filter((id: string) => id !== kbId);
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
// 清空知识库选择
|
||||
clearKnowledgeBases() {
|
||||
this.settings.selectedKnowledgeBases = [];
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
// 获取选中的知识库列表
|
||||
getSelectedKnowledgeBases(): string[] {
|
||||
return this.settings.selectedKnowledgeBases || [];
|
||||
},
|
||||
|
||||
// 本机浏览器与联网搜索可独立选择。
|
||||
toggleLocalBrowser(enabled: boolean) {
|
||||
this.settings.localBrowserEnabled = enabled;
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
toggleWebSearch(enabled: boolean) {
|
||||
this.settings.webSearchEnabled = enabled;
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
// 启用/禁用自动检查更新
|
||||
toggleAutoCheckUpdate(enabled: boolean) {
|
||||
this.settings.autoCheckUpdate = enabled;
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
// File selection actions
|
||||
addFile(fileId: string) {
|
||||
if (!this.settings.selectedFiles) this.settings.selectedFiles = [];
|
||||
if (!this.settings.selectedFiles.includes(fileId)) {
|
||||
this.settings.selectedFiles.push(fileId);
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
}
|
||||
},
|
||||
|
||||
removeFile(fileId: string) {
|
||||
if (!this.settings.selectedFiles) return;
|
||||
this.settings.selectedFiles = this.settings.selectedFiles.filter((id: string) => id !== fileId);
|
||||
if (this.settings.selectedFileKbMap) delete this.settings.selectedFileKbMap[fileId];
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
clearFiles() {
|
||||
this.settings.selectedFiles = [];
|
||||
this.settings.selectedFileKbMap = {};
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
addTag(tag: { id: string; name: string; kbId: string; kbName?: string }) {
|
||||
if (!this.settings.selectedTags) this.settings.selectedTags = [];
|
||||
if (!this.settings.selectedTags.some(t => t.id === tag.id && t.kbId === tag.kbId)) {
|
||||
this.settings.selectedTags.push(tag);
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
}
|
||||
},
|
||||
|
||||
removeTag(tagId: string, kbId?: string) {
|
||||
if (!this.settings.selectedTags) return;
|
||||
this.settings.selectedTags = this.settings.selectedTags.filter(t => !(t.id === tagId && (!kbId || t.kbId === kbId)));
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
clearTags() {
|
||||
this.settings.selectedTags = [];
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
addMCPService(serviceId: string) {
|
||||
if (!this.settings.selectedMCPServices) this.settings.selectedMCPServices = [];
|
||||
if (!this.settings.selectedMCPServices.includes(serviceId)) {
|
||||
this.settings.selectedMCPServices.push(serviceId);
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
}
|
||||
},
|
||||
|
||||
removeMCPService(serviceId: string) {
|
||||
if (!this.settings.selectedMCPServices) return;
|
||||
this.settings.selectedMCPServices = this.settings.selectedMCPServices.filter(id => id !== serviceId);
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
addSkill(skillName: string) {
|
||||
if (!this.settings.selectedSkills) this.settings.selectedSkills = [];
|
||||
if (!this.settings.selectedSkills.includes(skillName)) {
|
||||
this.settings.selectedSkills.push(skillName);
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
}
|
||||
},
|
||||
|
||||
removeSkill(skillName: string) {
|
||||
if (!this.settings.selectedSkills) return;
|
||||
this.settings.selectedSkills = this.settings.selectedSkills.filter(name => name !== skillName);
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
setFileKbMap(updates: Record<string, string>) {
|
||||
if (!this.settings.selectedFileKbMap) this.settings.selectedFileKbMap = {};
|
||||
Object.assign(this.settings.selectedFileKbMap, updates);
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
removeFileKbId(fileId: string) {
|
||||
if (this.settings.selectedFileKbMap) delete this.settings.selectedFileKbMap[fileId];
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
getSelectedFiles(): string[] {
|
||||
return this.settings.selectedFiles || [];
|
||||
},
|
||||
|
||||
/**
|
||||
* Scope for suggested-questions API (KB / file / tag @mentions).
|
||||
* Leave `limit` undefined to let the backend apply the agent's configured
|
||||
* starter count; pass a number only to request a specific count.
|
||||
*/
|
||||
getSuggestedQuestionsParams(limit?: number) {
|
||||
const selectedKBs = this.getSelectedKnowledgeBases();
|
||||
const selectedFiles = this.getSelectedFiles();
|
||||
const tags = this.settings.selectedTags || [];
|
||||
const tagScopes = Object.entries(tags.reduce<Record<string, string[]>>((scopes, tag) => {
|
||||
if (!tag.id || !tag.kbId) return scopes;
|
||||
(scopes[tag.kbId] ||= []).push(tag.id);
|
||||
return scopes;
|
||||
}, {})).map(([knowledge_base_id, ids]) => ({
|
||||
knowledge_base_id,
|
||||
tag_ids: [...new Set(ids)],
|
||||
}));
|
||||
return {
|
||||
// A tag's parent KB is only an ownership hint, not an explicit whole-KB
|
||||
// selection. Keep it in tag_scopes so the backend cannot widen a tag to
|
||||
// every document in that KB.
|
||||
knowledge_base_ids: selectedKBs.length > 0 ? selectedKBs : undefined,
|
||||
knowledge_ids: selectedFiles.length > 0 ? selectedFiles : undefined,
|
||||
tag_scopes: tagScopes.length > 0 ? tagScopes : undefined,
|
||||
limit,
|
||||
};
|
||||
},
|
||||
|
||||
// 选择智能体(sourceTenantId 仅在使用共享智能体时传入)
|
||||
selectAgent(agentId: string, sourceTenantId?: string | null) {
|
||||
this.reasoningEffortOverride = '';
|
||||
this.settings.selectedAgentId = agentId;
|
||||
this.settings.selectedAgentSourceTenantId = (sourceTenantId != null && sourceTenantId !== "") ? sourceTenantId : null;
|
||||
// 智能体配置只决定是否具备网络搜索能力,不替用户决定是否在本轮使用。
|
||||
// 每次选择智能体都默认关闭,之后只能由用户从输入框主动开启。
|
||||
this.settings.webSearchEnabled = false;
|
||||
this.settings.localBrowserEnabled = false;
|
||||
// 根据智能体类型自动切换 Agent 模式
|
||||
if (agentId === BUILTIN_QUICK_ANSWER_ID) {
|
||||
this.settings.isAgentEnabled = false;
|
||||
} else if (agentId === BUILTIN_SMART_REASONING_ID) {
|
||||
this.settings.isAgentEnabled = true;
|
||||
}
|
||||
// 自定义智能体需要根据其配置来决定
|
||||
|
||||
// 切换智能体时重置知识库和文件选择状态
|
||||
// 因为不同智能体关联的知识库不同,需要清空用户之前的选择
|
||||
this.settings.selectedKnowledgeBases = [];
|
||||
this.settings.selectedFiles = [];
|
||||
this.settings.selectedFileKbMap = {};
|
||||
this.settings.selectedTags = [];
|
||||
this.settings.selectedMCPServices = [];
|
||||
this.settings.selectedSkills = [];
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
// 获取选中的智能体ID
|
||||
getSelectedAgentId(): string {
|
||||
return this.settings.selectedAgentId || BUILTIN_QUICK_ANSWER_ID;
|
||||
},
|
||||
|
||||
// —— 会话级输入态恢复 —— //
|
||||
//
|
||||
// 输入栏的 agent / 模型 / KB / 联网 / MCP 等选择由本 store 持有,跨会话共享。
|
||||
// 但用户的诉求是:点开旧会话时,能看到当时发起请求的那一套状态。
|
||||
// 实现策略:进入会话时把"当前的全局默认"暂存到一个非持久化的 `_defaultsSnapshot`
|
||||
// 字段里,然后用 session.last_request_state 覆盖 store;离开会话时从快照还原。
|
||||
// 快照不写 localStorage,因为它只在「正处于某个旧会话」这段路由期内有意义;
|
||||
// 刷新页面相当于"重新进入会话" → 重新拍快照 + 覆盖,不会丢失用户的全局默认。
|
||||
|
||||
// 拍下当前 settings 作为"离开会话后要还原回去的默认"。
|
||||
// 已存在快照时不覆盖,避免会话间切换(B→B')把已恢复的 store 错当成默认。
|
||||
snapshotAsDefaultsIfNeeded() {
|
||||
if (this._defaultsSnapshot) return;
|
||||
this._defaultsSnapshot = JSON.parse(JSON.stringify(this.settings));
|
||||
},
|
||||
|
||||
// 还原默认(如果有快照),用于离开会话或跨会话切换时。
|
||||
restoreDefaultsIfSnapshotted() {
|
||||
this.reasoningEffortOverride = '';
|
||||
if (!this._defaultsSnapshot) return;
|
||||
this.settings = this._defaultsSnapshot;
|
||||
this._defaultsSnapshot = null;
|
||||
// 不写 localStorage:默认值在快照之前已经写过 localStorage,这里恢复
|
||||
// 的就是 localStorage 中既有的值,再写一次只会增加无意义的 IO。
|
||||
},
|
||||
|
||||
// 新会话首条发送沿用 createChat 的输入态,不能被异步返回的空/旧记录覆盖。
|
||||
// preserveDraft 必须在请求 session 详情之前捕获,而不是响应返回时读取。
|
||||
hydrateSessionInputState(state: SessionLastRequestStatePayload | null | undefined, preserveDraft = false) {
|
||||
if (!state || preserveDraft) return;
|
||||
this.snapshotAsDefaultsIfNeeded();
|
||||
this.applyLastRequestState(state);
|
||||
},
|
||||
|
||||
// 根据 session.last_request_state 覆盖输入栏相关字段。
|
||||
// 只触碰本次记录的字段,**不**清空 store 中其它无关字段(如模型列表)。
|
||||
// 按字段语义恢复,不将会话选择写入用户默认设置。
|
||||
applyLastRequestState(state: SessionLastRequestStatePayload | null | undefined) {
|
||||
if (!state) return;
|
||||
this._isApplyingSessionState = true;
|
||||
try {
|
||||
this.reasoningEffortOverride = isReasoningLevel(state.reasoning_effort) ? state.reasoning_effort : '';
|
||||
if (typeof state.agent_enabled === "boolean") {
|
||||
this.settings.isAgentEnabled = state.agent_enabled;
|
||||
}
|
||||
if (typeof state.agent_id === "string" && state.agent_id) {
|
||||
this.settings.selectedAgentId = state.agent_id;
|
||||
// 上次记录是自有 agent 还是共享 agent,目前服务端不区分回传 sourceTenantId。
|
||||
// 与 selectAgent() 不同,这里**不**重置 KB/文件选择 —— 因为我们紧接着
|
||||
// 就要用 state 里的 KB/文件覆盖,不需要先清空再写。
|
||||
}
|
||||
if (state.model_id !== undefined) {
|
||||
const current = this.settings.conversationModels || defaultSettings.conversationModels;
|
||||
this.settings.conversationModels = { ...current, selectedChatModelId: state.model_id || "" };
|
||||
}
|
||||
// 后端会用 omitempty 省略空列表,所以缺失值表示“本会话没有 KB 范围”,
|
||||
// 而不是“保留上一个会话的选择”。后者会把过期的 @KB 继续发给服务端。
|
||||
this.settings.selectedKnowledgeBases = Array.isArray(state.knowledge_base_ids)
|
||||
? [...state.knowledge_base_ids]
|
||||
: [];
|
||||
// 服务端省略空的选择项列表;保留现值会把其它会话或全局默认的
|
||||
// 文件、标签和工具选择带入本会话。
|
||||
this.settings.selectedFiles = Array.isArray(state.knowledge_ids) ? [...state.knowledge_ids] : [];
|
||||
// 保留仍选中文件的已知 KB 归属(共享文件需要它);其它文件的缓存不跨会话带入。
|
||||
this.settings.selectedFileKbMap = Object.fromEntries(
|
||||
Object.entries(this.settings.selectedFileKbMap || {})
|
||||
.filter(([id]) => this.settings.selectedFiles.includes(id))
|
||||
);
|
||||
if (Array.isArray(state.mentioned_items)) {
|
||||
const fromMentions = state.mentioned_items
|
||||
.filter(item => item.type === "tag" && item.id && item.kb_id)
|
||||
.filter(item => !Array.isArray(state.tag_ids) || state.tag_ids.includes(item.id))
|
||||
.map(item => ({ id: item.id, name: item.name || item.id, kbId: item.kb_id!, kbName: item.kb_name }));
|
||||
const covered = new Set(fromMentions.map(t => t.id));
|
||||
const orphanTagIds = (state.tag_ids || []).filter(id => id && !covered.has(id));
|
||||
if (orphanTagIds.length > 0 && Array.isArray(state.knowledge_base_ids) && state.knowledge_base_ids.length === 1) {
|
||||
const kbId = state.knowledge_base_ids[0];
|
||||
orphanTagIds.forEach(id => {
|
||||
fromMentions.push({ id, name: id, kbId, kbName: undefined });
|
||||
});
|
||||
}
|
||||
this.settings.selectedTags = fromMentions;
|
||||
} else if (Array.isArray(state.tag_ids)) {
|
||||
const existing = this.settings.selectedTags || [];
|
||||
this.settings.selectedTags = existing.filter(tag => state.tag_ids?.includes(tag.id));
|
||||
} else {
|
||||
this.settings.selectedTags = [];
|
||||
}
|
||||
if (Array.isArray(state.mcp_service_ids)) {
|
||||
this.settings.selectedMCPServices = [...state.mcp_service_ids];
|
||||
} else if (Array.isArray(state.mentioned_items)) {
|
||||
this.settings.selectedMCPServices = state.mentioned_items
|
||||
.filter(item => item.type === "mcp" && item.id)
|
||||
.map(item => item.id);
|
||||
} else {
|
||||
this.settings.selectedMCPServices = [];
|
||||
}
|
||||
if (Array.isArray(state.skill_names)) {
|
||||
this.settings.selectedSkills = [...state.skill_names];
|
||||
} else if (Array.isArray(state.mentioned_items)) {
|
||||
this.settings.selectedSkills = state.mentioned_items
|
||||
.filter(item => item.type === "skill" && item.id)
|
||||
.map(item => item.skill_name || item.id);
|
||||
} else {
|
||||
this.settings.selectedSkills = [];
|
||||
}
|
||||
this.settings.localBrowserEnabled = state.local_browser_enabled === true;
|
||||
if (typeof state.web_search_enabled === "boolean") {
|
||||
this.settings.webSearchEnabled = state.web_search_enabled;
|
||||
}
|
||||
} finally {
|
||||
// 复位必须延后到下一次 flush 之后:监听 selectedAgentId 的 watcher 默认
|
||||
// flush:'pre',是异步执行的;若在此处同步复位,watcher 真正运行时标志早已
|
||||
// 为 false,守卫形同虚设、恢复出来的 KB 仍会被 agent 配置覆盖。放到 nextTick
|
||||
// 可保证本次状态变更触发的 watcher 在标志仍为 true 时执行。
|
||||
nextTick(() => {
|
||||
this._isApplyingSessionState = false;
|
||||
});
|
||||
}
|
||||
// 注意:故意不写 localStorage —— 旧会话的状态不应污染"用户默认"。
|
||||
// 离开会话时 restoreDefaultsIfSnapshotted 会把 localStorage 里那份完整
|
||||
// 的默认值再次同步回 this.settings。
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// 后端 sessions.last_request_state JSON 形状(与 SessionLastRequestState 对齐)。
|
||||
// 字段全部可选——历史会话或新建会话首发前的请求没有这条记录。
|
||||
export interface SessionLastRequestStatePayload {
|
||||
reasoning_effort?: string;
|
||||
agent_id?: string;
|
||||
agent_enabled?: boolean;
|
||||
model_id?: string;
|
||||
knowledge_base_ids?: string[];
|
||||
knowledge_ids?: string[];
|
||||
tag_ids?: string[];
|
||||
mcp_service_ids?: string[];
|
||||
skill_names?: string[];
|
||||
mentioned_items?: Array<{
|
||||
id: string;
|
||||
name?: string;
|
||||
type: string;
|
||||
kb_id?: string;
|
||||
kb_name?: string;
|
||||
skill_name?: string;
|
||||
}>;
|
||||
local_browser_enabled?: boolean;
|
||||
web_search_enabled?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const SETTINGS_STORAGE_KEY = "WeKnora_settings";
|
||||
const BUILTIN_QUICK_ANSWER_ID = "builtin-quick-answer";
|
||||
const BUILTIN_SMART_REASONING_ID = "builtin-smart-reasoning";
|
||||
|
||||
function reconcileBuiltinAgentMode(settings) {
|
||||
const agentId = settings.selectedAgentId || BUILTIN_QUICK_ANSWER_ID;
|
||||
if (agentId === BUILTIN_QUICK_ANSWER_ID && settings.isAgentEnabled) {
|
||||
settings.isAgentEnabled = false;
|
||||
return true;
|
||||
}
|
||||
if (agentId === BUILTIN_SMART_REASONING_ID && !settings.isAgentEnabled) {
|
||||
settings.isAgentEnabled = true;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function cloneSettings(settings) {
|
||||
return JSON.parse(JSON.stringify(settings));
|
||||
}
|
||||
|
||||
function isStoredSettingsRecord(value) {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function reconcileLoadedSettings(loaded) {
|
||||
loaded.selectedTags ||= [];
|
||||
loaded.selectedMCPServices ||= [];
|
||||
loaded.selectedSkills ||= loaded.selectedTools || [];
|
||||
loaded.selectedFileKbMap ||= {};
|
||||
if (reconcileBuiltinAgentMode(loaded)) {
|
||||
localStorage.setItem(SETTINGS_STORAGE_KEY, JSON.stringify(loaded));
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
|
||||
function resetStoredSettings(defaultSettings, reason) {
|
||||
localStorage.removeItem(SETTINGS_STORAGE_KEY);
|
||||
return reconcileLoadedSettings(cloneSettings(defaultSettings));
|
||||
}
|
||||
|
||||
function loadAndReconcileSettings(defaultSettings) {
|
||||
try {
|
||||
const raw = localStorage.getItem(SETTINGS_STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return reconcileLoadedSettings(cloneSettings(defaultSettings));
|
||||
}
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!isStoredSettingsRecord(parsed)) {
|
||||
return resetStoredSettings(
|
||||
defaultSettings,
|
||||
new Error("stored value is not a settings object"),
|
||||
);
|
||||
}
|
||||
return reconcileLoadedSettings(parsed);
|
||||
} catch (e) {
|
||||
return resetStoredSettings(defaultSettings, e);
|
||||
}
|
||||
}
|
||||
|
||||
function makeDefaults() {
|
||||
return {
|
||||
isAgentEnabled: false,
|
||||
selectedAgentId: BUILTIN_QUICK_ANSWER_ID,
|
||||
selectedTags: [],
|
||||
selectedMCPServices: [],
|
||||
selectedSkills: [],
|
||||
selectedFileKbMap: {},
|
||||
nested: { items: ["a"] },
|
||||
};
|
||||
}
|
||||
|
||||
function installMockLocalStorage() {
|
||||
const store = {};
|
||||
Object.defineProperty(globalThis, "localStorage", {
|
||||
value: {
|
||||
getItem: (key) => (key in store ? store[key] : null),
|
||||
setItem: (key, value) => {
|
||||
store[key] = value;
|
||||
},
|
||||
removeItem: (key) => {
|
||||
delete store[key];
|
||||
},
|
||||
},
|
||||
configurable: true,
|
||||
writable: true,
|
||||
});
|
||||
return store;
|
||||
}
|
||||
|
||||
test("isStoredSettingsRecord rejects non-object JSON values", () => {
|
||||
assert.equal(isStoredSettingsRecord(null), false);
|
||||
assert.equal(isStoredSettingsRecord([]), false);
|
||||
assert.equal(isStoredSettingsRecord("x"), false);
|
||||
assert.equal(isStoredSettingsRecord({}), true);
|
||||
});
|
||||
|
||||
test("cloneSettings deep-clones nested structures", () => {
|
||||
const defaults = makeDefaults();
|
||||
const cloned = cloneSettings(defaults);
|
||||
cloned.nested.items.push("b");
|
||||
assert.deepEqual(defaults.nested.items, ["a"]);
|
||||
});
|
||||
|
||||
test("loadAndReconcileSettings returns deep-cloned defaults when key is missing", () => {
|
||||
const store = installMockLocalStorage();
|
||||
const defaults = makeDefaults();
|
||||
|
||||
const loaded = loadAndReconcileSettings(defaults);
|
||||
loaded.selectedTags.push("tag-1");
|
||||
|
||||
assert.deepEqual(defaults.selectedTags, []);
|
||||
assert.equal(store[SETTINGS_STORAGE_KEY], undefined);
|
||||
});
|
||||
|
||||
test("loadAndReconcileSettings resets invalid JSON and removes corrupted key", () => {
|
||||
const store = installMockLocalStorage();
|
||||
store[SETTINGS_STORAGE_KEY] = "{broken";
|
||||
|
||||
const loaded = loadAndReconcileSettings(makeDefaults());
|
||||
|
||||
assert.equal(store[SETTINGS_STORAGE_KEY], undefined);
|
||||
assert.deepEqual(loaded.selectedTags, []);
|
||||
});
|
||||
|
||||
test("loadAndReconcileSettings resets non-object JSON such as null", () => {
|
||||
const store = installMockLocalStorage();
|
||||
store[SETTINGS_STORAGE_KEY] = "null";
|
||||
|
||||
const loaded = loadAndReconcileSettings(makeDefaults());
|
||||
|
||||
assert.equal(store[SETTINGS_STORAGE_KEY], undefined);
|
||||
assert.deepEqual(loaded.selectedTags, []);
|
||||
});
|
||||
|
||||
test("loadAndReconcileSettings keeps valid stored settings", () => {
|
||||
const store = installMockLocalStorage();
|
||||
const stored = {
|
||||
isAgentEnabled: true,
|
||||
selectedAgentId: BUILTIN_QUICK_ANSWER_ID,
|
||||
selectedTags: [{ id: "t1", name: "Tag", kbId: "kb1" }],
|
||||
};
|
||||
store[SETTINGS_STORAGE_KEY] = JSON.stringify(stored);
|
||||
|
||||
const loaded = loadAndReconcileSettings(makeDefaults());
|
||||
|
||||
assert.equal(loaded.isAgentEnabled, false);
|
||||
assert.equal(loaded.selectedTags.length, 1);
|
||||
assert.equal(loaded.selectedTags[0].id, "t1");
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import { safeRemoveItem, safeSetItem } from "@/composables/preferenceStorage";
|
||||
import { reconcileBuiltinAgentMode } from "@/utils/agent-mode";
|
||||
|
||||
export const SETTINGS_STORAGE_KEY = "WeKnora_settings";
|
||||
|
||||
/** Deep-clone settings so nested arrays/objects are not shared with defaults. */
|
||||
export function cloneSettings<T>(settings: T): T {
|
||||
return JSON.parse(JSON.stringify(settings));
|
||||
}
|
||||
|
||||
export function isStoredSettingsRecord(
|
||||
value: unknown,
|
||||
): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
type ReconcilableSettings = {
|
||||
selectedTags?: unknown;
|
||||
selectedMCPServices?: unknown;
|
||||
selectedSkills?: unknown;
|
||||
selectedTools?: unknown;
|
||||
selectedFileKbMap?: unknown;
|
||||
enableMemory?: unknown;
|
||||
isAgentEnabled: boolean;
|
||||
selectedAgentId?: string;
|
||||
};
|
||||
|
||||
function reconcileLoadedSettings<T extends ReconcilableSettings>(loaded: T): T {
|
||||
loaded.selectedTags ||= [];
|
||||
loaded.selectedMCPServices ||= [];
|
||||
loaded.selectedSkills ||= (loaded.selectedTools as string[] | undefined) || [];
|
||||
loaded.selectedFileKbMap ||= {};
|
||||
const removedLegacyMemorySetting = Object.prototype.hasOwnProperty.call(loaded, "enableMemory");
|
||||
if (removedLegacyMemorySetting) {
|
||||
delete loaded.enableMemory;
|
||||
}
|
||||
const reconciledAgentMode = reconcileBuiltinAgentMode(loaded);
|
||||
if (removedLegacyMemorySetting || reconciledAgentMode) {
|
||||
safeSetItem(SETTINGS_STORAGE_KEY, JSON.stringify(loaded));
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
|
||||
function resetStoredSettings<T extends ReconcilableSettings>(
|
||||
defaultSettings: T,
|
||||
reason: unknown,
|
||||
): T {
|
||||
console.error(
|
||||
"[settings] Failed to parse WeKnora_settings from localStorage, resetting to defaults:",
|
||||
reason,
|
||||
);
|
||||
safeRemoveItem(SETTINGS_STORAGE_KEY);
|
||||
return reconcileLoadedSettings(cloneSettings(defaultSettings));
|
||||
}
|
||||
|
||||
/** Load settings from localStorage, reconcile builtin agent mode, fall back on corruption. */
|
||||
export function loadAndReconcileSettings<T extends ReconcilableSettings>(
|
||||
defaultSettings: T,
|
||||
): T {
|
||||
try {
|
||||
const raw = localStorage.getItem(SETTINGS_STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return reconcileLoadedSettings(cloneSettings(defaultSettings));
|
||||
}
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (!isStoredSettingsRecord(parsed)) {
|
||||
return resetStoredSettings(
|
||||
defaultSettings,
|
||||
new Error("stored value is not a settings object"),
|
||||
);
|
||||
}
|
||||
return reconcileLoadedSettings(parsed as T);
|
||||
} catch (e) {
|
||||
return resetStoredSettings(defaultSettings, e);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { isStorageConfigDenied } from './storageEngineAccess.ts'
|
||||
|
||||
/** Mirrors withHttpStatus in utils/request.ts: rejected values carry a
|
||||
* non-enumerable `status` property on the payload. */
|
||||
function rejectedWithStatus(status: number, message = 'forbidden'): unknown {
|
||||
const payload: Record<string, unknown> = { message }
|
||||
Object.defineProperty(payload, 'status', { value: status, enumerable: false })
|
||||
return payload
|
||||
}
|
||||
|
||||
test('isStorageConfigDenied accepts permission rejections', () => {
|
||||
assert.equal(isStorageConfigDenied(rejectedWithStatus(403)), true)
|
||||
assert.equal(isStorageConfigDenied(rejectedWithStatus(401)), true)
|
||||
})
|
||||
|
||||
test('isStorageConfigDenied rejects other failures so they stay fatal', () => {
|
||||
assert.equal(isStorageConfigDenied(rejectedWithStatus(500)), false)
|
||||
assert.equal(isStorageConfigDenied(rejectedWithStatus(404)), false)
|
||||
assert.equal(isStorageConfigDenied(new Error('network down')), false)
|
||||
assert.equal(isStorageConfigDenied(null), false)
|
||||
assert.equal(isStorageConfigDenied(undefined), false)
|
||||
assert.equal(isStorageConfigDenied('403'), false)
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Whether a storage-engine config request was rejected for permissions.
|
||||
*
|
||||
* The tenant KV key `storage-engine-config` is admin-only (it carries
|
||||
* integration secrets), while every agent creator — Contributors included —
|
||||
* needs the Viewer-safe status list to pick a usable provider. The store's
|
||||
* ensureStorageEngine therefore downgrades a permission rejection on the
|
||||
* config call to "no admin config" instead of failing the whole editor
|
||||
* dependency chain (#2991).
|
||||
*
|
||||
* The rejected value carries a non-enumerable `status` property (see
|
||||
* `withHttpStatus` in utils/request.ts); only 401/403 mean "this caller
|
||||
* may not read the admin-only config". Anything else stays fatal.
|
||||
*/
|
||||
export function isStorageConfigDenied(error: unknown): boolean {
|
||||
const status = (error as { status?: unknown } | null | undefined)?.status
|
||||
return status === 401 || status === 403
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { clampSidebarWidth, SIDEBAR_COLLAPSED_WIDTH, SIDEBAR_COLLAPSE_THRESHOLD } from '../utils/sidebarWidth'
|
||||
|
||||
export const useUIStore = defineStore('ui', {
|
||||
state: () => ({
|
||||
showSettingsModal: false,
|
||||
showKBEditorModal: false,
|
||||
kbEditorMode: 'create' as 'create' | 'edit',
|
||||
currentKBId: null as string | null,
|
||||
kbEditorType: 'document' as 'document' | 'faq',
|
||||
// 当前选中的标签 ID,用于文件上传时传递
|
||||
selectedTagIds: [] as string[],
|
||||
kbEditorInitialSection: null as string | null,
|
||||
settingsInitialSection: null as string | null,
|
||||
settingsInitialSubSection: null as string | null,
|
||||
manualEditorVisible: false,
|
||||
manualEditorMode: 'create' as 'create' | 'edit',
|
||||
manualEditorKBId: null as string | null,
|
||||
manualEditorKnowledgeId: null as string | null,
|
||||
manualEditorInitialTitle: '',
|
||||
manualEditorInitialContent: '',
|
||||
manualEditorInitialStatus: 'draft' as 'draft' | 'publish',
|
||||
manualEditorOnSuccess: null as null | ((payload: { kbId: string; knowledgeId: string; status: 'draft' | 'publish' }) => void),
|
||||
sidebarCollapsed: localStorage.getItem('sidebar_collapsed') === 'true',
|
||||
sidebarWidth: clampSidebarWidth(Number(localStorage.getItem('sidebar_width'))),
|
||||
sidebarResizing: false,
|
||||
sidebarBrowserStatus: localStorage.getItem('sidebar_browser_status') !== 'false',
|
||||
}),
|
||||
|
||||
getters: {
|
||||
sidebarDisplayWidth: (state) => state.sidebarCollapsed ? SIDEBAR_COLLAPSED_WIDTH : state.sidebarWidth,
|
||||
},
|
||||
|
||||
actions: {
|
||||
openSettings(section?: string, subSection?: string) {
|
||||
this.settingsInitialSection = section || null
|
||||
this.settingsInitialSubSection = subSection || null
|
||||
this.showSettingsModal = true
|
||||
},
|
||||
|
||||
closeSettings() {
|
||||
this.showSettingsModal = false
|
||||
this.settingsInitialSection = null
|
||||
this.settingsInitialSubSection = null
|
||||
},
|
||||
|
||||
toggleSettings() {
|
||||
this.showSettingsModal = !this.showSettingsModal
|
||||
},
|
||||
|
||||
openKBSettings(kbId: string, initialSection?: string) {
|
||||
this.currentKBId = kbId
|
||||
this.kbEditorMode = 'edit'
|
||||
this.kbEditorType = 'document'
|
||||
this.kbEditorInitialSection = initialSection || null
|
||||
this.showKBEditorModal = true
|
||||
},
|
||||
|
||||
openEditKB(kbId: string, initialSection?: string) {
|
||||
this.openKBSettings(kbId, initialSection)
|
||||
},
|
||||
|
||||
openCreateKB(type: 'document' | 'faq' = 'document', initialSection?: string) {
|
||||
this.currentKBId = null
|
||||
this.kbEditorMode = 'create'
|
||||
this.kbEditorType = type
|
||||
this.kbEditorInitialSection = initialSection || null
|
||||
this.showKBEditorModal = true
|
||||
},
|
||||
|
||||
closeKBEditor() {
|
||||
this.showKBEditorModal = false
|
||||
this.currentKBId = null
|
||||
this.kbEditorInitialSection = null
|
||||
this.kbEditorType = 'document'
|
||||
},
|
||||
|
||||
openManualEditor(options: {
|
||||
mode?: 'create' | 'edit'
|
||||
kbId?: string | null
|
||||
knowledgeId?: string | null
|
||||
title?: string
|
||||
content?: string
|
||||
status?: 'draft' | 'publish'
|
||||
onSuccess?: (payload: { kbId: string; knowledgeId: string; status: 'draft' | 'publish' }) => void
|
||||
} = {}) {
|
||||
this.manualEditorMode = options.mode || 'create'
|
||||
this.manualEditorKBId = options.kbId ?? null
|
||||
this.manualEditorKnowledgeId = options.knowledgeId ?? null
|
||||
this.manualEditorInitialTitle = options.title || ''
|
||||
this.manualEditorInitialContent = options.content || ''
|
||||
this.manualEditorInitialStatus = options.status || 'draft'
|
||||
this.manualEditorOnSuccess = options.onSuccess || null
|
||||
this.manualEditorVisible = true
|
||||
},
|
||||
|
||||
closeManualEditor() {
|
||||
this.manualEditorVisible = false
|
||||
this.manualEditorKnowledgeId = null
|
||||
this.manualEditorInitialContent = ''
|
||||
this.manualEditorInitialTitle = ''
|
||||
this.manualEditorInitialStatus = 'draft'
|
||||
this.manualEditorOnSuccess = null
|
||||
},
|
||||
|
||||
notifyManualEditorSuccess(payload: { kbId: string; knowledgeId: string; status: 'draft' | 'publish' }) {
|
||||
if (typeof this.manualEditorOnSuccess === 'function') {
|
||||
try {
|
||||
this.manualEditorOnSuccess(payload)
|
||||
} catch (err) {
|
||||
console.error('Manual editor success callback error:', err)
|
||||
}
|
||||
}
|
||||
this.manualEditorOnSuccess = null
|
||||
},
|
||||
|
||||
// 设置当前选中的标签 ID
|
||||
toggleSelectedTagId(tagId: string) {
|
||||
const idx = this.selectedTagIds.indexOf(tagId)
|
||||
if (idx >= 0) {
|
||||
this.selectedTagIds.splice(idx, 1)
|
||||
} else {
|
||||
this.selectedTagIds.push(tagId)
|
||||
}
|
||||
},
|
||||
|
||||
clearSelectedTagIds() {
|
||||
this.selectedTagIds = []
|
||||
},
|
||||
|
||||
setSidebarBrowserStatus(visible: boolean) {
|
||||
this.sidebarBrowserStatus = visible
|
||||
localStorage.setItem('sidebar_browser_status', String(visible))
|
||||
},
|
||||
|
||||
toggleSidebar() {
|
||||
this.sidebarCollapsed = !this.sidebarCollapsed
|
||||
localStorage.setItem('sidebar_collapsed', String(this.sidebarCollapsed))
|
||||
},
|
||||
|
||||
resizeSidebar(width: number) {
|
||||
if (!Number.isFinite(width)) return
|
||||
if (width < SIDEBAR_COLLAPSE_THRESHOLD) {
|
||||
this.collapseSidebar()
|
||||
return
|
||||
}
|
||||
this.sidebarWidth = clampSidebarWidth(width)
|
||||
localStorage.setItem('sidebar_width', String(this.sidebarWidth))
|
||||
this.expandSidebar()
|
||||
},
|
||||
|
||||
collapseSidebar() {
|
||||
this.sidebarCollapsed = true
|
||||
localStorage.setItem('sidebar_collapsed', 'true')
|
||||
},
|
||||
|
||||
expandSidebar() {
|
||||
this.sidebarCollapsed = false
|
||||
localStorage.setItem('sidebar_collapsed', 'false')
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,50 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { useUIStore } from './ui.ts'
|
||||
import { SIDEBAR_COLLAPSED_WIDTH } from '../utils/sidebarWidth.ts'
|
||||
|
||||
test('sidebar drag bounds, collapse, button restore, and saved width stay consistent', () => {
|
||||
const originalStorage = Object.getOwnPropertyDescriptor(globalThis, 'localStorage')
|
||||
const storage = new Map<string, string>()
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
value: {
|
||||
getItem: (key: string) => storage.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => storage.set(key, value),
|
||||
},
|
||||
})
|
||||
try {
|
||||
setActivePinia(createPinia())
|
||||
const ui = useUIStore()
|
||||
assert.equal(ui.sidebarDisplayWidth, 260)
|
||||
ui.resizeSidebar(900)
|
||||
assert.equal(ui.sidebarDisplayWidth, 280)
|
||||
ui.resizeSidebar(195)
|
||||
assert.equal(ui.sidebarDisplayWidth, 220)
|
||||
ui.resizeSidebar(270)
|
||||
ui.resizeSidebar(179)
|
||||
assert.equal(ui.sidebarCollapsed, true)
|
||||
assert.equal(ui.sidebarDisplayWidth, SIDEBAR_COLLAPSED_WIDTH)
|
||||
ui.toggleSidebar()
|
||||
assert.equal(ui.sidebarDisplayWidth, 270, 'collapse keeps the last expanded width')
|
||||
ui.collapseSidebar()
|
||||
ui.resizeSidebar(240)
|
||||
assert.equal(ui.sidebarCollapsed, false, 'drag can reopen the collapsed sidebar')
|
||||
assert.equal(ui.sidebarDisplayWidth, 240)
|
||||
|
||||
setActivePinia(createPinia())
|
||||
assert.equal(useUIStore().sidebarDisplayWidth, 240, 'reload restores the chosen width')
|
||||
storage.set('sidebar_width', '420')
|
||||
setActivePinia(createPinia())
|
||||
assert.equal(useUIStore().sidebarDisplayWidth, 280, 'old saved widths respect the reduced maximum')
|
||||
for (const invalid of ['NaN', '-1', '0', '']) {
|
||||
storage.set('sidebar_width', invalid)
|
||||
setActivePinia(createPinia())
|
||||
assert.equal(useUIStore().sidebarDisplayWidth, 260)
|
||||
}
|
||||
} finally {
|
||||
if (originalStorage) Object.defineProperty(globalThis, 'localStorage', originalStorage)
|
||||
else Reflect.deleteProperty(globalThis, 'localStorage')
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,121 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import type { KnowledgeProcessOverrides } from '@/types/knowledgeProcess'
|
||||
|
||||
export type UploadConfirmMode = 'file' | 'url' | 'manual' | 'reparse'
|
||||
|
||||
export interface UploadConfirmManualSource {
|
||||
kbId: string
|
||||
knowledgeId?: string
|
||||
title: string
|
||||
content: string
|
||||
tagIds?: string[]
|
||||
}
|
||||
|
||||
export interface UploadConfirmReparseSource {
|
||||
knowledgeId: string
|
||||
fileName?: string
|
||||
fileType?: string
|
||||
processOverrides?: KnowledgeProcessOverrides | null
|
||||
}
|
||||
|
||||
export interface UploadConfirmResult {
|
||||
processConfig: KnowledgeProcessOverrides
|
||||
mode: UploadConfirmMode
|
||||
tagIds?: string[]
|
||||
files?: File[]
|
||||
urls?: string[]
|
||||
manual?: UploadConfirmManualSource
|
||||
reparse?: UploadConfirmReparseSource
|
||||
/**
|
||||
* Folder the batch is uploaded into ('' = knowledge base root). Returned as
|
||||
* part of the result because the dialog lets the user change it, so callers
|
||||
* must use this value rather than whatever folder was open when they opened
|
||||
* the dialog.
|
||||
*/
|
||||
targetFolder?: string
|
||||
}
|
||||
|
||||
export interface OpenUploadConfirmOptions {
|
||||
mode: UploadConfirmMode
|
||||
kbInfo: any
|
||||
tagIds?: string[]
|
||||
files?: File[]
|
||||
urls?: string[]
|
||||
manual?: UploadConfirmManualSource
|
||||
reparse?: UploadConfirmReparseSource
|
||||
acceptFileTypes?: string
|
||||
supportedFileTypes?: string[]
|
||||
/** Folder pre-selected from the sidebar tree; '' means the root. */
|
||||
targetFolder?: string
|
||||
/** Existing folders the dialog can offer as upload destinations. */
|
||||
folderOptions?: Array<{ path: string; name: string; depth: number }>
|
||||
}
|
||||
|
||||
export const useUploadConfirmStore = defineStore('uploadConfirm', {
|
||||
state: () => ({
|
||||
visible: false,
|
||||
mode: 'file' as UploadConfirmMode,
|
||||
kbInfo: null as any,
|
||||
files: [] as File[],
|
||||
urls: [] as string[],
|
||||
tagIds: [] as string[],
|
||||
manual: null as UploadConfirmManualSource | null,
|
||||
reparse: null as UploadConfirmReparseSource | null,
|
||||
acceptFileTypes: '',
|
||||
supportedFileTypes: [] as string[],
|
||||
targetFolder: '',
|
||||
folderOptions: [] as Array<{ path: string; name: string; depth: number }>,
|
||||
pendingResolve: null as ((value: UploadConfirmResult) => void) | null,
|
||||
pendingReject: null as (() => void) | null,
|
||||
}),
|
||||
|
||||
actions: {
|
||||
open(options: OpenUploadConfirmOptions): Promise<UploadConfirmResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.visible = true
|
||||
this.mode = options.mode
|
||||
this.kbInfo = options.kbInfo
|
||||
this.files = options.files ? [...options.files] : []
|
||||
this.urls = options.urls ? [...options.urls] : []
|
||||
this.tagIds = options.tagIds
|
||||
? [...options.tagIds]
|
||||
: [...(options.manual?.tagIds || [])]
|
||||
this.manual = options.manual || null
|
||||
this.reparse = options.reparse || null
|
||||
this.acceptFileTypes = options.acceptFileTypes || ''
|
||||
this.supportedFileTypes = options.supportedFileTypes ? [...options.supportedFileTypes] : []
|
||||
this.targetFolder = options.targetFolder || ''
|
||||
this.folderOptions = options.folderOptions ? [...options.folderOptions] : []
|
||||
this.pendingResolve = resolve
|
||||
this.pendingReject = reject
|
||||
})
|
||||
},
|
||||
|
||||
resolveConfirm(payload: UploadConfirmResult) {
|
||||
this.pendingResolve?.(payload)
|
||||
this.reset()
|
||||
},
|
||||
|
||||
rejectConfirm() {
|
||||
this.pendingReject?.()
|
||||
this.reset()
|
||||
},
|
||||
|
||||
reset() {
|
||||
this.visible = false
|
||||
this.mode = 'file'
|
||||
this.kbInfo = null
|
||||
this.files = []
|
||||
this.urls = []
|
||||
this.tagIds = []
|
||||
this.manual = null
|
||||
this.reparse = null
|
||||
this.acceptFileTypes = ''
|
||||
this.supportedFileTypes = []
|
||||
this.targetFolder = ''
|
||||
this.folderOptions = []
|
||||
this.pendingResolve = null
|
||||
this.pendingReject = null
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,319 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
createListRefreshThrottle,
|
||||
createUploadQueue,
|
||||
type KnowledgeStatusRow,
|
||||
type Timers,
|
||||
type TransferEnd,
|
||||
type UploadBatch,
|
||||
type UploadPayload,
|
||||
type UploadQueueDeps,
|
||||
} from './uploadQueue.ts'
|
||||
import type { UploadItem } from './uploadTasksState.ts'
|
||||
|
||||
type Call = {
|
||||
batch: UploadBatch
|
||||
payload: UploadPayload
|
||||
signal: AbortSignal
|
||||
progress: (ratio: number) => void
|
||||
resolve: (value: unknown) => void
|
||||
reject: (reason: unknown) => void
|
||||
}
|
||||
|
||||
const file = (name: string, size = 100) => ({ name, size, webkitRelativePath: '' }) as unknown as File
|
||||
|
||||
const flush = () => new Promise(resolve => setImmediate(resolve))
|
||||
|
||||
/** Timers that only fire when the test says so. */
|
||||
function manualTimers() {
|
||||
const pending = new Set<{ fn: () => void; ms: number }>()
|
||||
const timers: Timers = {
|
||||
setTimer: (fn, ms) => {
|
||||
const handle = { fn, ms }
|
||||
pending.add(handle)
|
||||
return handle
|
||||
},
|
||||
clearTimer: handle => {
|
||||
pending.delete(handle as { fn: () => void; ms: number })
|
||||
},
|
||||
}
|
||||
const runAll = () => {
|
||||
const due = [...pending]
|
||||
pending.clear()
|
||||
for (const handle of due) handle.fn()
|
||||
}
|
||||
return { timers, runAll, pending }
|
||||
}
|
||||
|
||||
function setup(overrides: Partial<UploadQueueDeps> = {}) {
|
||||
const items: UploadItem[] = []
|
||||
const batches: UploadBatch[] = []
|
||||
const calls: Call[] = []
|
||||
const ends: Array<[string, TransferEnd]> = []
|
||||
const statusRows = new Map<string, KnowledgeStatusRow[] | null>()
|
||||
const clock = manualTimers()
|
||||
|
||||
const queue = createUploadQueue(items, batches, {
|
||||
concurrency: 2,
|
||||
pollIntervalMs: 1000,
|
||||
pollChunkSize: 2,
|
||||
pollConcurrency: 4,
|
||||
upload: (batch, payload, progress, signal) => new Promise((resolve, reject) => {
|
||||
calls.push({ batch, payload, signal, progress, resolve, reject })
|
||||
signal.addEventListener('abort', () => reject({ message: 'Network error' }))
|
||||
}),
|
||||
queryStatus: async (kbId, ids) => {
|
||||
const rows = statusRows.get(kbId)
|
||||
return rows === null ? null : (rows ?? []).filter(row => ids.includes(row.id))
|
||||
},
|
||||
onTransferEnd: (kbId, end) => ends.push([kbId, end]),
|
||||
timers: clock.timers,
|
||||
...overrides,
|
||||
})
|
||||
const batch = (kbId = 'kb1') => ({ kbId, kbName: 'KB', targetFolder: '' })
|
||||
const byName = (name: string) => items.find(item => item.name === name)!
|
||||
return { items, batches, calls, ends, statusRows, clock, queue, batch, byName }
|
||||
}
|
||||
|
||||
test('runs at most `concurrency` transfers and starts the next as one settles', async () => {
|
||||
const { calls, ends, queue, batch, byName } = setup()
|
||||
queue.add(batch(), [{ file: file('a', 100) }, { file: file('b', 200) }, { file: file('c', 300) }])
|
||||
assert.deepEqual(calls.map(call => call.payload.file.name), ['a', 'b'])
|
||||
assert.equal(byName('c').transfer, 'queued')
|
||||
|
||||
calls[0].progress(0.4)
|
||||
assert.equal(byName('a').loaded, 40)
|
||||
|
||||
calls[0].resolve({ success: true, data: { id: 'k-a', parse_status: 'pending' } })
|
||||
await flush()
|
||||
assert.equal(byName('a').transfer, 'uploaded')
|
||||
assert.equal(byName('a').knowledgeId, 'k-a')
|
||||
assert.deepEqual(calls.map(call => call.payload.file.name), ['a', 'b', 'c'])
|
||||
assert.deepEqual(ends, [['kb1', { uploaded: true, settled: false }]])
|
||||
})
|
||||
|
||||
test('never runs two same-size files for one knowledge base at once', async () => {
|
||||
const { calls, queue, batch } = setup({ concurrency: 3 })
|
||||
queue.add(batch(), [{ file: file('copy-1', 500) }, { file: file('copy-2', 500) }, { file: file('other', 7) }])
|
||||
queue.add(batch('kb2'), [{ file: file('elsewhere', 500) }])
|
||||
// copy-2 waits for copy-1, so the server's hash dedup sees copy-1's row.
|
||||
assert.deepEqual(calls.map(call => call.payload.file.name), ['copy-1', 'other', 'elsewhere'])
|
||||
|
||||
calls[0].resolve({ success: true, data: { id: 'k1' } })
|
||||
await flush()
|
||||
assert.equal(calls[3].payload.file.name, 'copy-2')
|
||||
})
|
||||
|
||||
test('classifies duplicates and failures, and retries a failed file', async () => {
|
||||
const { calls, ends, queue, batch, byName } = setup()
|
||||
queue.add(batch(), [{ file: file('dup', 1) }, { file: file('bad', 2) }])
|
||||
|
||||
calls[0].reject({ status: 409, code: 'duplicate_file', data: { id: 'k-old' } })
|
||||
calls[1].reject({ status: 400, message: 'too large' })
|
||||
await flush()
|
||||
assert.equal(byName('dup').transfer, 'duplicate')
|
||||
assert.equal(byName('dup').knowledgeId, 'k-old')
|
||||
assert.equal(byName('bad').transfer, 'failed')
|
||||
assert.equal(byName('bad').error, 'too large')
|
||||
assert.deepEqual(ends.at(-1), ['kb1', { uploaded: false, settled: true }])
|
||||
|
||||
queue.retryFailed()
|
||||
assert.equal(calls.length, 3)
|
||||
assert.equal(calls[2].payload.file.name, 'bad')
|
||||
// Duplicates are settled, not retryable.
|
||||
assert.equal(byName('dup').transfer, 'duplicate')
|
||||
calls[2].resolve({ success: true, data: { id: 'k-bad' } })
|
||||
await flush()
|
||||
assert.equal(byName('bad').transfer, 'uploaded')
|
||||
assert.equal(byName('bad').parseStatus, 'pending')
|
||||
assert.deepEqual(ends.at(-1), ['kb1', { uploaded: true, settled: true }])
|
||||
})
|
||||
|
||||
test('cancelling aborts the request without reporting it as a failure', async () => {
|
||||
const { calls, ends, queue, batch, byName } = setup()
|
||||
queue.add(batch(), [{ file: file('a', 1) }, { file: file('b', 2) }, { file: file('c', 3) }])
|
||||
|
||||
queue.cancel(byName('c').id)
|
||||
assert.equal(byName('c').transfer, 'cancelled')
|
||||
|
||||
queue.cancel(byName('a').id)
|
||||
assert.equal(calls[0].signal.aborted, true)
|
||||
await flush()
|
||||
assert.equal(byName('a').transfer, 'cancelled')
|
||||
assert.equal(byName('a').error, undefined)
|
||||
// The freed slot doesn't resurrect the cancelled queued file.
|
||||
assert.equal(calls.length, 2)
|
||||
assert.deepEqual(ends, [['kb1', { uploaded: false, settled: false }]])
|
||||
|
||||
// Fully sent: the server is already storing it, so it can't be cancelled.
|
||||
calls[1].progress(1)
|
||||
queue.cancel(byName('b').id)
|
||||
assert.equal(calls[1].signal.aborted, false)
|
||||
assert.equal(byName('b').transfer, 'uploading')
|
||||
})
|
||||
|
||||
test('a late abort from a cancelled attempt cannot overwrite its retry', async () => {
|
||||
let rejectFirst!: (reason: unknown) => void
|
||||
const { calls, queue, batch, byName } = setup({
|
||||
// The first attempt ignores its signal, as a slow transport might.
|
||||
upload: (b, payload, progress, signal) => new Promise((resolve, reject) => {
|
||||
calls.push({ batch: b, payload, signal, progress, resolve, reject })
|
||||
if (calls.length === 1) rejectFirst = reject
|
||||
}),
|
||||
})
|
||||
queue.add(batch(), [{ file: file('a') }])
|
||||
queue.cancel(byName('a').id)
|
||||
queue.retry(byName('a').id)
|
||||
assert.equal(calls.length, 2)
|
||||
|
||||
rejectFirst({ message: 'Network error' })
|
||||
await flush()
|
||||
assert.equal(byName('a').transfer, 'uploading')
|
||||
|
||||
calls[1].resolve({ success: true, data: { id: 'k-a' } })
|
||||
await flush()
|
||||
assert.equal(byName('a').transfer, 'uploaded')
|
||||
})
|
||||
|
||||
test('polls created rows until parsing settles', async () => {
|
||||
const { calls, clock, statusRows, queue, batch, byName } = setup()
|
||||
queue.add(batch(), [{ file: file('a', 1) }, { file: file('b', 2) }, { file: file('c', 3) }])
|
||||
calls[0].resolve({ success: true, data: { id: 'k-a', parse_status: 'pending' } })
|
||||
calls[1].resolve({ success: true, data: { id: 'k-b', parse_status: 'pending' } })
|
||||
await flush()
|
||||
calls[2].resolve({ success: true, data: { id: 'k-c', parse_status: 'pending' } })
|
||||
await flush()
|
||||
// One timer no matter how many uploads landed.
|
||||
assert.equal(clock.pending.size, 1)
|
||||
|
||||
statusRows.set('kb1', null)
|
||||
await queue.pollNow()
|
||||
assert.equal(byName('a').parseStatus, 'pending', 'a failed request changes nothing')
|
||||
|
||||
statusRows.set('kb1', [
|
||||
{ id: 'k-a', parse_status: 'completed' },
|
||||
{ id: 'k-b', parse_status: 'failed', error_message: 'broken pdf' },
|
||||
])
|
||||
await queue.pollNow()
|
||||
assert.equal(byName('a').parseStatus, 'completed')
|
||||
assert.equal(byName('b').parseStatus, 'failed')
|
||||
assert.equal(byName('b').parseError, 'broken pdf')
|
||||
// Missing from one answer is not proof of deletion.
|
||||
assert.equal(byName('c').parseStatus, 'pending')
|
||||
await queue.pollNow()
|
||||
assert.equal(byName('c').parseStatus, 'pending')
|
||||
await queue.pollNow()
|
||||
assert.equal(byName('c').parseStatus, 'deleted')
|
||||
})
|
||||
|
||||
test('a poll keeps at most `pollConcurrency` status requests in flight', async () => {
|
||||
// Thousands of files still parsing used to fire every chunk at once, one
|
||||
// database connection each on the server.
|
||||
const pending: Array<{ ids: string[]; resolve: (rows: KnowledgeStatusRow[]) => void }> = []
|
||||
const { items, batches, queue, byName } = setup({
|
||||
pollConcurrency: 2,
|
||||
queryStatus: (_kbId, ids) => new Promise(resolve => pending.push({ ids, resolve })),
|
||||
})
|
||||
batches.push({ id: 'b1', kbId: 'kb1', kbName: 'KB', targetFolder: '' })
|
||||
for (const name of ['a', 'b', 'c', 'd', 'e', 'f', 'g']) {
|
||||
items.push({
|
||||
id: `u-${name}`, batchId: 'b1', name, relativePath: '', size: 1, loaded: 1,
|
||||
transfer: 'uploaded', knowledgeId: `k-${name}`, parseStatus: 'pending',
|
||||
})
|
||||
}
|
||||
|
||||
const poll = queue.pollNow()
|
||||
let done = false
|
||||
void poll.then(() => { done = true })
|
||||
const answered: string[][] = []
|
||||
let maxInFlight = 0
|
||||
while (!done) {
|
||||
await flush()
|
||||
maxInFlight = Math.max(maxInFlight, pending.length)
|
||||
const next = pending.shift()
|
||||
if (!next) continue
|
||||
answered.push(next.ids)
|
||||
next.resolve(next.ids.map(id => ({ id, parse_status: 'completed' })))
|
||||
}
|
||||
|
||||
assert.equal(maxInFlight, 2)
|
||||
// pollChunkSize 2: seven ids in four requests, each id asked about once.
|
||||
assert.deepEqual(answered.flat().sort(), ['k-a', 'k-b', 'k-c', 'k-d', 'k-e', 'k-f', 'k-g'])
|
||||
assert.equal(answered.length, 4)
|
||||
assert.equal(byName('g').parseStatus, 'completed')
|
||||
})
|
||||
|
||||
test('a row that reappears resets its missing count', async () => {
|
||||
const { calls, statusRows, queue, batch, byName } = setup()
|
||||
queue.add(batch(), [{ file: file('a') }])
|
||||
calls[0].resolve({ success: true, data: { id: 'k-a', parse_status: 'pending' } })
|
||||
await flush()
|
||||
|
||||
statusRows.set('kb1', [])
|
||||
await queue.pollNow()
|
||||
await queue.pollNow()
|
||||
statusRows.set('kb1', [{ id: 'k-a', parse_status: 'processing' }])
|
||||
await queue.pollNow()
|
||||
statusRows.set('kb1', [])
|
||||
await queue.pollNow()
|
||||
await queue.pollNow()
|
||||
assert.equal(byName('a').parseStatus, 'processing')
|
||||
})
|
||||
|
||||
test('clear() lets fully sent files finish and reports them, but aborts the rest', async () => {
|
||||
const { items, batches, calls, ends, queue, batch } = setup()
|
||||
queue.add(batch(), [{ file: file('sent', 1) }, { file: file('sending', 2) }])
|
||||
calls[0].progress(1)
|
||||
calls[1].progress(0.3)
|
||||
|
||||
queue.clear()
|
||||
assert.equal(calls[0].signal.aborted, false)
|
||||
assert.equal(calls[1].signal.aborted, true)
|
||||
assert.equal(items.length, 0)
|
||||
assert.equal(batches.length, 0)
|
||||
assert.deepEqual(ends, [['kb1', { uploaded: false, settled: true }]])
|
||||
|
||||
queue.add(batch(), [{ file: file('next', 3) }])
|
||||
calls[0].resolve({ success: true, data: { id: 'late' } })
|
||||
await flush()
|
||||
assert.deepEqual(items.map(item => item.name), ['next'])
|
||||
// The late file is new in the list; the new batch still has work queued.
|
||||
assert.deepEqual(ends.at(-1), ['kb1', { uploaded: true, settled: false }])
|
||||
})
|
||||
|
||||
test('pruneFinished drops clean batches and keeps ones with issues', async () => {
|
||||
const { items, batches, calls, statusRows, queue, batch } = setup()
|
||||
queue.add(batch(), [{ file: file('ok', 1) }])
|
||||
queue.add(batch(), [{ file: file('broken', 2) }])
|
||||
calls[0].resolve({ success: true, data: { id: 'k-ok' } })
|
||||
calls[1].reject({ status: 500, message: 'boom' })
|
||||
await flush()
|
||||
statusRows.set('kb1', [{ id: 'k-ok', parse_status: 'completed' }])
|
||||
await queue.pollNow()
|
||||
|
||||
queue.pruneFinished()
|
||||
assert.equal(batches.length, 1)
|
||||
assert.deepEqual(items.map(item => item.name), ['broken'])
|
||||
})
|
||||
|
||||
test('list refresh throttle: mid-batch at most once per interval, one final refresh', () => {
|
||||
const emitted: Array<[string, boolean]> = []
|
||||
const clock = manualTimers()
|
||||
const notify = createListRefreshThrottle((kbId, settled) => emitted.push([kbId, settled]), 2000, 150, clock.timers)
|
||||
|
||||
notify('kb1', { uploaded: true, settled: false })
|
||||
notify('kb1', { uploaded: true, settled: false })
|
||||
notify('kb1', { uploaded: false, settled: false })
|
||||
assert.deepEqual(emitted, [['kb1', false]])
|
||||
clock.runAll()
|
||||
assert.deepEqual(emitted, [['kb1', false], ['kb1', false]])
|
||||
|
||||
// Several ends settling together (cancel all) make one final refresh.
|
||||
notify('kb1', { uploaded: false, settled: true })
|
||||
notify('kb1', { uploaded: false, settled: true })
|
||||
clock.runAll()
|
||||
assert.deepEqual(emitted.slice(2), [['kb1', true]])
|
||||
clock.runAll()
|
||||
assert.equal(emitted.length, 3)
|
||||
})
|
||||
@@ -0,0 +1,382 @@
|
||||
import type { KnowledgeProcessOverrides } from '@/types/knowledgeProcess'
|
||||
import {
|
||||
classifyUploadResult,
|
||||
itemPhase,
|
||||
needsParsePolling,
|
||||
pickNextToStart,
|
||||
type UploadItem,
|
||||
} from './uploadTasksState'
|
||||
|
||||
/**
|
||||
* The upload queue's behaviour — bounded concurrent transfers, cancel, retry
|
||||
* and polling the created rows until parsing settles — with the network and
|
||||
* timers injected, so the store only wires it to the API and Vue.
|
||||
*
|
||||
* `items` and `batches` are mutated in place (never reassigned) so a reactive
|
||||
* array handed in by the store stays the one the panel renders.
|
||||
*/
|
||||
|
||||
export interface UploadBatch {
|
||||
id: string
|
||||
kbId: string
|
||||
kbName: string
|
||||
/** Destination folder, '' for the knowledge base root. */
|
||||
targetFolder: string
|
||||
tagIds?: string[]
|
||||
processConfig?: KnowledgeProcessOverrides
|
||||
}
|
||||
|
||||
export interface UploadPayload {
|
||||
file: File
|
||||
/** Path-qualified name the backend splits into folder + file name. */
|
||||
fileName?: string
|
||||
}
|
||||
|
||||
export interface KnowledgeStatusRow {
|
||||
id: string
|
||||
parse_status?: string
|
||||
error_message?: string
|
||||
}
|
||||
|
||||
export interface TransferEnd {
|
||||
/** The file reached the server, so the knowledge base has a new row. */
|
||||
uploaded: boolean
|
||||
/** Nothing is queued or uploading for this knowledge base any more. */
|
||||
settled: boolean
|
||||
}
|
||||
|
||||
export interface Timers {
|
||||
setTimer: (fn: () => void, ms: number) => unknown
|
||||
clearTimer: (handle: unknown) => void
|
||||
}
|
||||
|
||||
export const defaultTimers: Timers = {
|
||||
setTimer: (fn, ms) => setTimeout(fn, ms),
|
||||
clearTimer: handle => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
||||
}
|
||||
|
||||
export interface UploadQueueDeps {
|
||||
concurrency: number
|
||||
pollIntervalMs: number
|
||||
/** Most knowledge ids asked about in one status request. */
|
||||
pollChunkSize: number
|
||||
/**
|
||||
* Most status requests one poll keeps in flight. Each one holds a database
|
||||
* connection on the server, so thousands of files still parsing must not
|
||||
* turn into a burst of hundreds of parallel requests.
|
||||
*/
|
||||
pollConcurrency: number
|
||||
/** Resolves or rejects with the API's response body; the queue classifies either. */
|
||||
upload: (
|
||||
batch: UploadBatch,
|
||||
payload: UploadPayload,
|
||||
onProgress: (ratio: number) => void,
|
||||
signal: AbortSignal,
|
||||
) => Promise<unknown>
|
||||
/** Current rows for the ids, or null when the request failed. */
|
||||
queryStatus: (kbId: string, knowledgeIds: string[]) => Promise<KnowledgeStatusRow[] | null>
|
||||
/** Called whenever a transfer ends, including one that outlived clear(). */
|
||||
onTransferEnd: (kbId: string, end: TransferEnd) => void
|
||||
timers?: Timers
|
||||
}
|
||||
|
||||
/**
|
||||
* Consecutive successful polls a row must be missing from before it counts as
|
||||
* deleted, so one odd answer can't strand a live document as "Deleted".
|
||||
*/
|
||||
const MISSING_POLLS_BEFORE_DELETED = 3
|
||||
|
||||
let idSeq = 0
|
||||
const nextId = (prefix: string) => `${prefix}-${Date.now().toString(36)}-${(idSeq++).toString(36)}`
|
||||
|
||||
export function createUploadQueue(items: UploadItem[], batches: UploadBatch[], deps: UploadQueueDeps) {
|
||||
const { setTimer, clearTimer } = deps.timers ?? defaultTimers
|
||||
|
||||
// File payloads and abort handles stay out of the (possibly reactive) items:
|
||||
// proxying a File buys nothing and the panel never renders them.
|
||||
const payloads = new Map<string, UploadPayload>()
|
||||
const controllers = new Map<string, AbortController>()
|
||||
const missingPolls = new Map<string, number>()
|
||||
// Bumped by clear(), so work started before it cannot touch what comes after.
|
||||
let generation = 0
|
||||
let pollTimer: unknown = null
|
||||
|
||||
const batchOf = (item: UploadItem) => batches.find(batch => batch.id === item.batchId)
|
||||
const findItem = (id: string) => items.find(item => item.id === id)
|
||||
|
||||
const isBusy = (kbId: string) => items.some(item =>
|
||||
(item.transfer === 'queued' || item.transfer === 'uploading') && batchOf(item)?.kbId === kbId)
|
||||
|
||||
// ---- transfer -----------------------------------------------------------
|
||||
|
||||
// Identical files always have the same size. Keeping same-size files for one
|
||||
// knowledge base out of flight together lets the server's content-hash dedup,
|
||||
// which only sees rows already written, catch the second copy.
|
||||
const dedupKey = (item: UploadItem) => `${batchOf(item)?.kbId}:${item.size}`
|
||||
|
||||
const pump = () => {
|
||||
for (const item of pickNextToStart(items, deps.concurrency, dedupKey)) void transfer(item)
|
||||
}
|
||||
|
||||
const transfer = async (item: UploadItem) => {
|
||||
const batch = batchOf(item)
|
||||
const payload = payloads.get(item.id)
|
||||
if (!batch || !payload) {
|
||||
item.transfer = 'failed'
|
||||
return
|
||||
}
|
||||
const startedIn = generation
|
||||
const controller = new AbortController()
|
||||
controllers.set(item.id, controller)
|
||||
item.transfer = 'uploading'
|
||||
item.loaded = 0
|
||||
item.error = undefined
|
||||
|
||||
let result: unknown
|
||||
try {
|
||||
result = await deps.upload(batch, payload, ratio => {
|
||||
if (item.transfer === 'uploading') item.loaded = Math.min(item.size, Math.round(ratio * item.size))
|
||||
}, controller.signal)
|
||||
} catch (error) {
|
||||
result = error
|
||||
}
|
||||
// A retry after a cancel starts a new attempt under the same id; only the
|
||||
// latest attempt may write the item.
|
||||
const latestAttempt = controllers.get(item.id) === controller
|
||||
if (latestAttempt) controllers.delete(item.id)
|
||||
const aborted = controller.signal.aborted
|
||||
|
||||
// Outlived clear(): the row is gone from the panel, but a file that still
|
||||
// made it (clear() lets fully sent files finish) is new in the list.
|
||||
if (startedIn !== generation) {
|
||||
if (!aborted && classifyUploadResult(result).kind === 'uploaded') {
|
||||
deps.onTransferEnd(batch.kbId, { uploaded: true, settled: !isBusy(batch.kbId) })
|
||||
}
|
||||
return
|
||||
}
|
||||
if (!latestAttempt) return
|
||||
|
||||
if (aborted || item.transfer !== 'uploading') {
|
||||
// Cancelled mid-flight; the abort rejection carries nothing worth showing.
|
||||
if (item.transfer === 'uploading') item.transfer = 'cancelled'
|
||||
} else {
|
||||
const outcome = classifyUploadResult(result)
|
||||
if (outcome.kind === 'uploaded') {
|
||||
item.transfer = 'uploaded'
|
||||
item.loaded = item.size
|
||||
item.knowledgeId = outcome.knowledgeId
|
||||
item.parseStatus = outcome.parseStatus || 'pending'
|
||||
payloads.delete(item.id)
|
||||
schedulePoll()
|
||||
} else if (outcome.kind === 'duplicate') {
|
||||
item.transfer = 'duplicate'
|
||||
item.knowledgeId = outcome.knowledgeId
|
||||
payloads.delete(item.id)
|
||||
} else {
|
||||
item.transfer = 'failed'
|
||||
item.error = outcome.message
|
||||
}
|
||||
}
|
||||
deps.onTransferEnd(batch.kbId, { uploaded: item.transfer === 'uploaded', settled: !isBusy(batch.kbId) })
|
||||
pump()
|
||||
}
|
||||
|
||||
const add = (batchInput: Omit<UploadBatch, 'id'>, uploads: UploadPayload[]) => {
|
||||
const batch: UploadBatch = { ...batchInput, id: nextId('batch') }
|
||||
batches.push(batch)
|
||||
for (const upload of uploads) {
|
||||
const id = nextId('upload')
|
||||
payloads.set(id, upload)
|
||||
items.push({
|
||||
id,
|
||||
batchId: batch.id,
|
||||
name: upload.file.name,
|
||||
relativePath: upload.file.webkitRelativePath || '',
|
||||
size: upload.file.size,
|
||||
loaded: 0,
|
||||
transfer: 'queued',
|
||||
})
|
||||
}
|
||||
pump()
|
||||
return batch
|
||||
}
|
||||
|
||||
const cancel = (id: string) => {
|
||||
const item = findItem(id)
|
||||
if (!item || (item.transfer !== 'queued' && item.transfer !== 'uploading')) return
|
||||
// Once the whole body is sent the server is already storing the file;
|
||||
// aborting now would hide a row that still gets created.
|
||||
if (itemPhase(item) === 'saving') return
|
||||
item.transfer = 'cancelled'
|
||||
item.loaded = 0
|
||||
const controller = controllers.get(id)
|
||||
if (controller) {
|
||||
// Its transfer reports the end once the abort lands.
|
||||
controller.abort()
|
||||
return
|
||||
}
|
||||
const kbId = batchOf(item)?.kbId
|
||||
if (kbId && !isBusy(kbId)) deps.onTransferEnd(kbId, { uploaded: false, settled: true })
|
||||
}
|
||||
|
||||
const cancelAll = () => {
|
||||
for (const item of items) cancel(item.id)
|
||||
}
|
||||
|
||||
const retry = (id: string) => {
|
||||
const item = findItem(id)
|
||||
if (!item || (item.transfer !== 'failed' && item.transfer !== 'cancelled') || !payloads.has(id)) return
|
||||
item.transfer = 'queued'
|
||||
item.loaded = 0
|
||||
item.error = undefined
|
||||
pump()
|
||||
}
|
||||
|
||||
const retryFailed = () => {
|
||||
for (const item of items) retry(item.id)
|
||||
}
|
||||
|
||||
/** Drop batches whose every file is searchable; anything with an issue stays. */
|
||||
const pruneFinished = () => {
|
||||
for (const batch of [...batches]) {
|
||||
const own = items.filter(item => item.batchId === batch.id)
|
||||
if (!own.every(item => itemPhase(item) === 'ready')) continue
|
||||
for (const item of own) {
|
||||
items.splice(items.indexOf(item), 1)
|
||||
missingPolls.delete(item.id)
|
||||
}
|
||||
batches.splice(batches.indexOf(batch), 1)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- parse polling ------------------------------------------------------
|
||||
|
||||
function schedulePoll() {
|
||||
if (pollTimer !== null || !items.some(needsParsePolling)) return
|
||||
pollTimer = setTimer(() => {
|
||||
pollTimer = null
|
||||
void pollNow()
|
||||
}, deps.pollIntervalMs)
|
||||
}
|
||||
|
||||
const pollNow = async () => {
|
||||
const startedIn = generation
|
||||
const byKb = new Map<string, UploadItem[]>()
|
||||
for (const item of items) {
|
||||
const kbId = needsParsePolling(item) ? batchOf(item)?.kbId : undefined
|
||||
if (!kbId) continue
|
||||
if (!byKb.has(kbId)) byKb.set(kbId, [])
|
||||
byKb.get(kbId)!.push(item)
|
||||
}
|
||||
|
||||
const chunks: Array<{ kbId: string; chunk: UploadItem[] }> = []
|
||||
for (const [kbId, group] of byKb) {
|
||||
for (let i = 0; i < group.length; i += deps.pollChunkSize) {
|
||||
chunks.push({ kbId, chunk: group.slice(i, i + deps.pollChunkSize) })
|
||||
}
|
||||
}
|
||||
|
||||
const queryChunk = async ({ kbId, chunk }: { kbId: string; chunk: UploadItem[] }) => {
|
||||
const rows = await deps.queryStatus(kbId, chunk.map(item => item.knowledgeId!)).catch(() => null)
|
||||
// A failed request just waits for the next tick.
|
||||
if (!rows || startedIn !== generation) return
|
||||
const byId = new Map(rows.map(row => [row.id, row]))
|
||||
for (const item of chunk) {
|
||||
const row = byId.get(item.knowledgeId!)
|
||||
if (!row) {
|
||||
const misses = (missingPolls.get(item.id) ?? 0) + 1
|
||||
missingPolls.set(item.id, misses)
|
||||
if (misses >= MISSING_POLLS_BEFORE_DELETED) item.parseStatus = 'deleted'
|
||||
continue
|
||||
}
|
||||
missingPolls.delete(item.id)
|
||||
item.parseStatus = row.parse_status
|
||||
item.parseError = row.error_message || undefined
|
||||
}
|
||||
}
|
||||
|
||||
let next = 0
|
||||
const worker = async () => {
|
||||
while (next < chunks.length && startedIn === generation) await queryChunk(chunks[next++])
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(Math.max(1, deps.pollConcurrency), chunks.length) }, worker))
|
||||
if (startedIn === generation) schedulePoll()
|
||||
}
|
||||
|
||||
// ---- lifecycle ----------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Forget everything. Transfers still sending are aborted; ones whose body is
|
||||
* fully sent are left to finish, since the server stores them regardless.
|
||||
*/
|
||||
const clear = () => {
|
||||
generation++
|
||||
for (const item of items) {
|
||||
if (itemPhase(item) !== 'saving') controllers.get(item.id)?.abort()
|
||||
}
|
||||
const busyKbs = new Set(items.filter(item => item.transfer === 'queued' || item.transfer === 'uploading')
|
||||
.map(item => batchOf(item)?.kbId)
|
||||
.filter((kbId): kbId is string => !!kbId))
|
||||
controllers.clear()
|
||||
payloads.clear()
|
||||
missingPolls.clear()
|
||||
items.splice(0)
|
||||
batches.splice(0)
|
||||
if (pollTimer !== null) {
|
||||
clearTimer(pollTimer)
|
||||
pollTimer = null
|
||||
}
|
||||
// Files that landed before the clear may still be waiting for a refresh.
|
||||
for (const kbId of busyKbs) deps.onTransferEnd(kbId, { uploaded: false, settled: true })
|
||||
}
|
||||
|
||||
return { add, cancel, cancelAll, retry, retryFailed, pruneFinished, pollNow, clear }
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns transfer ends into `knowledgeFileUploaded` refreshes: while a knowledge
|
||||
* base still has work queued, at most one mid-batch (`settled: false`) refresh
|
||||
* per `intervalMs`; once it settles, a single final (`settled: true`) one.
|
||||
* Ends that settle within `coalesceMs` of each other (cancel-all aborting
|
||||
* several requests) produce one final refresh.
|
||||
*/
|
||||
export function createListRefreshThrottle(
|
||||
emit: (kbId: string, settled: boolean) => void,
|
||||
intervalMs: number,
|
||||
coalesceMs: number,
|
||||
timers: Timers = defaultTimers,
|
||||
) {
|
||||
const throttles = new Map<string, unknown>()
|
||||
const pending = new Set<string>()
|
||||
const finals = new Map<string, unknown>()
|
||||
|
||||
return (kbId: string, end: TransferEnd) => {
|
||||
if (end.settled) {
|
||||
const throttle = throttles.get(kbId)
|
||||
if (throttle !== undefined) timers.clearTimer(throttle)
|
||||
throttles.delete(kbId)
|
||||
pending.delete(kbId)
|
||||
if (finals.has(kbId)) return
|
||||
finals.set(kbId, timers.setTimer(() => {
|
||||
finals.delete(kbId)
|
||||
emit(kbId, true)
|
||||
}, coalesceMs))
|
||||
return
|
||||
}
|
||||
if (!end.uploaded) return
|
||||
if (throttles.has(kbId)) {
|
||||
pending.add(kbId)
|
||||
return
|
||||
}
|
||||
emit(kbId, false)
|
||||
const tick = () => {
|
||||
if (pending.delete(kbId)) {
|
||||
emit(kbId, false)
|
||||
throttles.set(kbId, timers.setTimer(tick, intervalMs))
|
||||
} else {
|
||||
throttles.delete(kbId)
|
||||
}
|
||||
}
|
||||
throttles.set(kbId, timers.setTimer(tick, intervalMs))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { batchQueryKnowledge, uploadKnowledgeFile } from '@/api/knowledge-base/index'
|
||||
import { useAuthStore } from './auth'
|
||||
import type { KnowledgeStatusRow } from './uploadQueue'
|
||||
import { createUploadTasks } from './uploadTasksCore'
|
||||
|
||||
export type { UploadBatch } from './uploadQueue'
|
||||
export type { EnqueueUploadsInput } from './uploadTasksCore'
|
||||
|
||||
/**
|
||||
* Knowledge file uploads behind the floating progress panel
|
||||
* (components/upload-tasks/UploadTasksPanel.vue). Lives in a store rather than
|
||||
* the knowledge base page so uploads keep going, and stay visible, when the
|
||||
* user navigates elsewhere in the app. Behaviour is in uploadTasksCore.ts and
|
||||
* uploadQueue.ts; this file only connects it to the API and the page.
|
||||
*/
|
||||
export const useUploadTasksStore = defineStore('uploadTasks', () => {
|
||||
const auth = useAuthStore()
|
||||
|
||||
return createUploadTasks({
|
||||
upload: (batch, payload, onProgress, signal) => uploadKnowledgeFile(
|
||||
batch.kbId,
|
||||
{
|
||||
file: payload.file,
|
||||
fileName: payload.fileName,
|
||||
tag_ids: batch.tagIds,
|
||||
process_config: batch.processConfig,
|
||||
},
|
||||
(event: { loaded?: number; total?: number; progress?: number }) => {
|
||||
onProgress(event.progress ?? (event.total ? (event.loaded ?? 0) / event.total : 0))
|
||||
},
|
||||
{ signal },
|
||||
),
|
||||
queryStatus: async (kbId, knowledgeIds) => {
|
||||
const query = knowledgeIds.map(id => `ids=${encodeURIComponent(id)}`).join('&')
|
||||
try {
|
||||
const result: any = await batchQueryKnowledge(query, kbId)
|
||||
return result?.success && Array.isArray(result.data) ? (result.data as KnowledgeStatusRow[]) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
},
|
||||
emitListRefresh: (kbId, settled) => {
|
||||
window.dispatchEvent(new CustomEvent('knowledgeFileUploaded', { detail: { kbId, settled } }))
|
||||
},
|
||||
owner: [() => auth.user?.id, () => auth.effectiveTenantId],
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,69 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { ref } from 'vue'
|
||||
import type { Timers, UploadBatch, UploadPayload } from './uploadQueue.ts'
|
||||
import { createUploadTasks } from './uploadTasksCore.ts'
|
||||
|
||||
type Call = { batch: UploadBatch; payload: UploadPayload; signal: AbortSignal; resolve: (v: unknown) => void; reject: (r: unknown) => void }
|
||||
|
||||
const file = (name: string, size = 100) => ({ name, size, webkitRelativePath: '' }) as unknown as File
|
||||
const flush = () => new Promise(resolve => setImmediate(resolve))
|
||||
const noTimers: Timers = { setTimer: () => ({}), clearTimer: () => {} }
|
||||
|
||||
function setup() {
|
||||
const user = ref<{ id: string; nickname?: string } | null>({ id: 'u1' })
|
||||
const tenant = ref(1)
|
||||
const calls: Call[] = []
|
||||
const tasks = createUploadTasks({
|
||||
upload: (batch, payload, _progress, signal) => new Promise((resolve, reject) => {
|
||||
calls.push({ batch, payload, signal, resolve, reject })
|
||||
signal.addEventListener('abort', () => reject({ message: 'Network error' }))
|
||||
}),
|
||||
queryStatus: async () => [],
|
||||
emitListRefresh: () => {},
|
||||
owner: [() => user.value?.id, () => tenant.value],
|
||||
timers: noTimers,
|
||||
})
|
||||
const enqueue = (name: string, size = 100) =>
|
||||
tasks.enqueue({ kbId: 'kb1', kbName: 'KB', uploads: [{ file: file(name, size) }] })
|
||||
return { user, tenant, calls, tasks, enqueue }
|
||||
}
|
||||
|
||||
test('replacing the user object for the same person keeps uploads running', () => {
|
||||
const { user, tenant, calls, tasks, enqueue } = setup()
|
||||
enqueue('a')
|
||||
// What setUser() does on every /auth/me refresh.
|
||||
user.value = { id: 'u1', nickname: 'refreshed' }
|
||||
assert.equal(tasks.items.length, 1)
|
||||
assert.equal(calls[0].signal.aborted, false)
|
||||
assert.equal(tasks.visible.value, true)
|
||||
|
||||
tenant.value = 2
|
||||
assert.equal(tasks.items.length, 0)
|
||||
assert.equal(calls[0].signal.aborted, true)
|
||||
assert.equal(tasks.visible.value, false)
|
||||
})
|
||||
|
||||
test('a new batch keeps an earlier batch that still has failures to retry', async () => {
|
||||
const { calls, tasks, enqueue } = setup()
|
||||
enqueue('broken', 1)
|
||||
calls[0].reject({ status: 500, message: 'boom' })
|
||||
await flush()
|
||||
assert.equal(tasks.summary.value.stage, 'done')
|
||||
|
||||
enqueue('next', 2)
|
||||
assert.deepEqual(tasks.items.map(item => item.name), ['broken', 'next'])
|
||||
tasks.retryItem(tasks.items[0].id)
|
||||
assert.equal(calls.at(-1)!.payload.file.name, 'broken')
|
||||
})
|
||||
|
||||
test('a new batch drops earlier batches that finished cleanly', async () => {
|
||||
const { calls, tasks, enqueue } = setup()
|
||||
enqueue('done', 1)
|
||||
calls[0].resolve({ success: true, data: { id: 'k1', parse_status: 'completed' } })
|
||||
await flush()
|
||||
|
||||
enqueue('next', 2)
|
||||
assert.deepEqual(tasks.items.map(item => item.name), ['next'])
|
||||
assert.equal(tasks.batches.length, 1)
|
||||
})
|
||||
@@ -0,0 +1,128 @@
|
||||
import { computed, reactive, ref, watch, type WatchSource } from 'vue'
|
||||
import type { KnowledgeProcessOverrides } from '@/types/knowledgeProcess'
|
||||
import {
|
||||
createListRefreshThrottle,
|
||||
createUploadQueue,
|
||||
defaultTimers,
|
||||
type Timers,
|
||||
type UploadBatch,
|
||||
type UploadPayload,
|
||||
type UploadQueueDeps,
|
||||
} from './uploadQueue'
|
||||
import { summarizeItems, type UploadItem } from './uploadTasksState'
|
||||
|
||||
/**
|
||||
* Everything the uploadTasks store does, with the API, page events and the
|
||||
* signed-in identity injected so it runs (and is tested) without the app.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Parallel transfers. The server hashes and stores every file before it
|
||||
* answers, so a small number keeps the pipe full without piling work on it.
|
||||
*/
|
||||
const CONCURRENCY = 3
|
||||
const POLL_INTERVAL_MS = 3000
|
||||
/** Keeps the ids=… query string of one status request well under URL length limits. */
|
||||
const POLL_CHUNK_SIZE = 40
|
||||
/** Status requests in flight per poll; each holds a database connection on the server. */
|
||||
const POLL_CONCURRENCY = 4
|
||||
/** Minimum gap between mid-batch list refreshes pushed to an open page. */
|
||||
const LIST_REFRESH_INTERVAL_MS = 2000
|
||||
/** Batch ends this close together produce one final refresh. */
|
||||
const LIST_REFRESH_COALESCE_MS = 150
|
||||
|
||||
export interface EnqueueUploadsInput {
|
||||
kbId: string
|
||||
kbName: string
|
||||
targetFolder?: string
|
||||
tagIds?: string[]
|
||||
processConfig?: KnowledgeProcessOverrides
|
||||
uploads: UploadPayload[]
|
||||
}
|
||||
|
||||
export interface UploadTasksDeps {
|
||||
upload: UploadQueueDeps['upload']
|
||||
queryStatus: UploadQueueDeps['queryStatus']
|
||||
/** Ask an open knowledge base page or list to reload; `settled` marks a batch's last one. */
|
||||
emitListRefresh: (kbId: string, settled: boolean) => void
|
||||
/**
|
||||
* Who the uploads belong to, as getters of primitive ids. Changing any of
|
||||
* them drops the queue.
|
||||
*/
|
||||
owner: WatchSource<unknown>[]
|
||||
timers?: Timers
|
||||
}
|
||||
|
||||
export function createUploadTasks(deps: UploadTasksDeps) {
|
||||
const items = reactive<UploadItem[]>([])
|
||||
const batches = reactive<UploadBatch[]>([])
|
||||
const visible = ref(false)
|
||||
const collapsed = ref(false)
|
||||
const timers = deps.timers ?? defaultTimers
|
||||
|
||||
const summary = computed(() => summarizeItems(items))
|
||||
const batchById = computed(() => new Map(batches.map(batch => [batch.id, batch])))
|
||||
|
||||
const queue = createUploadQueue(items, batches, {
|
||||
concurrency: CONCURRENCY,
|
||||
pollIntervalMs: POLL_INTERVAL_MS,
|
||||
pollChunkSize: POLL_CHUNK_SIZE,
|
||||
pollConcurrency: POLL_CONCURRENCY,
|
||||
upload: deps.upload,
|
||||
queryStatus: deps.queryStatus,
|
||||
onTransferEnd: createListRefreshThrottle(
|
||||
deps.emitListRefresh,
|
||||
LIST_REFRESH_INTERVAL_MS,
|
||||
LIST_REFRESH_COALESCE_MS,
|
||||
timers,
|
||||
),
|
||||
timers,
|
||||
})
|
||||
|
||||
const enqueue = (input: EnqueueUploadsInput) => {
|
||||
if (!input.kbId || input.uploads.length === 0) return
|
||||
// Batches that finished cleanly have nothing left to show; ones with
|
||||
// failures stay so their files can still be retried.
|
||||
queue.pruneFinished()
|
||||
queue.add({
|
||||
kbId: input.kbId,
|
||||
kbName: input.kbName,
|
||||
targetFolder: input.targetFolder || '',
|
||||
tagIds: input.tagIds && input.tagIds.length > 0 ? [...input.tagIds] : undefined,
|
||||
processConfig: input.processConfig,
|
||||
}, input.uploads)
|
||||
visible.value = true
|
||||
collapsed.value = false
|
||||
}
|
||||
|
||||
/** Hide the panel and forget every task, cancelling transfers still sending. */
|
||||
const dismiss = () => {
|
||||
queue.clear()
|
||||
visible.value = false
|
||||
}
|
||||
|
||||
const toggleCollapsed = () => {
|
||||
collapsed.value = !collapsed.value
|
||||
}
|
||||
|
||||
// Uploads belong to the account and space they were started in. The ids are
|
||||
// separate watch sources on purpose: one getter returning a fresh array would
|
||||
// fire on every setUser(), even for the same person, and kill running uploads.
|
||||
watch(deps.owner, dismiss, { flush: 'sync' })
|
||||
|
||||
return {
|
||||
items,
|
||||
batches,
|
||||
visible,
|
||||
collapsed,
|
||||
summary,
|
||||
batchById,
|
||||
enqueue,
|
||||
cancelItem: queue.cancel,
|
||||
cancelAll: queue.cancelAll,
|
||||
retryItem: queue.retry,
|
||||
retryFailed: queue.retryFailed,
|
||||
dismiss,
|
||||
toggleCollapsed,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
classifyUploadResult,
|
||||
estimateRate,
|
||||
estimateRemainingSeconds,
|
||||
itemPhase,
|
||||
needsParsePolling,
|
||||
pickNextToStart,
|
||||
splitDuration,
|
||||
summarizeItems,
|
||||
type UploadItem,
|
||||
} from './uploadTasksState.ts'
|
||||
|
||||
let seq = 0
|
||||
const item = (patch: Partial<UploadItem> = {}): UploadItem => ({
|
||||
id: `item-${seq++}`,
|
||||
batchId: 'batch',
|
||||
name: 'a.pdf',
|
||||
relativePath: '',
|
||||
size: 100,
|
||||
loaded: 0,
|
||||
transfer: 'queued',
|
||||
...patch,
|
||||
})
|
||||
|
||||
test('itemPhase folds transfer and parse state into one row status', () => {
|
||||
assert.equal(itemPhase(item()), 'waiting')
|
||||
assert.equal(itemPhase(item({ transfer: 'uploading', loaded: 40 })), 'uploading')
|
||||
assert.equal(itemPhase(item({ transfer: 'uploading', loaded: 100 })), 'saving')
|
||||
assert.equal(itemPhase(item({ transfer: 'uploaded', parseStatus: 'pending' })), 'parsing')
|
||||
assert.equal(itemPhase(item({ transfer: 'uploaded', parseStatus: 'processing' })), 'parsing')
|
||||
// finalizing is already searchable, so it counts as ready.
|
||||
assert.equal(itemPhase(item({ transfer: 'uploaded', parseStatus: 'finalizing' })), 'ready')
|
||||
assert.equal(itemPhase(item({ transfer: 'uploaded', parseStatus: 'completed' })), 'ready')
|
||||
assert.equal(itemPhase(item({ transfer: 'uploaded', parseStatus: 'failed' })), 'failed')
|
||||
assert.equal(itemPhase(item({ transfer: 'uploaded', parseStatus: 'deleted' })), 'cancelled')
|
||||
assert.equal(itemPhase(item({ transfer: 'failed' })), 'failed')
|
||||
assert.equal(itemPhase(item({ transfer: 'duplicate' })), 'duplicate')
|
||||
assert.equal(itemPhase(item({ transfer: 'cancelled' })), 'cancelled')
|
||||
})
|
||||
|
||||
test('needsParsePolling keeps watching until the row leaves finalizing', () => {
|
||||
assert.equal(needsParsePolling(item({ transfer: 'uploaded', knowledgeId: 'k', parseStatus: 'pending' })), true)
|
||||
assert.equal(needsParsePolling(item({ transfer: 'uploaded', knowledgeId: 'k', parseStatus: 'finalizing' })), true)
|
||||
assert.equal(needsParsePolling(item({ transfer: 'uploaded', knowledgeId: 'k', parseStatus: 'completed' })), false)
|
||||
assert.equal(needsParsePolling(item({ transfer: 'uploaded', parseStatus: 'pending' })), false)
|
||||
assert.equal(needsParsePolling(item({ transfer: 'duplicate', knowledgeId: 'k' })), false)
|
||||
})
|
||||
|
||||
test('summarizeItems reports the uploading stage while anything is queued or in flight', () => {
|
||||
const summary = summarizeItems([
|
||||
item({ transfer: 'uploaded', parseStatus: 'completed' }),
|
||||
item({ transfer: 'uploading', loaded: 50 }),
|
||||
item(),
|
||||
item({ transfer: 'failed' }),
|
||||
])
|
||||
assert.equal(summary.stage, 'uploading')
|
||||
assert.equal(summary.transferSettled, 2)
|
||||
assert.equal(summary.transferTotal, 4)
|
||||
assert.equal(summary.loadedBytes, 250)
|
||||
// The failed file is settled for the remaining-bytes estimate but never counts as sent.
|
||||
assert.equal(summary.sentBytes, 150)
|
||||
assert.equal(summary.totalBytes, 400)
|
||||
assert.equal(summary.retryable, 1)
|
||||
assert.deepEqual(summary.bar, { ready: 0.25, active: 0.125, failed: 0.25, duplicate: 0 })
|
||||
})
|
||||
|
||||
test('summarizeItems moves to parsing once every transfer settled, then to done', () => {
|
||||
const parsing = summarizeItems([
|
||||
item({ transfer: 'uploaded', parseStatus: 'processing' }),
|
||||
item({ transfer: 'uploaded', parseStatus: 'finalizing' }),
|
||||
item({ transfer: 'duplicate' }),
|
||||
])
|
||||
assert.equal(parsing.stage, 'parsing')
|
||||
assert.equal(parsing.uploaded, 2)
|
||||
assert.equal(parsing.parsing, 1)
|
||||
assert.equal(parsing.ready, 1)
|
||||
|
||||
const done = summarizeItems([
|
||||
item({ transfer: 'uploaded', parseStatus: 'completed' }),
|
||||
item({ transfer: 'uploaded', parseStatus: 'failed' }),
|
||||
])
|
||||
assert.equal(done.stage, 'done')
|
||||
assert.equal(done.failed, 1)
|
||||
// A parse failure cannot be retried by uploading again.
|
||||
assert.equal(done.retryable, 0)
|
||||
})
|
||||
|
||||
test('cancelled transfers leave the bar denominator and byte totals', () => {
|
||||
const summary = summarizeItems([
|
||||
item({ transfer: 'uploaded', parseStatus: 'completed' }),
|
||||
item({ transfer: 'cancelled' }),
|
||||
])
|
||||
assert.equal(summary.stage, 'done')
|
||||
assert.equal(summary.transferTotal, 1)
|
||||
assert.equal(summary.totalBytes, 100)
|
||||
assert.equal(summary.retryable, 1)
|
||||
assert.equal(summary.bar.ready, 1)
|
||||
})
|
||||
|
||||
test('pickNextToStart fills free slots in queue order', () => {
|
||||
const items = [
|
||||
item({ transfer: 'uploading' }),
|
||||
item({ transfer: 'uploaded' }),
|
||||
item({ id: 'q1' }),
|
||||
item({ id: 'q2' }),
|
||||
item({ id: 'q3' }),
|
||||
]
|
||||
assert.deepEqual(pickNextToStart(items, 3).map(i => i.id), ['q1', 'q2'])
|
||||
assert.deepEqual(pickNextToStart(items, 1), [])
|
||||
})
|
||||
|
||||
test('pickNextToStart skips items whose conflict key is already in flight', () => {
|
||||
const items = [
|
||||
item({ transfer: 'uploading', size: 10 }),
|
||||
item({ id: 'same-as-running', size: 10 }),
|
||||
item({ id: 'first-of-pair', size: 20 }),
|
||||
item({ id: 'second-of-pair', size: 20 }),
|
||||
item({ id: 'free', size: 30 }),
|
||||
]
|
||||
const bySize = (i: UploadItem) => String(i.size)
|
||||
assert.deepEqual(pickNextToStart(items, 3, bySize).map(i => i.id), ['first-of-pair', 'free'])
|
||||
})
|
||||
|
||||
test('classifyUploadResult reads success, duplicate rejections and failures', () => {
|
||||
assert.deepEqual(
|
||||
classifyUploadResult({ success: true, data: { id: 'k1', parse_status: 'pending' } }),
|
||||
{ kind: 'uploaded', knowledgeId: 'k1', parseStatus: 'pending' },
|
||||
)
|
||||
assert.deepEqual(
|
||||
classifyUploadResult({ status: 409, success: false, code: 'duplicate_file', message: 'exists', data: { id: 'k0' } }),
|
||||
{ kind: 'duplicate', knowledgeId: 'k0', message: 'exists' },
|
||||
)
|
||||
assert.deepEqual(
|
||||
classifyUploadResult({ status: 400, success: false, error: { code: 'bad', message: 'too large' } }),
|
||||
{ kind: 'failed', message: 'too large' },
|
||||
)
|
||||
assert.deepEqual(classifyUploadResult({ message: 'Network error' }), { kind: 'failed', message: 'Network error' })
|
||||
assert.deepEqual(classifyUploadResult(undefined), { kind: 'failed', message: undefined })
|
||||
})
|
||||
|
||||
test('estimateRate waits for a one second window and ignores stale samples', () => {
|
||||
assert.equal(estimateRate([{ at: 0, bytes: 0 }, { at: 500, bytes: 1000 }]), 0)
|
||||
assert.equal(estimateRate([{ at: 0, bytes: 0 }, { at: 2000, bytes: 4000 }]), 2000)
|
||||
const samples = [
|
||||
{ at: 0, bytes: 0 },
|
||||
{ at: 10_000, bytes: 100_000 },
|
||||
{ at: 12_000, bytes: 104_000 },
|
||||
]
|
||||
assert.equal(estimateRate(samples, 8000), 2000)
|
||||
})
|
||||
|
||||
test('remaining time is rounded into a stable unit', () => {
|
||||
assert.equal(estimateRemainingSeconds(1000, 0), null)
|
||||
assert.equal(estimateRemainingSeconds(0, 100), null)
|
||||
assert.equal(estimateRemainingSeconds(1000, 300), 4)
|
||||
assert.deepEqual(splitDuration(4), { unit: 'seconds', value: 5 })
|
||||
assert.deepEqual(splitDuration(41), { unit: 'seconds', value: 45 })
|
||||
assert.deepEqual(splitDuration(57), { unit: 'minutes', value: 1 })
|
||||
assert.deepEqual(splitDuration(610), { unit: 'minutes', value: 11 })
|
||||
assert.deepEqual(splitDuration(5400), { unit: 'hours', value: 1.5 })
|
||||
})
|
||||
@@ -0,0 +1,271 @@
|
||||
/**
|
||||
* Framework-free rules behind the knowledge upload queue (stores/uploadTasks.ts):
|
||||
* how an item's transfer and parse states fold into one display phase, how a
|
||||
* set of items summarises into the panel header, and which queued items may
|
||||
* start next. Kept pure so the store stays a thin reactive shell over them.
|
||||
*/
|
||||
|
||||
/** Client-side life of one file's HTTP upload. */
|
||||
export type TransferStatus = 'queued' | 'uploading' | 'uploaded' | 'failed' | 'duplicate' | 'cancelled'
|
||||
|
||||
export interface UploadItem {
|
||||
id: string
|
||||
batchId: string
|
||||
name: string
|
||||
/** webkitRelativePath for folder uploads, '' otherwise. */
|
||||
relativePath: string
|
||||
size: number
|
||||
/** Bytes of the file body sent so far, scaled from the multipart progress. */
|
||||
loaded: number
|
||||
transfer: TransferStatus
|
||||
/** Transfer failure reason. */
|
||||
error?: string
|
||||
/** Knowledge created by this upload, or the existing one for a duplicate. */
|
||||
knowledgeId?: string
|
||||
/** Backend parse_status once uploaded; 'deleted' when the row disappeared. */
|
||||
parseStatus?: string
|
||||
parseError?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* One status per row, combining both stages. `saving` is the gap between the
|
||||
* last request byte leaving the browser and the response arriving, while the
|
||||
* server hashes and stores the file.
|
||||
*/
|
||||
export type ItemPhase =
|
||||
| 'waiting'
|
||||
| 'uploading'
|
||||
| 'saving'
|
||||
| 'parsing'
|
||||
| 'ready'
|
||||
| 'failed'
|
||||
| 'duplicate'
|
||||
| 'cancelled'
|
||||
|
||||
export type UploadStage = 'uploading' | 'parsing' | 'done'
|
||||
|
||||
export function itemPhase(item: UploadItem): ItemPhase {
|
||||
switch (item.transfer) {
|
||||
case 'queued':
|
||||
return 'waiting'
|
||||
case 'uploading':
|
||||
return item.size > 0 && item.loaded >= item.size ? 'saving' : 'uploading'
|
||||
case 'failed':
|
||||
return 'failed'
|
||||
case 'duplicate':
|
||||
return 'duplicate'
|
||||
case 'cancelled':
|
||||
return 'cancelled'
|
||||
}
|
||||
switch (item.parseStatus) {
|
||||
// finalizing means the document is already searchable; summary / question /
|
||||
// graph enrichment keeps running in the background.
|
||||
case 'finalizing':
|
||||
case 'completed':
|
||||
return 'ready'
|
||||
case 'failed':
|
||||
return 'failed'
|
||||
case 'cancelled':
|
||||
case 'deleting':
|
||||
case 'deleted':
|
||||
return 'cancelled'
|
||||
default:
|
||||
return 'parsing'
|
||||
}
|
||||
}
|
||||
|
||||
/** Parse states the panel keeps polling. finalizing is polled so the row can settle on completed. */
|
||||
export function needsParsePolling(item: UploadItem): boolean {
|
||||
if (item.transfer !== 'uploaded' || !item.knowledgeId) return false
|
||||
const status = item.parseStatus
|
||||
return !status || status === 'pending' || status === 'processing' || status === 'finalizing'
|
||||
}
|
||||
|
||||
export interface UploadSummary {
|
||||
total: number
|
||||
waiting: number
|
||||
/** Includes `saving`. */
|
||||
uploading: number
|
||||
parsing: number
|
||||
ready: number
|
||||
failed: number
|
||||
duplicate: number
|
||||
cancelled: number
|
||||
/** Items whose transfer settled (uploaded, failed or duplicate). */
|
||||
transferSettled: number
|
||||
/** Items still meant to be transferred (everything except transfer-cancelled). */
|
||||
transferTotal: number
|
||||
/** Items that reached the server. */
|
||||
uploaded: number
|
||||
totalBytes: number
|
||||
/** Bytes no longer waiting to be sent: settled items in full plus in-flight progress. */
|
||||
loadedBytes: number
|
||||
/**
|
||||
* Bytes that actually crossed the wire to a live or successful request. Unlike
|
||||
* loadedBytes it never jumps when a file fails, so it is what speed is measured on.
|
||||
*/
|
||||
sentBytes: number
|
||||
/** Failed or cancelled transfers that can be queued again. */
|
||||
retryable: number
|
||||
stage: UploadStage
|
||||
/** Stacked progress bar widths, each 0..1 of the non-cancelled items. */
|
||||
bar: { ready: number; active: number; failed: number; duplicate: number }
|
||||
}
|
||||
|
||||
export function summarizeItems(items: readonly UploadItem[]): UploadSummary {
|
||||
const summary: UploadSummary = {
|
||||
total: items.length,
|
||||
waiting: 0,
|
||||
uploading: 0,
|
||||
parsing: 0,
|
||||
ready: 0,
|
||||
failed: 0,
|
||||
duplicate: 0,
|
||||
cancelled: 0,
|
||||
transferSettled: 0,
|
||||
transferTotal: 0,
|
||||
uploaded: 0,
|
||||
totalBytes: 0,
|
||||
loadedBytes: 0,
|
||||
sentBytes: 0,
|
||||
retryable: 0,
|
||||
stage: 'done',
|
||||
bar: { ready: 0, active: 0, failed: 0, duplicate: 0 },
|
||||
}
|
||||
let inFlightUnits = 0
|
||||
|
||||
for (const item of items) {
|
||||
const phase = itemPhase(item)
|
||||
switch (phase) {
|
||||
case 'waiting':
|
||||
summary.waiting++
|
||||
break
|
||||
case 'uploading':
|
||||
case 'saving':
|
||||
summary.uploading++
|
||||
if (item.size > 0) inFlightUnits += Math.min(1, item.loaded / item.size)
|
||||
break
|
||||
default:
|
||||
summary[phase]++
|
||||
}
|
||||
|
||||
if (item.transfer === 'cancelled') {
|
||||
summary.retryable++
|
||||
continue
|
||||
}
|
||||
summary.transferTotal++
|
||||
summary.totalBytes += item.size
|
||||
if (item.transfer === 'uploaded' || item.transfer === 'failed' || item.transfer === 'duplicate') {
|
||||
summary.transferSettled++
|
||||
summary.loadedBytes += item.size
|
||||
if (item.transfer !== 'failed') summary.sentBytes += item.size
|
||||
} else if (item.transfer === 'uploading') {
|
||||
summary.loadedBytes += Math.min(item.loaded, item.size)
|
||||
summary.sentBytes += Math.min(item.loaded, item.size)
|
||||
}
|
||||
if (item.transfer === 'uploaded') summary.uploaded++
|
||||
if (item.transfer === 'failed') summary.retryable++
|
||||
}
|
||||
|
||||
if (summary.waiting + summary.uploading > 0) summary.stage = 'uploading'
|
||||
else if (summary.parsing > 0) summary.stage = 'parsing'
|
||||
|
||||
const denominator = summary.total - summary.cancelled
|
||||
if (denominator > 0) {
|
||||
summary.bar = {
|
||||
ready: summary.ready / denominator,
|
||||
active: (summary.parsing + inFlightUnits) / denominator,
|
||||
failed: summary.failed / denominator,
|
||||
duplicate: summary.duplicate / denominator,
|
||||
}
|
||||
}
|
||||
return summary
|
||||
}
|
||||
|
||||
/**
|
||||
* Queued items to start now so that no more than `concurrency` transfers run
|
||||
* at once. Items sharing a `conflictKey` with a running or just-picked item
|
||||
* wait their turn, and the next free slot goes to a later item instead.
|
||||
*/
|
||||
export function pickNextToStart<T extends UploadItem>(
|
||||
items: readonly T[],
|
||||
concurrency: number,
|
||||
conflictKey?: (item: T) => string,
|
||||
): T[] {
|
||||
let running = 0
|
||||
const busyKeys = new Set<string>()
|
||||
for (const item of items) {
|
||||
if (item.transfer !== 'uploading') continue
|
||||
running++
|
||||
if (conflictKey) busyKeys.add(conflictKey(item))
|
||||
}
|
||||
const picked: T[] = []
|
||||
for (const item of items) {
|
||||
if (running >= concurrency) break
|
||||
if (item.transfer !== 'queued') continue
|
||||
const key = conflictKey?.(item)
|
||||
if (key !== undefined) {
|
||||
if (busyKeys.has(key)) continue
|
||||
busyKeys.add(key)
|
||||
}
|
||||
picked.push(item)
|
||||
running++
|
||||
}
|
||||
return picked
|
||||
}
|
||||
|
||||
export type UploadOutcome =
|
||||
| { kind: 'uploaded'; knowledgeId?: string; parseStatus?: string }
|
||||
| { kind: 'duplicate'; knowledgeId?: string; message?: string }
|
||||
| { kind: 'failed'; message?: string }
|
||||
|
||||
/**
|
||||
* Classify a resolved or rejected upload call. request.ts rejects non-2xx
|
||||
* responses with the JSON body spread over `{ status, message }`, so a 409
|
||||
* duplicate arrives as a rejection carrying `code` and the existing row in `data`.
|
||||
*/
|
||||
export function classifyUploadResult(result: any): UploadOutcome {
|
||||
const code = result?.code ?? result?.error?.code
|
||||
if (code === 'duplicate_file') {
|
||||
return { kind: 'duplicate', knowledgeId: result?.data?.id, message: result?.message }
|
||||
}
|
||||
if (result?.success === true) {
|
||||
return { kind: 'uploaded', knowledgeId: result?.data?.id, parseStatus: result?.data?.parse_status }
|
||||
}
|
||||
return { kind: 'failed', message: result?.error?.message || result?.message }
|
||||
}
|
||||
|
||||
export interface RateSample {
|
||||
at: number
|
||||
bytes: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Bytes per second over the samples inside `windowMs` of the newest one.
|
||||
* Returns 0 until the window spans at least one second, so a first burst of
|
||||
* buffered progress events doesn't produce a wildly optimistic ETA.
|
||||
*/
|
||||
export function estimateRate(samples: readonly RateSample[], windowMs = 8000): number {
|
||||
if (samples.length < 2) return 0
|
||||
const newest = samples[samples.length - 1]
|
||||
const oldest = samples.find(sample => newest.at - sample.at <= windowMs) ?? newest
|
||||
const elapsed = newest.at - oldest.at
|
||||
if (elapsed < 1000) return 0
|
||||
return Math.max(0, (newest.bytes - oldest.bytes) / (elapsed / 1000))
|
||||
}
|
||||
|
||||
/** Remaining seconds, or null when there is no usable rate yet. */
|
||||
export function estimateRemainingSeconds(remainingBytes: number, bytesPerSecond: number): number | null {
|
||||
if (bytesPerSecond <= 0 || remainingBytes <= 0) return null
|
||||
return Math.ceil(remainingBytes / bytesPerSecond)
|
||||
}
|
||||
|
||||
/**
|
||||
* The coarse unit an ETA is read in. Seconds round up to 5 so the number
|
||||
* doesn't flicker every tick; hours keep one decimal.
|
||||
*/
|
||||
export function splitDuration(seconds: number): { unit: 'seconds' | 'minutes' | 'hours'; value: number } {
|
||||
if (seconds <= 55) return { unit: 'seconds', value: Math.max(5, Math.ceil(seconds / 5) * 5) }
|
||||
if (seconds < 3600) return { unit: 'minutes', value: Math.ceil(seconds / 60) }
|
||||
return { unit: 'hours', value: Math.round(seconds / 360) / 10 }
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { createVersionedRequestCoordinator } from './versionedRequest.ts'
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
const promise = new Promise<T>((done) => {
|
||||
resolve = done
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
test('force queues a fresh request behind an existing request', async () => {
|
||||
const first = deferred<string>()
|
||||
const second = deferred<string>()
|
||||
const requests = [first, second]
|
||||
const applied: string[] = []
|
||||
let calls = 0
|
||||
const coordinator = createVersionedRequestCoordinator(
|
||||
() => requests[calls++].promise,
|
||||
value => applied.push(value)
|
||||
)
|
||||
|
||||
const initial = coordinator.fetch()
|
||||
const forced = coordinator.fetch(true)
|
||||
assert.equal(calls, 1)
|
||||
|
||||
first.resolve('old')
|
||||
await initial
|
||||
await new Promise<void>(resolve => queueMicrotask(resolve))
|
||||
assert.equal(calls, 2)
|
||||
|
||||
second.resolve('fresh')
|
||||
await forced
|
||||
assert.deepEqual(applied, ['old', 'fresh'])
|
||||
})
|
||||
|
||||
test('an invalidated older response cannot overwrite newer state', async () => {
|
||||
const first = deferred<string>()
|
||||
const second = deferred<string>()
|
||||
const requests = [first, second]
|
||||
const applied: string[] = []
|
||||
let calls = 0
|
||||
const coordinator = createVersionedRequestCoordinator(
|
||||
() => requests[calls++].promise,
|
||||
value => applied.push(value)
|
||||
)
|
||||
|
||||
const initial = coordinator.fetch()
|
||||
coordinator.invalidate()
|
||||
const forced = coordinator.fetch(true)
|
||||
|
||||
first.resolve('stale')
|
||||
await initial
|
||||
await new Promise<void>(resolve => queueMicrotask(resolve))
|
||||
second.resolve('fresh')
|
||||
await forced
|
||||
|
||||
assert.deepEqual(applied, ['fresh'])
|
||||
})
|
||||
|
||||
test('a newer force request extends an active force queue after invalidation', async () => {
|
||||
const first = deferred<string>()
|
||||
const second = deferred<string>()
|
||||
const third = deferred<string>()
|
||||
const requests = [first, second, third]
|
||||
const applied: string[] = []
|
||||
let calls = 0
|
||||
const coordinator = createVersionedRequestCoordinator(
|
||||
() => requests[calls++].promise,
|
||||
value => applied.push(value)
|
||||
)
|
||||
|
||||
void coordinator.fetch()
|
||||
const firstForce = coordinator.fetch(true)
|
||||
first.resolve('first')
|
||||
await new Promise<void>(resolve => queueMicrotask(resolve))
|
||||
|
||||
coordinator.invalidate()
|
||||
const secondForce = coordinator.fetch(true)
|
||||
second.resolve('stale-second')
|
||||
await new Promise<void>(resolve => queueMicrotask(resolve))
|
||||
assert.equal(calls, 3)
|
||||
|
||||
third.resolve('fresh-third')
|
||||
await Promise.all([firstForce, secondForce])
|
||||
assert.deepEqual(applied, ['first', 'fresh-third'])
|
||||
})
|
||||
@@ -0,0 +1,90 @@
|
||||
export interface VersionedRequestCoordinator<T> {
|
||||
fetch: (force?: boolean) => Promise<void>
|
||||
invalidate: () => void
|
||||
hasInFlightRequest: () => boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Coordinates cached reads that also need a reliable "force refresh" mode.
|
||||
*
|
||||
* A forced read requested while another read is running is queued after the
|
||||
* current request. Invalidating the coordinator also prevents an older
|
||||
* response from overwriting state changed by a newer write.
|
||||
*/
|
||||
export function createVersionedRequestCoordinator<T>(
|
||||
request: () => Promise<T>,
|
||||
apply: (value: T) => void
|
||||
): VersionedRequestCoordinator<T> {
|
||||
let revision = 0
|
||||
let startedSequence = 0
|
||||
let completedSequence = 0
|
||||
let forceTargetSequence = 0
|
||||
let inFlight: Promise<void> | null = null
|
||||
let forceQueue: Promise<void> | null = null
|
||||
|
||||
const start = (): Promise<void> => {
|
||||
const requestRevision = revision
|
||||
const sequence = ++startedSequence
|
||||
const current = (async () => {
|
||||
const value = await request()
|
||||
if (requestRevision === revision) {
|
||||
apply(value)
|
||||
}
|
||||
})()
|
||||
|
||||
inFlight = current
|
||||
void current.then(
|
||||
() => {
|
||||
completedSequence = Math.max(completedSequence, sequence)
|
||||
if (inFlight === current) inFlight = null
|
||||
},
|
||||
() => {
|
||||
completedSequence = Math.max(completedSequence, sequence)
|
||||
if (inFlight === current) inFlight = null
|
||||
}
|
||||
)
|
||||
return current
|
||||
}
|
||||
|
||||
const fetch = (force = false): Promise<void> => {
|
||||
if (!inFlight) return start()
|
||||
if (!force) return inFlight
|
||||
|
||||
// A force call always requires at least one request newer than the one
|
||||
// that was in flight when force was requested.
|
||||
forceTargetSequence = Math.max(forceTargetSequence, startedSequence + 1)
|
||||
if (!forceQueue) {
|
||||
const queued = (async () => {
|
||||
while (completedSequence < forceTargetSequence) {
|
||||
if (inFlight) {
|
||||
try {
|
||||
await inFlight
|
||||
} catch {
|
||||
// The queued forced request must still run after a failed read.
|
||||
}
|
||||
} else {
|
||||
await start()
|
||||
}
|
||||
}
|
||||
})()
|
||||
forceQueue = queued
|
||||
void queued.then(
|
||||
() => {
|
||||
if (forceQueue === queued) forceQueue = null
|
||||
},
|
||||
() => {
|
||||
if (forceQueue === queued) forceQueue = null
|
||||
}
|
||||
)
|
||||
}
|
||||
return forceQueue
|
||||
}
|
||||
|
||||
return {
|
||||
fetch,
|
||||
invalidate: () => {
|
||||
revision += 1
|
||||
},
|
||||
hasInFlightRequest: () => inFlight !== null
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user