chore(files): drop casts and real-time waits flagged by the quality gates

This commit is contained in:
Neil
2026-11-09 15:35:48 -08:00
parent 3384c5b08c
commit b6418aeb45
6 changed files with 47 additions and 34 deletions
@@ -39,9 +39,8 @@ export function toRuntimeDownloadError(error: unknown, signal: AbortSignal): Run
return error
}
const message = error instanceof Error ? error.message : String(error)
const code =
typeof (error as { code?: unknown } | null)?.code === 'string'
? (error as { code: string }).code
: 'runtime_error'
const rawCode =
typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined
const code = typeof rawCode === 'string' ? rawCode : 'runtime_error'
return runtimeDownloadErrorFromResponse({ code, message })
}
@@ -1,5 +1,6 @@
import { app, BrowserWindow, dialog, ipcMain, shell, type WebContents } from 'electron'
import { open } from 'node:fs/promises'
import { z } from 'zod'
import { join } from 'node:path'
import {
RUNTIME_OPEN_LOCALLY_MAX_BYTES,
@@ -37,26 +38,29 @@ const MAX_ACTIVE_DOWNLOADS = 8
const activeDownloads = new Map<string, AbortController>()
const Text = z.string().max(4096)
const RequiredText = Text.refine((value) => value.trim() !== '')
const StartArgs = z.object({
downloadId: RequiredText,
environmentId: RequiredText,
worktree: RequiredText,
relativePath: Text,
name: RequiredText,
kind: z.enum(['file', 'folder']),
intent: z.enum(['save', 'open']),
excludeDefaultDirs: z.boolean().optional(),
expectedEnvironmentPairingRevision: z.number().int().optional()
}) satisfies z.ZodType<RuntimeDownloadStartArgs>
function validateArgs(args: unknown): RuntimeDownloadStartArgs {
const value = args as Partial<RuntimeDownloadStartArgs> | null
const isText = (field: unknown, allowEmpty = false): field is string =>
typeof field === 'string' && (allowEmpty || field.trim() !== '') && field.length <= 4096
if (
!value ||
!isText(value.downloadId) ||
!isText(value.environmentId) ||
!isText(value.worktree) ||
!isText(value.relativePath, true) ||
!isText(value.name) ||
(value.kind !== 'file' && value.kind !== 'folder') ||
(value.intent !== 'save' && value.intent !== 'open')
) {
const parsed = StartArgs.safeParse(args)
if (!parsed.success) {
throw new Error('Invalid runtime download request')
}
if (value.intent === 'open' && value.kind !== 'file') {
if (parsed.data.intent === 'open' && parsed.data.kind !== 'file') {
throw new Error('Only files can be opened locally')
}
return value as RuntimeDownloadStartArgs
return parsed.data
}
function createCall(args: RuntimeDownloadStartArgs): RuntimeDownloadCall {
@@ -78,6 +82,7 @@ function createCall(args: RuntimeDownloadStartArgs): RuntimeDownloadCall {
if (!response.ok) {
throw runtimeDownloadErrorFromResponse(response.error)
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: each caller names the result type of the host method it calls; the host's RPC contract defines that shape.
return response.result as T
}
}
@@ -1,7 +1,7 @@
import { mkdtemp, open, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
RuntimeDownloadError,
transferRuntimeFile,
@@ -11,6 +11,12 @@ import {
let dir: string
/** A scripted host; the transfer code names each method's result type itself. */
function fakeCall<P>(impl: (method: string, params: P) => Promise<unknown>): RuntimeDownloadCall {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: each scripted reply matches the result type the transfer code expects for that method.
return impl as RuntimeDownloadCall
}
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'orca-runtime-download-'))
})
@@ -20,19 +26,21 @@ afterEach(async () => {
})
function fileHost(content: Buffer, statSize = content.byteLength): RuntimeDownloadCall {
return (async (method: string, params: { offset: number; length: number }) => {
return fakeCall(async (method: string, params: { offset: number; length: number }) => {
if (method === 'files.stat') {
return { size: statSize, isDirectory: false }
}
const bytes = content.subarray(params.offset, params.offset + params.length)
// Out-of-order replies: later pages may land first.
await new Promise((resolve) => setTimeout(resolve, params.offset % 3))
for (let turn = 0; turn < (params.offset / 7) % 3; turn += 1) {
await Promise.resolve()
}
return {
contentBase64: bytes.toString('base64'),
bytesRead: bytes.byteLength,
eof: params.offset + bytes.byteLength >= content.byteLength
}
}) as RuntimeDownloadCall
})
}
async function runFile(call: RuntimeDownloadCall, extra: { maxBytes?: number } = {}) {
@@ -85,7 +93,7 @@ describe('transferRuntimeFolder', () => {
it('releases the host archive when the download is canceled', async () => {
const controller = new AbortController()
const calls: string[] = []
const call = (async (method: string) => {
const call = fakeCall(async (method: string) => {
calls.push(method)
if (method === 'files.archiveStart') {
return { archiveId: 'z1', totalBytes: 10, excludedDirCount: 0, fileCount: 1 }
@@ -101,7 +109,7 @@ describe('transferRuntimeFolder', () => {
}
}
return { released: true }
}) as RuntimeDownloadCall
})
const sink = await open(join(dir, 'out.zip'), 'w+')
try {
await expect(
@@ -125,7 +133,7 @@ describe('transferRuntimeFolder', () => {
const controller = new AbortController()
const calls: { method: string; params: unknown }[] = []
let finishStart: (value: unknown) => void = () => {}
const call = (async (method: string, params: unknown) => {
const call = fakeCall(async (method: string, params: unknown) => {
calls.push({ method, params })
if (method === 'files.archiveStart') {
return new Promise<unknown>((resolve) => {
@@ -133,7 +141,7 @@ describe('transferRuntimeFolder', () => {
})
}
return { released: true }
}) as RuntimeDownloadCall
})
const sink = await open(join(dir, 'late.zip'), 'w+')
try {
const transfer = transferRuntimeFolder({
@@ -149,7 +157,7 @@ describe('transferRuntimeFolder', () => {
// Canceled at once, before the host has even finished walking.
await expect(transfer).rejects.toEqual(new RuntimeDownloadError('canceled'))
finishStart({ archiveId: 'late', totalBytes: 1, excludedDirCount: 0, fileCount: 1 })
await new Promise((resolve) => setTimeout(resolve, 0))
await vi.waitFor(() => expect(calls).toHaveLength(2))
} finally {
await sink.close()
}
@@ -2,7 +2,7 @@ import { mkdtemp, mkdir, rename, rm, symlink, writeFile, chmod } from 'node:fs/p
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { unzipSync } from 'fflate'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { FolderArchiveSessions } from './folder-archive-sessions'
import {
FolderArchiveLimitError,
@@ -181,8 +181,7 @@ describe('FolderArchiveSessions', () => {
await expect(
sessions.start({ folderPath: root, ownerKey: 'a', excludeDefaultDirs: true })
).rejects.toThrow('archive_busy')
await new Promise((resolve) => setTimeout(resolve, 60))
expect(sessions.activeCount()).toBe(0)
await vi.waitFor(() => expect(sessions.activeCount()).toBe(0))
await expect(
sessions.read({ archiveId: first.archiveId, ownerKey: 'a', maxBytes: 10 })
).rejects.toThrow('archive_not_found')
@@ -192,7 +191,8 @@ describe('FolderArchiveSessions', () => {
await writeFile(join(root, 'big.png'), Buffer.alloc(4 * 1024 * 1024, 7))
const plan = await planFolderArchive(root, 'r', { excludeDefaultDirs: true })
const stream = new FolderArchiveZipStream(plan.entries, 512 * 1024)
await new Promise((resolve) => setTimeout(resolve, 50))
// The producer fills to the mark, then must stop until something is read.
await vi.waitFor(() => expect(stream.processedBytes).toBeGreaterThanOrEqual(512 * 1024))
expect(stream.processedBytes).toBeLessThanOrEqual(1024 * 1024)
let total = 0
for (;;) {
@@ -197,7 +197,8 @@ async function isUnmovedDirectory(absolutePath: string): Promise<boolean> {
}
export function isVanishedOrDenied(error: unknown): boolean {
const code = (error as NodeJS.ErrnoException | null)?.code
const code =
typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined
return (
code === 'ENOENT' ||
code === 'ENOTDIR' ||
@@ -223,7 +223,7 @@ export class FolderArchiveZipStream {
}
this.processedBytes += bytesRead
// fflate may keep a reference until it deflates, so hand it a copy.
file.push(Uint8Array.prototype.slice.call(buffer, 0, bytesRead) as Uint8Array, false)
file.push(new Uint8Array(buffer.subarray(0, bytesRead)), false)
}
} finally {
await handle.close().catch(() => {})