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)
|
||||
})
|
||||
@@ -21,7 +21,11 @@ const failures = []
|
||||
const projectId = '019b0000-0000-7000-8000-000000000001'
|
||||
const taskSearchResultId = '019b0000-0000-7000-8000-000000000003'
|
||||
const unknownProjectId = '019b0000-0000-7000-8000-000000000099'
|
||||
const externalProjectId = '019b0000-0000-7000-8000-000000000088'
|
||||
const externalTaskId = '019b0000-0000-7000-8000-000000000089'
|
||||
const externalNoteId = '019b0000-0000-7000-8000-000000000090'
|
||||
const searchRequests = []
|
||||
const workspaceRequests = []
|
||||
const projectPatchRequests = []
|
||||
let expectingProjectPatchError = false
|
||||
let expectedProjectPatchConsoleErrorCount = 0
|
||||
@@ -83,6 +87,7 @@ await page.route('http://localhost:9150/api/v1/**', async (route) => {
|
||||
return
|
||||
}
|
||||
if (url.pathname === `/api/v1/projects/${projectId}/workspace`) {
|
||||
workspaceRequests.push(url.pathname)
|
||||
await route.fulfill({ json: visualCheckWorkspace })
|
||||
return
|
||||
}
|
||||
@@ -90,16 +95,22 @@ await page.route('http://localhost:9150/api/v1/**', async (route) => {
|
||||
const query = url.searchParams.get('q') ?? ''
|
||||
searchRequests.push(query)
|
||||
if (query === '慢请求') await new Promise((resolve) => setTimeout(resolve, 300))
|
||||
const projectIdForResult = query === '未知项目' ? unknownProjectId : projectId
|
||||
const result = query === '外部任务'
|
||||
? { id: externalTaskId, type: 'task', title: '获授权外部任务', projectId: externalProjectId, snippet: '仅限处理合同签署' }
|
||||
: query === '外部笔记'
|
||||
? { id: externalNoteId, type: 'note', title: '获授权外部笔记', projectId: externalProjectId, snippet: '仅共享合同背景段落' }
|
||||
: query === '未知结果'
|
||||
? { id: 'untrusted-result', type: 'source', title: '未知类型结果', projectId: unknownProjectId, snippet: '不得预览或导航' }
|
||||
: {
|
||||
id: taskSearchResultId,
|
||||
type: 'task',
|
||||
title: query === '慢请求' ? '慢请求任务' : query === '快请求' ? '快请求任务' : '回调任务',
|
||||
projectId,
|
||||
snippet: '检查签名',
|
||||
}
|
||||
await route.fulfill({
|
||||
json: {
|
||||
items: [{
|
||||
id: taskSearchResultId,
|
||||
type: 'task',
|
||||
title: query === '未知项目' ? '未知项目任务' : query === '慢请求' ? '慢请求任务' : query === '快请求' ? '快请求任务' : '回调任务',
|
||||
projectId: projectIdForResult,
|
||||
snippet: '检查签名',
|
||||
}],
|
||||
items: [result],
|
||||
},
|
||||
})
|
||||
return
|
||||
@@ -351,18 +362,67 @@ if (await searchInput.count() === 0 || await searchButton.count() === 0) {
|
||||
}
|
||||
}
|
||||
|
||||
await searchInput.fill('未知项目')
|
||||
const projectBeforeExternalPreview = await page.locator('.project-title h5').textContent()
|
||||
const externalWorkspacePath = `/api/v1/projects/${externalProjectId}/workspace`
|
||||
|
||||
await searchInput.fill('外部任务')
|
||||
await searchButton.click()
|
||||
await page.waitForTimeout(150)
|
||||
const unknownResult = page.getByRole('button', { name: /未知项目任务/ })
|
||||
if (await unknownResult.count() === 0) {
|
||||
failures.push('Search button must submit the current query and show results')
|
||||
const externalTaskResult = page.getByRole('button', { name: /获授权外部任务/ })
|
||||
if (await externalTaskResult.count() === 0) {
|
||||
failures.push('authorized external task must render as a search result')
|
||||
} else {
|
||||
await externalTaskResult.click()
|
||||
const preview = page.getByRole('dialog', { name: '授权对象预览' })
|
||||
if (await preview.count() === 0) {
|
||||
failures.push('authorized external task must open a restricted preview')
|
||||
} else {
|
||||
for (const text of ['仅显示被授权对象', '获授权外部任务', '仅限处理合同签署', externalProjectId]) {
|
||||
if (!await preview.getByText(text, { exact: false }).isVisible()) failures.push(`external task preview missing ${text}`)
|
||||
}
|
||||
await preview.getByRole('button', { name: '关闭预览', exact: true }).click()
|
||||
}
|
||||
}
|
||||
|
||||
await searchInput.fill('外部笔记')
|
||||
await searchButton.click()
|
||||
await page.waitForTimeout(150)
|
||||
const externalNoteResult = page.getByRole('button', { name: /获授权外部笔记/ })
|
||||
if (await externalNoteResult.count() === 0) {
|
||||
failures.push('authorized external note must render as a search result')
|
||||
} else {
|
||||
await externalNoteResult.click()
|
||||
const preview = page.getByRole('dialog', { name: '授权对象预览' })
|
||||
if (await preview.count() === 0) {
|
||||
failures.push('authorized external note must open a restricted preview')
|
||||
} else {
|
||||
for (const text of ['仅显示被授权对象', '获授权外部笔记', '仅共享合同背景段落', externalProjectId]) {
|
||||
if (!await preview.getByText(text, { exact: false }).isVisible()) failures.push(`external note preview missing ${text}`)
|
||||
}
|
||||
await preview.getByRole('button', { name: '关闭预览', exact: true }).click()
|
||||
}
|
||||
}
|
||||
|
||||
if (workspaceRequests.includes(externalWorkspacePath)) {
|
||||
failures.push('external previews must never load an unowned project workspace')
|
||||
}
|
||||
if (await page.locator('.project-title h5').textContent() !== projectBeforeExternalPreview) {
|
||||
failures.push('external previews must not switch the active owned project')
|
||||
}
|
||||
|
||||
await searchInput.fill('未知结果')
|
||||
await searchButton.click()
|
||||
await page.waitForTimeout(150)
|
||||
const unknownResult = page.getByRole('button', { name: /未知类型结果/ })
|
||||
if (await unknownResult.count() === 0) {
|
||||
failures.push('fixture must expose the unknown result for its safety assertion')
|
||||
} else {
|
||||
const projectBeforeUnknownResult = await page.locator('.project-title h5').textContent()
|
||||
await unknownResult.click()
|
||||
const projectAfterUnknownResult = await page.locator('.project-title h5').textContent()
|
||||
if (projectAfterUnknownResult !== projectBeforeUnknownResult) {
|
||||
failures.push('a result for an unavailable project must not fabricate project navigation')
|
||||
if (await page.getByRole('dialog', { name: '授权对象预览' }).count() !== 0) {
|
||||
failures.push('unknown search result types must not open an authorized preview')
|
||||
}
|
||||
if (await page.locator('.project-title h5').textContent() !== projectBeforeExternalPreview) {
|
||||
failures.push('unknown search results must not switch or fabricate a project')
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -121,10 +121,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