diff --git a/cli/src/modules/common/handlers/files.test.ts b/cli/src/modules/common/handlers/files.test.ts index 09354717..9d55b6de 100644 --- a/cli/src/modules/common/handlers/files.test.ts +++ b/cli/src/modules/common/handlers/files.test.ts @@ -4,6 +4,7 @@ import { join } from 'path' import { tmpdir } from 'os' import { RpcHandlerManager } from '../../../api/rpc/RpcHandlerManager' import { registerFileHandlers } from './files' +import { registerGeneratedImage } from '../generatedImages' async function createTempDir(prefix: string): Promise { const path = join(tmpdir(), `${prefix}-${Date.now()}-${Math.random().toString(16).slice(2)}`) @@ -46,4 +47,35 @@ describe('file RPC handlers', () => { expect(parsed.size).toBe(expectedStats.size) expect(parsed.modified).toBe(expectedStats.mtime.getTime()) }) + + it('reads generated media whole or sliced, and reports the total size', async () => { + const payload = Buffer.from('0123456789') + registerGeneratedImage({ id: 'media-1', path: 'media.bin', mimeType: 'application/octet-stream', bytes: payload }) + + const full = JSON.parse(await rpc.handleRequest({ + method: 'session-test:readGeneratedImage', + params: JSON.stringify({ id: 'media-1' }) + })) as { success: boolean; content?: string; size?: number } + expect(full.success).toBe(true) + expect(full.size).toBe(payload.length) + expect(full.content).toBe(payload.toString('base64')) + + const chunk = JSON.parse(await rpc.handleRequest({ + method: 'session-test:readGeneratedImage', + params: JSON.stringify({ id: 'media-1', offset: 2, length: 4 }) + })) as { success: boolean; content?: string; size?: number; offset?: number; length?: number } + expect(chunk).toMatchObject({ + success: true, + size: payload.length, + offset: 2, + length: 4, + content: Buffer.from('2345').toString('base64') + }) + + const past = JSON.parse(await rpc.handleRequest({ + method: 'session-test:readGeneratedImage', + params: JSON.stringify({ id: 'media-1', offset: 99, length: 4 }) + })) as { success: boolean } + expect(past.success).toBe(false) + }) }) diff --git a/cli/src/modules/common/handlers/files.ts b/cli/src/modules/common/handlers/files.ts index 282e8d7b..3dc0beeb 100644 --- a/cli/src/modules/common/handlers/files.ts +++ b/cli/src/modules/common/handlers/files.ts @@ -17,10 +17,16 @@ type ReadFileResponse = FileReadResponse interface ReadGeneratedImageRequest { id: string + /** Optional slice start; the hub streams large media in bounded chunks. */ + offset?: number + length?: number } type ReadGeneratedImageResponse = GeneratedImageResponse +/** Cap one chunk so a single RPC ack stays small on slow runner links. */ +const MAX_GENERATED_IMAGE_CHUNK_BYTES = 4 * 1024 * 1024 + interface WriteFileRequest { path: string content: string @@ -68,11 +74,35 @@ export function registerFileHandlers(rpcHandlerManager: RpcHandlerManager, worki } try { + const total = image.content.byteLength + const hasSlice = typeof data.offset === 'number' || typeof data.length === 'number' + if (!hasSlice) { + return { + success: true, + content: image.content.toString('base64'), + mimeType: image.mimeType, + fileName: image.fileName, + size: total + } + } + + const offset = Number.isFinite(data.offset) ? Math.max(0, Math.floor(data.offset as number)) : 0 + if (offset > total) { + return rpcError('Chunk offset is past the end of the media') + } + const requested = Number.isFinite(data.length) && (data.length as number) > 0 + ? Math.floor(data.length as number) + : MAX_GENERATED_IMAGE_CHUNK_BYTES + const length = Math.min(requested, MAX_GENERATED_IMAGE_CHUNK_BYTES, total - offset) + const slice = image.content.subarray(offset, offset + length) return { success: true, - content: image.content.toString('base64'), + content: slice.toString('base64'), mimeType: image.mimeType, - fileName: image.fileName + fileName: image.fileName, + size: total, + offset, + length } } catch (error) { logger.debug('Failed to read generated image:', error) diff --git a/hub/src/sync/rpcGateway.ts b/hub/src/sync/rpcGateway.ts index 9eedd796..0fc0bbdb 100644 --- a/hub/src/sync/rpcGateway.ts +++ b/hub/src/sync/rpcGateway.ts @@ -48,6 +48,13 @@ import type { RpcRegistry } from '../socket/rpcRegistry' const DEFAULT_RPC_TIMEOUT_MS = 30_000 const MODEL_LIST_RPC_TIMEOUT_MS = 120_000 +/** + * Byte-heavy reads/writes (file downloads, generated media, uploads) carry + * their payload inside the socket ack. A remote runner behind a slow tunnel + * needs far more than the default for tens of MB (e.g. a 19MB video at + * ~0.4MB/s), so give these calls a multi-minute budget. + */ +const MEDIA_TRANSFER_RPC_TIMEOUT_MS = 300_000 /** * tiann/hapi#916: thrown by {@link RpcGateway.rpcCall} when the target CLI is @@ -347,11 +354,26 @@ export class RpcGateway { } async readSessionFile(sessionId: string, path: string): Promise { - return await this.sessionRpc(sessionId, RPC_METHODS.ReadFile, { path }) as RpcReadFileResponse + return await this.sessionRpc(sessionId, RPC_METHODS.ReadFile, { path }, MEDIA_TRANSFER_RPC_TIMEOUT_MS) as RpcReadFileResponse } async readGeneratedImage(sessionId: string, imageId: string): Promise { - return await this.sessionRpc(sessionId, RPC_METHODS.ReadGeneratedImage, { id: imageId }) as RpcGeneratedImageResponse + return await this.sessionRpc(sessionId, RPC_METHODS.ReadGeneratedImage, { id: imageId }, MEDIA_TRANSFER_RPC_TIMEOUT_MS) as RpcGeneratedImageResponse + } + + /** Bounded slice read so the hub can stream large media without one giant ack. */ + async readGeneratedImageChunk( + sessionId: string, + imageId: string, + offset: number, + length: number + ): Promise { + return await this.sessionRpc( + sessionId, + RPC_METHODS.ReadGeneratedImage, + { id: imageId, offset, length }, + MEDIA_TRANSFER_RPC_TIMEOUT_MS + ) as RpcGeneratedImageResponse } async listDirectory(sessionId: string, path: string): Promise { @@ -363,7 +385,7 @@ export class RpcGateway { } async uploadFile(sessionId: string, filename: string, content: string, mimeType: string): Promise { - return await this.sessionRpc(sessionId, RPC_METHODS.UploadFile, { sessionId, filename, content, mimeType }) as RpcUploadFileResponse + return await this.sessionRpc(sessionId, RPC_METHODS.UploadFile, { sessionId, filename, content, mimeType }, MEDIA_TRANSFER_RPC_TIMEOUT_MS) as RpcUploadFileResponse } async deleteUploadFile(sessionId: string, path: string): Promise { diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index af3078a5..ce91eae1 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -4050,6 +4050,15 @@ export class SyncEngine { return await this.rpcGateway.readGeneratedImage(sessionId, imageId) } + async readGeneratedImageChunk( + sessionId: string, + imageId: string, + offset: number, + length: number + ): Promise { + return await this.rpcGateway.readGeneratedImageChunk(sessionId, imageId, offset, length) + } + async listDirectory(sessionId: string, path: string): Promise { return await this.rpcGateway.listDirectory(sessionId, path) } diff --git a/hub/src/web/routes/git.test.ts b/hub/src/web/routes/git.test.ts index a368c3ad..d180af22 100644 --- a/hub/src/web/routes/git.test.ts +++ b/hub/src/web/routes/git.test.ts @@ -20,11 +20,12 @@ describe('generated images route', () => { const session = { id: 'session-1', namespace: 'default', active: true } as unknown as Session const engine = { resolveSessionAccess: () => ({ ok: true as const, sessionId: 'session-1', session }), - readGeneratedImage: async () => ({ + readGeneratedImageChunk: async (_sessionId: string, _id: string, offset: number, length: number) => ({ success: true, - content: pngBytes.toString('base64'), + content: pngBytes.subarray(offset, offset + length).toString('base64'), mimeType: 'image/png', - fileName: 'shot.png' + fileName: 'shot.png', + size: pngBytes.length }) } as unknown as Partial @@ -44,9 +45,9 @@ describe('generated images route', () => { let rpcCalls = 0 const engine = { resolveSessionAccess: () => ({ ok: true as const, sessionId: 'session-1', session }), - readGeneratedImage: async () => { + readGeneratedImageChunk: async () => { rpcCalls += 1 - return { success: true, content: '', mimeType: 'image/png', fileName: 'shot.png' } + return { success: true, content: '', mimeType: 'image/png', fileName: 'shot.png', size: 0 } } } as unknown as Partial @@ -64,12 +65,16 @@ describe('generated images route', () => { let mimeType = 'audio/wav' const engine = { resolveSessionAccess: () => ({ ok: true as const, sessionId: 'session-1', session }), - readGeneratedImage: async () => ({ - success: true, - content: Buffer.from('media').toString('base64'), - mimeType, - fileName: mimeType === 'audio/wav' ? 'sample.wav' : 'archive.bin' - }) + readGeneratedImageChunk: async (_sessionId: string, _id: string, offset: number, length: number) => { + const payload = Buffer.from('media') + return { + success: true, + content: payload.subarray(offset, offset + length).toString('base64'), + mimeType, + fileName: mimeType === 'audio/wav' ? 'sample.wav' : 'archive.bin', + size: payload.length + } + } } as unknown as Partial const audio = await buildApp(engine).request('/api/sessions/session-1/generated-images/audio-1') @@ -81,6 +86,66 @@ describe('generated images route', () => { expect(file.headers.get('content-disposition')).toStartWith('attachment;') expect(file.headers.get('content-type')).toContain('application/octet-stream') }) + + it('serves the whole payload when a pre-chunk session ignores offset/length', async () => { + const session = { id: 'session-1', namespace: 'default', active: true } as unknown as Session + const payload = Buffer.from('legacy-media-bytes') + const engine = { + resolveSessionAccess: () => ({ ok: true as const, sessionId: 'session-1', session }), + // Old CLI handlers ignore offset/length and never report `size`. + readGeneratedImageChunk: async () => ({ + success: true, + content: payload.toString('base64'), + mimeType: 'video/mp4', + fileName: 'clip.mp4' + }) + } as unknown as Partial + + const response = await buildApp(engine).request('/api/sessions/session-1/generated-images/legacy-1') + expect(response.status).toBe(200) + expect(response.headers.get('content-type')).toContain('video/mp4') + expect(Buffer.from(await response.arrayBuffer()).equals(payload)).toBe(true) + }) + + it('streams multi-chunk media and honors Range requests', async () => { + const session = { id: 'session-1', namespace: 'default', active: true } as unknown as Session + const payload = Buffer.alloc(2 * 1024 * 1024 + 512 * 1024, 7) + const calls: Array<[number, number]> = [] + const engine = { + resolveSessionAccess: () => ({ ok: true as const, sessionId: 'session-1', session }), + readGeneratedImageChunk: async (_sessionId: string, _id: string, offset: number, length: number) => { + calls.push([offset, length]) + return { + success: true, + content: payload.subarray(offset, offset + length).toString('base64'), + mimeType: 'video/mp4', + fileName: 'clip.mp4', + size: payload.length, + offset + } + } + } as unknown as Partial + + const full = await buildApp(engine).request('/api/sessions/session-1/generated-images/vid-1') + expect(full.status).toBe(200) + expect(full.headers.get('accept-ranges')).toBe('bytes') + expect(full.headers.get('content-length')).toBe(String(payload.length)) + expect(Buffer.from(await full.arrayBuffer()).equals(payload)).toBe(true) + // probe + two more chunks (1MB + 1MB + 0.5MB) + expect(calls).toHaveLength(3) + + const ranged = await buildApp(engine).request('/api/sessions/session-1/generated-images/vid-1', { + headers: { range: 'bytes=1048576-1048579' } + }) + expect(ranged.status).toBe(206) + expect(ranged.headers.get('content-range')).toBe(`bytes 1048576-1048579/${payload.length}`) + expect(Buffer.from(await ranged.arrayBuffer()).equals(payload.subarray(1048576, 1048580))).toBe(true) + + const invalid = await buildApp(engine).request('/api/sessions/session-1/generated-images/vid-1', { + headers: { range: 'bytes=99999999-' } + }) + expect(invalid.status).toBe(416) + }) }) describe('file search route', () => { diff --git a/hub/src/web/routes/git.ts b/hub/src/web/routes/git.ts index 872c8c4c..4cb8c945 100644 --- a/hub/src/web/routes/git.ts +++ b/hub/src/web/routes/git.ts @@ -45,6 +45,9 @@ async function runRpc(fn: () => Promise): Promise SyncEngine | null): Hono { const app = new Hono() @@ -172,25 +175,123 @@ export function createGitRoutes(getSyncEngine: () => SyncEngine | null): Hono engine.readGeneratedImage(sessionResult.sessionId, parsed.data.imageId)) - if (!result.success || !result.content) { - return c.json({ success: false, error: result.error ?? 'Generated image not found' }, 404) - } + const sessionId = sessionResult.sessionId + const imageId = parsed.data.imageId - const bytes = Uint8Array.from(Buffer.from(result.content, 'base64')) - const mimeType = result.mimeType ?? 'application/octet-stream' - const disposition = !result.mimeType || mimeType.startsWith('image/') || mimeType.startsWith('video/') || mimeType.startsWith('audio/') + // The first bounded chunk doubles as a probe: it carries total size + mime. Larger + // media is then streamed chunk by chunk instead of one tens-of-MB socket ack, so a + // remote runner on a slow tunnel cannot trip RPC/idle timeouts mid-transfer. + let probe: Awaited> + try { + probe = await engine.readGeneratedImageChunk(sessionId, imageId, 0, GENERATED_MEDIA_CHUNK_BYTES) + } catch (error) { + return c.json({ success: false, error: error instanceof Error ? error.message : String(error) }, 404) + } + if (!probe.success || typeof probe.content !== 'string') { + return c.json({ success: false, error: probe.error ?? 'Generated image not found' }, 404) + } + if (typeof probe.size !== 'number') { + // Pre-chunk CLI (session process started before the streaming deploy): + // the probe is actually the whole payload — serve it in one response. + const bytes = Uint8Array.from(Buffer.from(probe.content, 'base64')) + const legacyMimeType = probe.mimeType ?? 'application/octet-stream' + const legacyDisposition = !probe.mimeType || legacyMimeType.startsWith('image/') || legacyMimeType.startsWith('video/') || legacyMimeType.startsWith('audio/') + ? 'inline' + : 'attachment' + return c.body(bytes, 200, { + 'Content-Type': legacyMimeType, + 'Content-Disposition': `${legacyDisposition}; filename="${encodeURIComponent(probe.fileName ?? 'generated-media')}"`, + 'X-Content-Type-Options': 'nosniff', + 'Cache-Control': GENERATED_IMAGE_CACHE_CONTROL, + ETag: etag + }) + } + const total = probe.size + if (total <= 0) { + return c.json({ success: false, error: 'Generated media is empty' }, 404) + } + const mimeType = probe.mimeType ?? 'application/octet-stream' + const disposition = !probe.mimeType || mimeType.startsWith('image/') || mimeType.startsWith('video/') || mimeType.startsWith('audio/') ? 'inline' : 'attachment' + + // Range support so big media can be seeked/resumed by players and download tools. + let start = 0 + let end = total - 1 + let status: 200 | 206 = 200 + const rangeHeader = c.req.header('range') + if (rangeHeader) { + const match = /^bytes=(\d*)-(\d*)$/.exec(rangeHeader.trim()) + const rawStart = match?.[1] ?? null + const rawEnd = match?.[2] ?? null + if (!match || (rawStart === '' && rawEnd === '')) { + return c.body(null, 416, { 'Content-Range': `bytes */${total}` }) + } + if (rawStart === '') { + const suffix = Number(rawEnd) + if (!Number.isFinite(suffix) || suffix <= 0) { + return c.body(null, 416, { 'Content-Range': `bytes */${total}` }) + } + start = Math.max(0, total - suffix) + } else { + start = Number(rawStart) + if (rawEnd !== '') { + end = Number(rawEnd) + } + } + if (!Number.isFinite(start) || !Number.isFinite(end) || start > end || start >= total) { + return c.body(null, 416, { 'Content-Range': `bytes */${total}` }) + } + end = Math.min(end, total - 1) + status = 206 + } + const contentLength = end - start + 1 + const probeBytes = Uint8Array.from(Buffer.from(probe.content, 'base64')) + + const stream = new ReadableStream({ + async start(controller) { + try { + let cursor = start + if (cursor < probeBytes.byteLength) { + const sliceEnd = Math.min(probeBytes.byteLength, end + 1) + if (sliceEnd > cursor) { + controller.enqueue(probeBytes.subarray(cursor, sliceEnd)) + cursor = sliceEnd + } + } + while (cursor <= end) { + const chunk = await engine.readGeneratedImageChunk(sessionId, imageId, cursor, GENERATED_MEDIA_CHUNK_BYTES) + if (!chunk.success || typeof chunk.content !== 'string') { + throw new Error(chunk.error ?? 'Generated media read failed') + } + const bytes = Uint8Array.from(Buffer.from(chunk.content, 'base64')) + if (bytes.byteLength === 0) { + break + } + const remaining = end - cursor + 1 + const slice = bytes.byteLength > remaining ? bytes.subarray(0, remaining) : bytes + controller.enqueue(slice) + cursor += slice.byteLength + } + controller.close() + } catch (error) { + controller.error(error instanceof Error ? error : new Error(String(error))) + } + } + }) + // Generated images are content-addressed by an immutable random id, so the bytes for a // given id never change. Cache aggressively so remounts/scroll/session reopen don't // re-run the full HTTP -> socket.io RPC -> base64 round-trip every time (issue #927). - return c.body(bytes, 200, { + return c.body(stream, status, { 'Content-Type': mimeType, - 'Content-Disposition': `${disposition}; filename="${encodeURIComponent(result.fileName ?? 'generated-media')}"`, + 'Content-Disposition': `${disposition}; filename="${encodeURIComponent(probe.fileName ?? 'generated-media')}"`, 'X-Content-Type-Options': 'nosniff', 'Cache-Control': GENERATED_IMAGE_CACHE_CONTROL, - ETag: etag + ETag: etag, + 'Accept-Ranges': 'bytes', + 'Content-Length': String(contentLength), + ...(status === 206 ? { 'Content-Range': `bytes ${start}-${end}/${total}` } : {}) }) }) diff --git a/hub/src/web/server.ts b/hub/src/web/server.ts index 6449113f..ee86eadd 100644 --- a/hub/src/web/server.ts +++ b/hub/src/web/server.ts @@ -513,7 +513,10 @@ export async function startWebServer(options: { const server = (Bun.serve as any)({ hostname: configuration.listenHost, port: configuration.listenPort, - idleTimeout: Math.max(30, socketHandler.idleTimeout), + // Media downloads wait on a hub→CLI RPC that can take minutes on a slow + // runner tunnel while zero bytes flow to the client. Keep the HTTP + // connection alive well past the socket idle default (Bun caps at 255s). + idleTimeout: Math.min(255, Math.max(30, socketHandler.idleTimeout, 240)), maxRequestBodySize: Math.max(socketHandler.maxRequestBodySize, 68 * 1024 * 1024), websocket: { ...originalWsHandler, diff --git a/shared/src/apiTypes.ts b/shared/src/apiTypes.ts index 6a6d07a4..3cacf00c 100644 --- a/shared/src/apiTypes.ts +++ b/shared/src/apiTypes.ts @@ -952,6 +952,10 @@ export type GeneratedImageResponse = { content?: string mimeType?: string fileName?: string + /** Total media size when content is a chunk (offset/length requests). */ + size?: number + offset?: number + length?: number error?: string }