diff --git a/src/main/runtime-downloads/runtime-download-errors.ts b/src/main/runtime-downloads/runtime-download-errors.ts index 67849ecc383..33244d65177 100644 --- a/src/main/runtime-downloads/runtime-download-errors.ts +++ b/src/main/runtime-downloads/runtime-download-errors.ts @@ -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 }) } diff --git a/src/main/runtime-downloads/runtime-download-handlers.ts b/src/main/runtime-downloads/runtime-download-handlers.ts index 52ad99a4e8f..ec1ecbf5b1e 100644 --- a/src/main/runtime-downloads/runtime-download-handlers.ts +++ b/src/main/runtime-downloads/runtime-download-handlers.ts @@ -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() +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 + function validateArgs(args: unknown): RuntimeDownloadStartArgs { - const value = args as Partial | 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 } } diff --git a/src/main/runtime-downloads/runtime-download-transfer.test.ts b/src/main/runtime-downloads/runtime-download-transfer.test.ts index 2073967cce7..eb5030706e9 100644 --- a/src/main/runtime-downloads/runtime-download-transfer.test.ts +++ b/src/main/runtime-downloads/runtime-download-transfer.test.ts @@ -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

(impl: (method: string, params: P) => Promise): 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((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() } diff --git a/src/main/runtime/files/archive/folder-archive-sessions.test.ts b/src/main/runtime/files/archive/folder-archive-sessions.test.ts index e3e3e73fda3..9171aef54ad 100644 --- a/src/main/runtime/files/archive/folder-archive-sessions.test.ts +++ b/src/main/runtime/files/archive/folder-archive-sessions.test.ts @@ -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 (;;) { diff --git a/src/main/runtime/files/archive/folder-archive-walk.ts b/src/main/runtime/files/archive/folder-archive-walk.ts index 2498ee91012..250ae37e912 100644 --- a/src/main/runtime/files/archive/folder-archive-walk.ts +++ b/src/main/runtime/files/archive/folder-archive-walk.ts @@ -197,7 +197,8 @@ async function isUnmovedDirectory(absolutePath: string): Promise { } 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' || diff --git a/src/main/runtime/files/archive/folder-archive-zip-stream.ts b/src/main/runtime/files/archive/folder-archive-zip-stream.ts index 85fe4411fe7..f1de2c7c269 100644 --- a/src/main/runtime/files/archive/folder-archive-zip-stream.ts +++ b/src/main/runtime/files/archive/folder-archive-zip-stream.ts @@ -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(() => {})