fix(files): 修 v0.24.1「压缩并下载」必然失败——archive.status 缺 sessionId + ready 交接无护栏(#798)
同一条轮询链上的两处,都在 #782 新增的 archive 功能里: 1. `archiveStatus(id)` 只发 `{ id }`,而宿主 `archive.status` 对 id 与 sessionId 都 `requireString`(src/index.ts)→ 第一次轮询即 400 `missing or invalid "sessionId"`,`state === 'ready'` 永远到不了, 整条链只有 build 成功。同族的 `archive.build` 与下载 URL 都带 scope, 只有这一处漏了。改为 `archiveStatus(scope, id)` 走 `scopePayload`。 2. `saveArchive` 是 fire-and-forget,`settleArchive()` 只在完成回调里执行, 于是 ready 之后 250ms 轮询照跑:下载路由是消费式的(GET 服务后释放任务), 首个 GET 未完成时会并发第二次 `save`(双下载),已完成时下一次 `status` 404 → 已成功的下载旁边同时挂一条 zipFailed。改为 ready 时先 `setArchiveJobId(null)` 停轮询,并用 `archiveHandedOffRef` 保证恰好一次交接。 测试:新增 `tests/archive-client.spec.ts` 钉客户端**真实载荷形状**(此前的 用例要么整体 mock 掉本模块、要么只测宿主侧),并给 FileTree 加一条 「ready 恰好交接一次」用例。回退 api.ts 的两个载荷断言、回退 FileTree 的 交接护栏,对应用例分别当场红(已实测)。
This commit is contained in:
1 parent
492661a3ea
commit
214bf451a0
4 files changed
+129
-6
No files matched your search
+19
-3
@@ -1321,11 +1321,17 @@ export function FileTree(props: {
|
||||
/** The job being polled (state so the poller starts/stops with it). */
|
||||
const [archiveJobId, setArchiveJobId] = useState<string | null>(null)
|
||||
const archiveJobRef = useRef<{ id: string; name: string } | null>(null)
|
||||
/** Whether the CURRENT job's `ready` status was already handed to the
|
||||
* download. The download route CONSUMES the task, so a second hand-off
|
||||
* would either fetch a deleted id (404 → a bogus `zipFailed` strip next to
|
||||
* a file that did land) or click the anchor twice. */
|
||||
const archiveHandedOffRef = useRef(false)
|
||||
|
||||
/** End the job: drop the progress line and release the guard. */
|
||||
const settleArchive = useCallback((): void => {
|
||||
archiveBusyRef.current = false
|
||||
archiveJobRef.current = null
|
||||
archiveHandedOffRef.current = false
|
||||
setArchiveJobId(null)
|
||||
setArchiveBusy(false)
|
||||
setArchiveProgress(null)
|
||||
@@ -1379,7 +1385,7 @@ export function FileTree(props: {
|
||||
// The poller swallows a rejected task (it must keep the loop alive), so
|
||||
// every failure is caught HERE and turned into the strip's `zipFailed`.
|
||||
try {
|
||||
const status = await archiveStatus(job.id)
|
||||
const status = await archiveStatus({ sessionId, cwd }, job.id)
|
||||
// The transport may deliver a response after teardown; the signal is the
|
||||
// only reliable staleness guard (the route call takes no signal).
|
||||
if (signal.aborted) return
|
||||
@@ -1388,17 +1394,27 @@ export function FileTree(props: {
|
||||
archiveHandlersRef.current.fail(status.error ?? `HTTP ${status.state}`)
|
||||
return
|
||||
}
|
||||
if (status.state === 'ready') archiveHandlersRef.current.save(job.id, job.name)
|
||||
if (status.state === 'ready') {
|
||||
// Hand the job over exactly ONCE, and stop polling BEFORE the download
|
||||
// starts: the GET releases the task, so the next tick would see 404 and
|
||||
// paint `zipFailed` over a download that actually succeeded (or, while
|
||||
// the first GET is still in flight, start a second one).
|
||||
if (archiveHandedOffRef.current) return
|
||||
archiveHandedOffRef.current = true
|
||||
setArchiveJobId(null)
|
||||
archiveHandlersRef.current.save(job.id, job.name)
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (signal.aborted) return
|
||||
archiveHandlersRef.current.fail(error instanceof Error ? error.message : String(error))
|
||||
}
|
||||
}, []), { intervalMs: 250, mode: 'self-scheduling', immediate: true })
|
||||
}, [cwd, sessionId]), { intervalMs: 250, mode: 'self-scheduling', immediate: true })
|
||||
|
||||
const downloadArchive = (paths: readonly string[]): void => {
|
||||
if (archiveBusyRef.current) return
|
||||
const name = paths.length === 1 ? `${baseName(paths[0]!)}.zip` : 'archive.zip'
|
||||
archiveBusyRef.current = true
|
||||
archiveHandedOffRef.current = false
|
||||
setArchiveBusy(true)
|
||||
setArchiveProgress(null)
|
||||
void archiveBuild({ sessionId, cwd }, paths, name)
|
||||
|
||||
+6
-3
@@ -466,9 +466,12 @@ export interface ArchiveBuildStatus {
|
||||
error?: string
|
||||
}
|
||||
|
||||
/** Poll one archive build (its id came from {@link archiveBuild}). */
|
||||
export function archiveStatus(id: string): Promise<ArchiveBuildStatus> {
|
||||
return call<ArchiveBuildStatus>('archive.status', { id })
|
||||
/** Poll one archive build (its id came from {@link archiveBuild}). The session
|
||||
* scope rides along exactly like `archive.build`: the host requires BOTH keys
|
||||
* (`requireString(payload, 'id')` + `requireString(payload, 'sessionId')`), so
|
||||
* a bare `{ id }` payload is refused with a 400 and the status is never read. */
|
||||
export function archiveStatus(scope: SessionScope, id: string): Promise<ArchiveBuildStatus> {
|
||||
return call<ArchiveBuildStatus>('archive.status', scopePayload(scope, { id }))
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* The archive client's WIRE payloads.
|
||||
*
|
||||
* The file tree's async "zip and download" failed in v0.24.1 because
|
||||
* `archiveStatus` posted a bare `{ id }` while the host requires
|
||||
* `requireString(payload, 'id')` AND `requireString(payload, 'sessionId')` —
|
||||
* a 400 on every poll, so the download never happened. The unit specs for the
|
||||
* tree mock this module wholesale, and `tests/zip.spec.ts` drives the HOST side
|
||||
* with hand-built payloads, so nothing covered what the client actually sends.
|
||||
* These cases run the real module against a stubbed `fetch` and assert the
|
||||
* request bodies, including the session scope on every archive call.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { archiveBuild, archiveDownloadUrl, archiveStatus, type SessionScope } from '../src/client/api.ts'
|
||||
|
||||
const scope: SessionScope = { sessionId: 's1', cwd: '/w' }
|
||||
|
||||
interface Posted {
|
||||
url: string
|
||||
body: Record<string, unknown>
|
||||
}
|
||||
|
||||
/** Stub `fetch` with one successful envelope and record the request. */
|
||||
function stubFetch(value: unknown): Posted[] {
|
||||
const posted: Posted[] = []
|
||||
vi.stubGlobal('fetch', vi.fn(async (url: string, init?: RequestInit) => {
|
||||
posted.push({ url, body: JSON.parse(String(init?.body)) as Record<string, unknown> })
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ ok: true, value }),
|
||||
} as unknown as Response
|
||||
}))
|
||||
return posted
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('archive client payloads', () => {
|
||||
it('posts the session scope on archive.status (the host requires BOTH keys)', async () => {
|
||||
const posted = stubFetch({ state: 'ready', done: 1, total: 1, bytes: 8 })
|
||||
await expect(archiveStatus(scope, 'job-1')).resolves.toEqual({ state: 'ready', done: 1, total: 1, bytes: 8 })
|
||||
expect(posted).toEqual([{ url: '/sidebar/api/archive.status', body: { sessionId: 's1', cwd: '/w', id: 'job-1' } }])
|
||||
})
|
||||
|
||||
it('carries the scope on archive.build, plus the selection and the name', async () => {
|
||||
const posted = stubFetch({ id: 'job-2', entries: 2 })
|
||||
await expect(archiveBuild(scope, ['/w/a.ts', '/w/b.ts'], 'archive.zip')).resolves.toEqual({ id: 'job-2', entries: 2 })
|
||||
expect(posted).toEqual([{
|
||||
url: '/sidebar/api/archive.build',
|
||||
body: { sessionId: 's1', cwd: '/w', paths: ['/w/a.ts', '/w/b.ts'], name: 'archive.zip' },
|
||||
}])
|
||||
})
|
||||
|
||||
it('puts the session on the download URL (it answers only the session that built it)', () => {
|
||||
// A session without a cwd keeps the URL scoped and free of an empty cwd.
|
||||
expect(archiveDownloadUrl({ sessionId: 's9' }, 'job-9')).toBe('/sidebar/archive?sessionId=s9&id=job-9')
|
||||
})
|
||||
|
||||
it('omits an empty cwd but never the sessionId', async () => {
|
||||
const posted = stubFetch({ state: 'building', done: 0, total: 1, bytes: 0 })
|
||||
await archiveStatus({ sessionId: 's2', cwd: '' }, 'job-3')
|
||||
expect(posted[0]?.body).toEqual({ sessionId: 's2', id: 'job-3' })
|
||||
})
|
||||
})
|
||||
@@ -235,6 +235,9 @@ describe('FileTree zip and download', () => {
|
||||
expect(fetchMock).toHaveBeenCalledWith('/sidebar/archive/job-1')
|
||||
expect(downloads).toEqual(['blob:mock-1|archive.zip'])
|
||||
expect(progressLine(harness.container)).toBeNull()
|
||||
// The poll carries the session scope: the host requires BOTH keys on
|
||||
// `archive.status`, so a bare `{ id }` is refused with a 400.
|
||||
expect(archiveStatus).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, 'job-1')
|
||||
// The object URL is released on the next task.
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(1) })
|
||||
expect(revokedUrls).toEqual(['blob:mock-1'])
|
||||
@@ -344,6 +347,40 @@ describe('FileTree zip and download', () => {
|
||||
expect(downloads).toEqual([])
|
||||
})
|
||||
|
||||
it('hands a ready job to the download exactly once, and stops polling first', async () => {
|
||||
// The download is held open, so the 250ms poller would tick again while the
|
||||
// GET is still in flight; `archiveStatus` keeps answering `ready`. The GET
|
||||
// CONSUMES the task, so a second hand-off either double-downloads or reads a
|
||||
// 404 and paints `zipFailed` beside a file that actually landed.
|
||||
let releaseDownload: (response: Response) => void = () => {}
|
||||
fetchMock.mockImplementation(async () => await new Promise<Response>(resolve => { releaseDownload = resolve }))
|
||||
harness = await mountTree()
|
||||
rightClick(rowByName(harness.container, 'sub'))
|
||||
clickMenuitem('Zip and download')
|
||||
await flush()
|
||||
await poll()
|
||||
await flush()
|
||||
expect(archiveStatus).toHaveBeenCalledTimes(1)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
expect(downloads).toEqual([])
|
||||
|
||||
// Three more poll intervals: no second download, no bogus failure strip.
|
||||
await poll()
|
||||
await poll()
|
||||
await poll()
|
||||
expect(archiveStatus).toHaveBeenCalledTimes(1)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
expect(harness.container.querySelector('[role="alert"]')).toBeNull()
|
||||
|
||||
await act(async () => {
|
||||
releaseDownload({ ok: true, status: 200, blob: async () => new Blob(['zip-bytes']) } as unknown as Response)
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
})
|
||||
expect(downloads).toEqual(['blob:mock-1|sub.zip'])
|
||||
expect(harness.container.querySelector('[role="alert"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('builds once while a job is in flight (double click guard)', async () => {
|
||||
let release: (job: { id: string; entries: number }) => void = () => {}
|
||||
archiveBuild.mockImplementation(async () => await new Promise<{ id: string; entries: number }>(resolve => { release = resolve }))
|
||||
|
||||
Reference in new issue
Block a user