fix(search): harden authorized results and ordering
This commit is contained in:
@@ -125,6 +125,19 @@ test('FormData body leaves Content-Type unset so fetch provides the boundary', a
|
||||
assert.equal(requestInit.headers['Content-Type'], undefined)
|
||||
})
|
||||
|
||||
test('request forwards its AbortSignal to fetch', async () => {
|
||||
let requestInit
|
||||
const controller = new AbortController()
|
||||
globalThis.fetch = async (_url, init) => {
|
||||
requestInit = init
|
||||
return Response.json({ ok: true })
|
||||
}
|
||||
|
||||
await apiRequest('/search', { signal: controller.signal })
|
||||
|
||||
assert.equal(requestInit.signal, controller.signal)
|
||||
})
|
||||
|
||||
test('base URL normalizer trims whitespace and all trailing slashes', () => {
|
||||
assert.equal(normalizeBaseUrl(' https://host.example/// '), 'https://host.example')
|
||||
})
|
||||
|
||||
41
apps/web_v1/scripts/search-request-gate.test.mjs
Normal file
41
apps/web_v1/scripts/search-request-gate.test.mjs
Normal file
@@ -0,0 +1,41 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { createSearchRequestGate } from '../src/app/search-request-gate.ts'
|
||||
|
||||
test('starting a new request aborts and invalidates the previous request', () => {
|
||||
const gate = createSearchRequestGate()
|
||||
const first = gate.begin()
|
||||
const second = gate.begin()
|
||||
|
||||
assert.equal(first.signal.aborted, true)
|
||||
assert.equal(first.isCurrent(), false)
|
||||
assert.equal(second.signal.aborted, false)
|
||||
assert.equal(second.isCurrent(), true)
|
||||
})
|
||||
|
||||
test('session cleanup aborts the request and suppresses its stale error', async () => {
|
||||
const gate = createSearchRequestGate()
|
||||
const request = gate.begin()
|
||||
const surfacedErrors = []
|
||||
const oldSessionFailure = Promise.reject(new Error('旧会话搜索失败')).catch((error) => {
|
||||
if (request.isCurrent()) surfacedErrors.push(error.message)
|
||||
})
|
||||
|
||||
gate.invalidate()
|
||||
await oldSessionFailure
|
||||
|
||||
assert.equal(request.signal.aborted, true)
|
||||
assert.equal(request.isCurrent(), false)
|
||||
assert.deepEqual(surfacedErrors, [])
|
||||
})
|
||||
|
||||
test('a request after invalidation belongs to the new session generation', () => {
|
||||
const gate = createSearchRequestGate()
|
||||
const oldSessionRequest = gate.begin()
|
||||
gate.invalidate()
|
||||
const newSessionRequest = gate.begin()
|
||||
|
||||
assert.equal(oldSessionRequest.isCurrent(), false)
|
||||
assert.equal(newSessionRequest.isCurrent(), true)
|
||||
assert.equal(newSessionRequest.signal.aborted, false)
|
||||
})
|
||||
@@ -8,6 +8,7 @@ type RequestOptions = {
|
||||
body?: unknown
|
||||
token?: string
|
||||
responseType?: 'json' | 'void'
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
type ErrorEnvelope = {
|
||||
@@ -59,6 +60,7 @@ export async function apiRequest<T>(path: string, options: RequestOptions = {}):
|
||||
...(options.token ? { Authorization: `Bearer ${options.token}` } : {}),
|
||||
},
|
||||
body: requestBody as BodyInit | undefined,
|
||||
signal: options.signal,
|
||||
})
|
||||
} catch {
|
||||
throw new ApiError(0, 'network_error', '无法连接服务器,请检查地址和网络后重试')
|
||||
|
||||
@@ -14,7 +14,7 @@ export type SearchResponseDTO = {
|
||||
|
||||
const searchPath = '/api/v1/search'
|
||||
|
||||
export async function searchWorkspace(session: ApiSession, query: string) {
|
||||
export async function searchWorkspace(session: ApiSession, query: string, signal?: AbortSignal) {
|
||||
const search = new URLSearchParams({ q: query })
|
||||
return apiRequest<SearchResponseDTO>(`${searchPath}?${search.toString()}`, { token: session.token })
|
||||
return apiRequest<SearchResponseDTO>(`${searchPath}?${search.toString()}`, { token: session.token, signal })
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
import type { SearchResultDTO } from '../api/search'
|
||||
import { LoginPage } from '../pages/login'
|
||||
import { ProjectActionModals, type CronDraft, type ProjectActionModal, type ProjectDraft, type SourceDraft, type TaskDraft } from '../pages/projects/project-action-modals'
|
||||
import { SearchResultPreview } from '../pages/projects/search-result-preview'
|
||||
import type { ProjectSettingsUpdate } from '../pages/projects/project-sidebar'
|
||||
import { ProjectPage } from '../pages/workspace-home'
|
||||
import type { WorkspaceTaskUpdate } from '../pages/workspace-body'
|
||||
@@ -37,6 +38,7 @@ function App() {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [actionLoading, setActionLoading] = useState(false)
|
||||
const [activeModal, setActiveModal] = useState<ProjectActionModal>(null)
|
||||
const [searchResultPreview, setSearchResultPreview] = useState<SearchResultDTO | null>(null)
|
||||
const workspaceSearch = useWorkbenchSearch(session)
|
||||
|
||||
const dark = theme === 'dark'
|
||||
@@ -228,16 +230,20 @@ function App() {
|
||||
}
|
||||
|
||||
function handleSelectSearchResult(result: SearchResultDTO) {
|
||||
const owningWorkspace = workspaces.find((workspace) => workspace.project.id === result.projectId)
|
||||
if (!owningWorkspace) {
|
||||
Message.warning('该搜索结果所在项目当前不可访问')
|
||||
return
|
||||
}
|
||||
const target = searchResultTarget(result.type)
|
||||
if (!target) {
|
||||
Message.warning('该搜索结果暂不支持导航')
|
||||
return
|
||||
}
|
||||
const owningWorkspace = workspaces.find((workspace) => workspace.project.id === result.projectId)
|
||||
if (!owningWorkspace) {
|
||||
if (isAuthorizedExternalPreview(result)) {
|
||||
setSearchResultPreview(result)
|
||||
} else {
|
||||
Message.warning('该搜索结果所在项目当前不可访问')
|
||||
}
|
||||
return
|
||||
}
|
||||
setActiveProjectID(owningWorkspace.project.id)
|
||||
setActiveView('project')
|
||||
setActiveChannel(target.channel)
|
||||
@@ -304,6 +310,7 @@ function App() {
|
||||
onCreateCronPlan={handleCreateCronPlan}
|
||||
tagOptions={activeTagOptions}
|
||||
/>
|
||||
<SearchResultPreview result={searchResultPreview} onClose={() => setSearchResultPreview(null)} />
|
||||
</main>
|
||||
</ConfigProvider>
|
||||
)
|
||||
@@ -316,4 +323,15 @@ function searchResultTarget(type: string): { channel: ChannelKey; openTask: bool
|
||||
return null
|
||||
}
|
||||
|
||||
function isAuthorizedExternalPreview(result: SearchResultDTO) {
|
||||
return (
|
||||
(result.type === 'task' || result.type === 'note')
|
||||
&& typeof result.projectId === 'string'
|
||||
&& result.projectId.trim() !== ''
|
||||
&& typeof result.title === 'string'
|
||||
&& result.title.trim() !== ''
|
||||
&& typeof result.snippet === 'string'
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
|
||||
29
apps/web_v1/src/app/search-request-gate.ts
Normal file
29
apps/web_v1/src/app/search-request-gate.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
export type SearchRequestTicket = {
|
||||
signal: AbortSignal
|
||||
isCurrent: () => boolean
|
||||
}
|
||||
|
||||
export function createSearchRequestGate() {
|
||||
let generation = 0
|
||||
let controller: AbortController | null = null
|
||||
|
||||
return {
|
||||
begin(): SearchRequestTicket {
|
||||
generation += 1
|
||||
controller?.abort()
|
||||
controller = new AbortController()
|
||||
const requestGeneration = generation
|
||||
return {
|
||||
signal: controller.signal,
|
||||
isCurrent: () => requestGeneration === generation,
|
||||
}
|
||||
},
|
||||
invalidate() {
|
||||
generation += 1
|
||||
controller?.abort()
|
||||
controller = null
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export type SearchRequestGate = ReturnType<typeof createSearchRequestGate>
|
||||
@@ -1,49 +1,63 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Message } from '@arco-design/web-react'
|
||||
import type { ApiSession } from '../api/client'
|
||||
import { searchWorkspace, type SearchResultDTO } from '../api/search'
|
||||
import { createSearchRequestGate, type SearchRequestGate } from './search-request-gate'
|
||||
|
||||
export function useWorkbenchSearch(session: ApiSession | null) {
|
||||
const [query, setQuery] = useState('')
|
||||
const [results, setResults] = useState<SearchResultDTO[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [searched, setSearched] = useState(false)
|
||||
const requestSequence = useRef(0)
|
||||
const requestGate = useRef<SearchRequestGate | null>(null)
|
||||
if (!requestGate.current) requestGate.current = createSearchRequestGate()
|
||||
|
||||
useEffect(() => {
|
||||
const gate = requestGate.current
|
||||
gate?.invalidate()
|
||||
setQuery('')
|
||||
setResults([])
|
||||
setLoading(false)
|
||||
setSearched(false)
|
||||
return () => gate?.invalidate()
|
||||
}, [session])
|
||||
|
||||
function changeQuery(value: string) {
|
||||
requestSequence.current += 1
|
||||
requestGate.current?.invalidate()
|
||||
setQuery(value)
|
||||
setLoading(false)
|
||||
setSearched(false)
|
||||
}
|
||||
|
||||
async function submitSearch() {
|
||||
const requestID = ++requestSequence.current
|
||||
const trimmedQuery = query.trim()
|
||||
if (!trimmedQuery) {
|
||||
requestGate.current?.invalidate()
|
||||
setResults([])
|
||||
setSearched(false)
|
||||
Message.warning('请输入搜索关键词')
|
||||
return
|
||||
}
|
||||
if (!session) {
|
||||
requestGate.current?.invalidate()
|
||||
Message.error('未登录或登录已失效')
|
||||
return
|
||||
}
|
||||
|
||||
const request = requestGate.current!.begin()
|
||||
setLoading(true)
|
||||
setSearched(false)
|
||||
try {
|
||||
const response = await searchWorkspace(session, trimmedQuery)
|
||||
if (requestID !== requestSequence.current) return
|
||||
const response = await searchWorkspace(session, trimmedQuery, request.signal)
|
||||
if (!request.isCurrent()) return
|
||||
setResults(response.items)
|
||||
setSearched(true)
|
||||
} catch (error) {
|
||||
if (requestID !== requestSequence.current) return
|
||||
if (!request.isCurrent()) return
|
||||
setResults([])
|
||||
Message.error(error instanceof Error ? error.message : '搜索失败,请稍后重试')
|
||||
} finally {
|
||||
if (requestID === requestSequence.current) setLoading(false)
|
||||
if (request.isCurrent()) setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -111,10 +111,11 @@ export function ProjectTopbar({
|
||||
)
|
||||
}
|
||||
|
||||
function searchTypeLabel(type: SearchResultDTO['type']) {
|
||||
function searchTypeLabel(type: string) {
|
||||
if (type === 'project') return '项目'
|
||||
if (type === 'task') return '任务'
|
||||
return '笔记'
|
||||
if (type === 'note') return '笔记'
|
||||
return '未知'
|
||||
}
|
||||
|
||||
function isDesktopRuntime() {
|
||||
|
||||
37
apps/web_v1/src/pages/projects/search-result-preview.tsx
Normal file
37
apps/web_v1/src/pages/projects/search-result-preview.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import { Alert, Button, Descriptions, Modal, Space, Tag, Typography } from '@arco-design/web-react'
|
||||
import type { SearchResultDTO } from '../../api/search'
|
||||
|
||||
const { Paragraph, Text, Title } = Typography
|
||||
|
||||
export function SearchResultPreview({
|
||||
result,
|
||||
onClose,
|
||||
}: {
|
||||
result: SearchResultDTO | null
|
||||
onClose: () => void
|
||||
}) {
|
||||
return (
|
||||
<Modal
|
||||
title="授权对象预览"
|
||||
visible={result !== null}
|
||||
onCancel={onClose}
|
||||
footer={<Button type="primary" onClick={onClose}>关闭预览</Button>}
|
||||
unmountOnExit
|
||||
>
|
||||
{result && (
|
||||
<Space direction="vertical" size={16} style={{ width: '100%' }}>
|
||||
<Alert type="info" content="仅显示被授权对象,不会加载完整项目工作区。" />
|
||||
<Space direction="vertical" size={8} style={{ width: '100%' }}>
|
||||
<Tag color="arcoblue">{result.type === 'task' ? '任务' : '笔记'}</Tag>
|
||||
<Title heading={6}>{result.title}</Title>
|
||||
{result.snippet && <Paragraph>{result.snippet}</Paragraph>}
|
||||
</Space>
|
||||
<Descriptions
|
||||
column={1}
|
||||
data={[{ label: '所属项目', value: <Text>{result.projectId}</Text> }]}
|
||||
/>
|
||||
</Space>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user