From bb7f12a625ed1ed4eacc5c0656f315e604262aeb Mon Sep 17 00:00:00 2001 From: Erik Sombroek Date: Fri, 27 Nov 2026 09:12:03 +0100 Subject: [PATCH 1/2] Show upload progress for the legacy upload command `poki upload` printed "uploading..." and then nothing until the server answered, so a large build on a slow connection looked stuck. The body is now written in 64 KiB slices, and each write callback updates a progress line with the percentage, bytes sent, and transfer rate. The line is drawn only when stdout is a terminal. Piped, captured, and CI output is byte-identical to before, which keeps the compatibility guarantee for the legacy command. Content-Length, the body, and the inactivity timeout are unchanged. Co-Authored-By: Claude Opus 5.5 --- src/p4d.ts | 57 ++++++++++--- src/upload-progress.ts | 81 ++++++++++++++++++ test/upload-progress.test.ts | 161 +++++++++++++++++++++++++++++++++++ 3 files changed, 289 insertions(+), 10 deletions(-) create mode 100644 src/upload-progress.ts create mode 100644 test/upload-progress.test.ts diff --git a/src/p4d.ts b/src/p4d.ts index 9547973..b6e2a14 100644 --- a/src/p4d.ts +++ b/src/p4d.ts @@ -2,9 +2,11 @@ import { auth, refresh } from './auth' import { Config } from './config' import { serviceEnvironment } from './service-environment' import { DEFAULT_UPLOAD_TIMEOUT_MS, timeoutMillisecondsOrDefault } from './timeouts' +import { ProgressOutput, uploadProgress } from './upload-progress' import { CLI_USER_AGENT } from './version' import { readFileSync, statSync } from 'fs' +import type { ClientRequest } from 'http' import { request } from 'https' import { basename } from 'path' @@ -47,6 +49,31 @@ export function legacyUploadTimeoutMs (): number { // loopback server; production always uses the https request above. export type LegacyTransport = typeof request +// Writing the body in slices lets each write callback report how much of it +// the socket has taken, which is what the progress line shows. Only one slice +// is in flight at a time, so Node never buffers more than a slice of it. +const UPLOAD_SLICE_BYTES = 64 * 1024 + +function writeBody (req: ClientRequest, body: Buffer, onWritten: (sent: number) => void): void { + let offset = 0 + const writeNext = (): void => { + // A destroyed request has already settled through its 'error' event. + if (req.destroyed) return + if (offset >= body.length) { + req.end() + return + } + const end = Math.min(offset + UPLOAD_SLICE_BYTES, body.length) + req.write(body.subarray(offset, end), error => { + if (error != null) return + offset = end + onWritten(offset) + writeNext() + }) + } + writeNext() +} + async function doit ( gameId: string, filename: string, @@ -55,7 +82,8 @@ async function doit ( makePublic: boolean, disableImageCompression: boolean, config: Config, - transport: LegacyTransport + transport: LegacyTransport, + progressOutput: ProgressOutput ): Promise { return await new Promise((resolve, reject) => { if (config.access_token === undefined) { @@ -96,6 +124,9 @@ async function doit ( const settle = (action: () => void): void => { if (settled) return settled = true + // End the progress line so what the caller prints next starts on its + // own row, even when the answer arrives before the body is sent. + progress.finish() action() } const req = transport({ @@ -139,8 +170,13 @@ async function doit ( : new LegacyUploadError(`Could not reach the Poki upload service: ${error.message}`, 'network'))) }) - req.write(buffer, 'binary') - req.end() + // Created only once the request exists: a request that throws while it + // is being built must not leave a half-drawn progress line behind. + const progress = uploadProgress(buffer.length, progressOutput) + writeBody(req, buffer, sent => { + progress.update(sent) + if (sent === buffer.length) progress.finish() + }) }) } @@ -169,10 +205,11 @@ async function uploadToP4D ( notes: string | undefined, makePublic: boolean, disableImageCompression: boolean, - transport: LegacyTransport + transport: LegacyTransport, + progressOutput: ProgressOutput ): Promise { let config = await auth(false, console.log) - let response = await doit(gameId, filename, name, notes, makePublic, disableImageCompression, config, transport) + let response = await doit(gameId, filename, name, notes, makePublic, disableImageCompression, config, transport, progressOutput) if (response.statusCode === 401 && config.access_type !== 'Token') { try { @@ -180,15 +217,15 @@ async function uploadToP4D ( } catch (e) { config = await auth(true, console.log) } - response = await doit(gameId, filename, name, notes, makePublic, disableImageCompression, config, transport) + response = await doit(gameId, filename, name, notes, makePublic, disableImageCompression, config, transport, progressOutput) } return finalizeP4dResponse(response) } // Keep the original six-argument entry point and its human presentation -// compatible for the deprecated default upload workflow. The seventh parameter -// exists for tests only and keeps that call shape intact. -export async function postToP4D (gameId: string, filename: string, name: string, notes: string | undefined, makePublic: boolean, disableImageCompression: boolean, transport: LegacyTransport = request): Promise { - return await uploadToP4D(gameId, filename, name, notes, makePublic, disableImageCompression, transport) +// compatible for the deprecated default upload workflow. The trailing +// parameters exist for tests only and keep that call shape intact. +export async function postToP4D (gameId: string, filename: string, name: string, notes: string | undefined, makePublic: boolean, disableImageCompression: boolean, transport: LegacyTransport = request, progressOutput: ProgressOutput = process.stdout): Promise { + return await uploadToP4D(gameId, filename, name, notes, makePublic, disableImageCompression, transport, progressOutput) } diff --git a/src/upload-progress.ts b/src/upload-progress.ts new file mode 100644 index 0000000..4a5ef79 --- /dev/null +++ b/src/upload-progress.ts @@ -0,0 +1,81 @@ +// A live progress line for the deprecated human upload. It renders only when +// the output is a terminal: piped, captured, and CI output never receives it, +// so the documented upload output stays byte-identical for every pipeline that +// reads it. + +export interface ProgressOutput { + isTTY?: boolean + columns?: number + write: (text: string) => unknown +} + +export interface UploadProgress { + update: (sent: number) => void + finish: () => void +} + +const RENDER_INTERVAL_MS = 100 +const MIN_BAR_WIDTH = 10 +const MAX_BAR_WIDTH = 30 +const DEFAULT_COLUMNS = 80 + +const units = ['B', 'KB', 'MB', 'GB', 'TB'] + +export function formatBytes (bytes: number): string { + let value = bytes + let unit = 0 + // Round before choosing the unit so 999,999 bytes reads 1.0 MB, not 1000.0 KB. + while (unit < units.length - 1 && (unit === 0 ? Math.round(value) : Math.round(value * 10) / 10) >= 1000) { + value /= 1000 + unit++ + } + return unit === 0 ? `${Math.round(value)} B` : `${value.toFixed(1)} ${units[unit]}` +} + +export function uploadProgressLine (sent: number, total: number, elapsedMs: number, columns = DEFAULT_COLUMNS): string { + const fraction = total > 0 ? Math.min(1, Math.max(0, sent / total)) : 1 + const percent = `${Math.floor(fraction * 100)}%`.padStart(4) + const rate = elapsedMs > 0 && sent > 0 ? ` ${formatBytes(sent / elapsedMs * 1000)}/s` : '' + const text = `${percent} ${formatBytes(sent)} / ${formatBytes(total)}${rate}` + // Stay one column short of the terminal width: a line that exactly fills it + // wraps in some terminals, and the carriage return then redraws the wrong row. + const width = Math.max(MIN_BAR_WIDTH, Math.min(MAX_BAR_WIDTH, columns - text.length - 4)) + const filled = Math.round(fraction * width) + return `[${'#'.repeat(filled)}${'-'.repeat(width - filled)}] ${text}` +} + +export function uploadProgress (total: number, output: ProgressOutput, now: () => number = Date.now): UploadProgress { + if (output.isTTY !== true) return { update: () => {}, finish: () => {} } + + const started = now() + let sent = 0 + let renderedSent = -1 + let renderedAt = -Infinity + let finished = false + + const render = (): void => { + renderedAt = now() + renderedSent = sent + // \r returns to the line start and ESC[K clears what a longer previous + // line left behind. libuv translates both for Windows consoles. + output.write(`\r${uploadProgressLine(sent, total, renderedAt - started, output.columns)}\x1b[K`) + } + + render() + + return { + update: bytes => { + if (finished) return + sent = bytes + if (sent >= total || now() - renderedAt >= RENDER_INTERVAL_MS) render() + }, + // Idempotent: the body completing and the response settling both end the + // line, and whichever comes first must leave later output on a fresh row. + finish: () => { + if (finished) return + finished = true + if (renderedSent !== sent) render() + output.write('\n') + } + } +} diff --git a/test/upload-progress.test.ts b/test/upload-progress.test.ts new file mode 100644 index 0000000..2fcb635 --- /dev/null +++ b/test/upload-progress.test.ts @@ -0,0 +1,161 @@ +import assert from 'node:assert/strict' +import { randomBytes } from 'node:crypto' +import { writeFileSync } from 'node:fs' +import { createServer, request as httpRequest, IncomingMessage, RequestOptions } from 'node:http' +import { join } from 'node:path' +import test, { TestContext } from 'node:test' + +import { LegacyTransport, postToP4D } from '../src/p4d' +import { formatBytes, ProgressOutput, uploadProgress, uploadProgressLine } from '../src/upload-progress' +import { temporaryDirectory } from './helpers' + +function recordingOutput (isTTY: boolean, columns = 80): ProgressOutput & { writes: string[] } { + const writes: string[] = [] + return { isTTY, columns, writes, write: text => writes.push(text) } +} + +void test('formatBytes uses decimal units and never shows 1000 of a unit', () => { + assert.equal(formatBytes(0), '0 B') + assert.equal(formatBytes(999), '999 B') + assert.equal(formatBytes(1000), '1.0 KB') + assert.equal(formatBytes(999_999), '1.0 MB') + assert.equal(formatBytes(12_345_678), '12.3 MB') + assert.equal(formatBytes(2_500_000_000), '2.5 GB') +}) + +void test('uploadProgressLine shows the bar, percentage, bytes, and rate', () => { + assert.equal(uploadProgressLine(0, 2000, 0), `[${'-'.repeat(30)}] 0% 0 B / 2.0 KB`) + assert.equal(uploadProgressLine(1000, 2000, 1000), `[${'#'.repeat(15)}${'-'.repeat(15)}] 50% 1.0 KB / 2.0 KB 1.0 KB/s`) + assert.equal(uploadProgressLine(2000, 2000, 500), `[${'#'.repeat(30)}] 100% 2.0 KB / 2.0 KB 4.0 KB/s`) +}) + +void test('uploadProgressLine stays narrower than the terminal', () => { + for (const columns of [50, 60, 80, 120]) { + const line = uploadProgressLine(123_456_789, 987_654_321, 12_345, columns) + assert.ok(line.length < columns, `${line.length} < ${columns}: ${line}`) + } + // Below the minimum bar width the line may wrap, but the bar never vanishes. + assert.match(uploadProgressLine(1, 2, 1, 20), /^\[#{5}-{5}\]/) +}) + +void test('uploadProgress writes nothing when the output is not a terminal', () => { + const output = recordingOutput(false) + const progress = uploadProgress(100, output) + progress.update(50) + progress.update(100) + progress.finish() + assert.deepEqual(output.writes, []) +}) + +void test('uploadProgress throttles redraws and ends its line exactly once', () => { + const output = recordingOutput(true) + let clock = 0 + const progress = uploadProgress(1000, output, () => clock) + assert.equal(output.writes.length, 1, 'renders 0% immediately') + + clock = 50 + progress.update(100) + assert.equal(output.writes.length, 1, 'skips redraws inside the render interval') + + clock = 150 + progress.update(400) + assert.equal(output.writes.length, 2) + assert.equal(output.writes[1], `\r${uploadProgressLine(400, 1000, 150)}\x1b[K`) + + clock = 160 + progress.update(1000) + assert.equal(output.writes.length, 3, 'always draws the final 100%') + assert.equal(output.writes[2], `\r${uploadProgressLine(1000, 1000, 160)}\x1b[K`) + + progress.finish() + progress.finish() + progress.update(1000) + assert.deepEqual(output.writes.slice(3), ['\n']) +}) + +void test('uploadProgress redraws the latest count before ending an interrupted line', () => { + const output = recordingOutput(true) + let clock = 0 + const progress = uploadProgress(1000, output, () => clock) + clock = 10 + progress.update(300) + progress.finish() + assert.equal(output.writes[1], `\r${uploadProgressLine(300, 1000, 10)}\x1b[K`) + assert.equal(output.writes[2], '\n') +}) + +async function uploadThroughLoopback (t: TestContext, output: ProgressOutput): Promise<{ archive: Buffer, received: Buffer, contentLength: number, logs: unknown[][] }> { + const directory = temporaryDirectory(t, 'upload-progress') + const archivePath = join(directory, 'build.zip') + // Several slices, and not a multiple of the slice size. + const archive = randomBytes(300 * 1024 + 123) + writeFileSync(archivePath, archive) + + let received = Buffer.alloc(0) + let contentLength = -1 + const server = createServer((req, res) => { + contentLength = Number(req.headers['content-length']) + const chunks: Buffer[] = [] + req.on('data', (chunk: Buffer) => chunks.push(chunk)) + req.on('end', () => { + received = Buffer.concat(chunks) + res.writeHead(201, { 'Content-Type': 'application/json' }) + res.end(JSON.stringify({ game_id: 'game-1', id: 42 })) + }) + }) + t.after(() => server.close()) + const port = await new Promise(resolve => server.listen(0, '127.0.0.1', () => { + const address = server.address() + assert.ok(address !== null && typeof address !== 'string') + resolve(address.port) + })) + + const transport = ((options: RequestOptions, callback?: (res: IncomingMessage) => void) => httpRequest({ + ...options, + protocol: 'http:', + hostname: '127.0.0.1', + port, + agent: false + }, callback)) as LegacyTransport + + const logs: unknown[][] = [] + const originalLog = console.log + console.log = (...args: unknown[]) => { logs.push(args) } + const previousToken = process.env.POKI_UPLOAD_TOKEN + process.env.POKI_UPLOAD_TOKEN = 'tok' + t.after(() => { + console.log = originalLog + if (previousToken === undefined) delete process.env.POKI_UPLOAD_TOKEN + else process.env.POKI_UPLOAD_TOKEN = previousToken + }) + + const data = await postToP4D('game-1', archivePath, 'Release', undefined, false, false, transport, output) + assert.deepEqual(data, { game_id: 'game-1', id: 42 }) + return { archive, received, contentLength, logs } +} + +void test('legacy upload draws progress on a terminal and still sends the exact body', async t => { + const output = recordingOutput(true) + const { archive, received, contentLength, logs } = await uploadThroughLoopback(t, output) + + assert.equal(contentLength, received.length, 'Content-Length matches the sliced body') + assert.ok(received.includes(archive), 'the archive bytes arrive intact') + assert.deepEqual(logs, [['uploading...']], 'the human text is unchanged') + + const lines = output.writes.filter(text => text !== '\n') + assert.ok(lines.length >= 2, 'draws at least the start and the end') + const total = formatBytes(received.length) + assert.ok(lines[0].startsWith(`\r[${'-'.repeat(30)}] 0% 0 B / ${total}`), lines[0]) + assert.ok(lines[lines.length - 1].startsWith(`\r[${'#'.repeat(30)}] 100% ${total} / ${total}`), lines[lines.length - 1]) + assert.deepEqual(output.writes.filter(text => text === '\n'), ['\n'], 'ends the line exactly once') + assert.equal(output.writes[output.writes.length - 1], '\n') +}) + +void test('legacy upload output is unchanged when stdout is not a terminal', async t => { + const output = recordingOutput(false) + const { archive, received, logs } = await uploadThroughLoopback(t, output) + + assert.ok(received.includes(archive)) + assert.deepEqual(logs, [['uploading...']]) + assert.deepEqual(output.writes, []) +}) From 3411ef31f5ba641c81df8e69e495085ae6d35f04 Mon Sep 17 00:00:00 2001 From: Erik Sombroek Date: Fri, 27 Nov 2026 15:38:07 +0100 Subject: [PATCH 2/2] Keep the upload progress line intact on narrow terminals and interrupts The bar never shrank below 10 columns, so on a 40-column terminal the line reached 48 characters and wrapped, and each redraw left part of the previous one behind. Narrow terminals now drop the rate, then the byte counts, then the bar, and always keep the line shorter than the terminal. An interrupt exits without settling the request, so the error document continued the unfinished progress line. The line's finish is now an interrupt cleanup, unregistered once the request settles. Co-Authored-By: Claude Opus 5.5 --- src/p4d.ts | 5 ++ src/upload-progress.ts | 20 +++++--- test/upload-progress.test.ts | 96 +++++++++++++++++++++++++++++++++--- 3 files changed, 109 insertions(+), 12 deletions(-) diff --git a/src/p4d.ts b/src/p4d.ts index b6e2a14..fec28b2 100644 --- a/src/p4d.ts +++ b/src/p4d.ts @@ -1,5 +1,6 @@ import { auth, refresh } from './auth' import { Config } from './config' +import { registerInterruptCleanup } from './errors' import { serviceEnvironment } from './service-environment' import { DEFAULT_UPLOAD_TIMEOUT_MS, timeoutMillisecondsOrDefault } from './timeouts' import { ProgressOutput, uploadProgress } from './upload-progress' @@ -126,6 +127,7 @@ async function doit ( settled = true // End the progress line so what the caller prints next starts on its // own row, even when the answer arrives before the body is sent. + unregisterProgressInterrupt() progress.finish() action() } @@ -173,6 +175,9 @@ async function doit ( // Created only once the request exists: a request that throws while it // is being built must not leave a half-drawn progress line behind. const progress = uploadProgress(buffer.length, progressOutput) + // An interrupt exits without settling, and its error document would + // otherwise continue the unfinished progress line in the terminal. + const unregisterProgressInterrupt = registerInterruptCleanup(progress.finish) writeBody(req, buffer, sent => { progress.update(sent) if (sent === buffer.length) progress.finish() diff --git a/src/upload-progress.ts b/src/upload-progress.ts index 4a5ef79..1effe48 100644 --- a/src/upload-progress.ts +++ b/src/upload-progress.ts @@ -36,12 +36,20 @@ export function uploadProgressLine (sent: number, total: number, elapsedMs: numb const fraction = total > 0 ? Math.min(1, Math.max(0, sent / total)) : 1 const percent = `${Math.floor(fraction * 100)}%`.padStart(4) const rate = elapsedMs > 0 && sent > 0 ? ` ${formatBytes(sent / elapsedMs * 1000)}/s` : '' - const text = `${percent} ${formatBytes(sent)} / ${formatBytes(total)}${rate}` - // Stay one column short of the terminal width: a line that exactly fills it - // wraps in some terminals, and the carriage return then redraws the wrong row. - const width = Math.max(MIN_BAR_WIDTH, Math.min(MAX_BAR_WIDTH, columns - text.length - 4)) - const filled = Math.round(fraction * width) - return `[${'#'.repeat(filled)}${'-'.repeat(width - filled)}] ${text}` + const bytes = `${formatBytes(sent)} / ${formatBytes(total)}` + // Every line stays at least one column short of the terminal width. A line + // that wraps puts the carriage return on its last row, so each redraw would + // leave the start of the previous one behind. Narrow terminals shed the + // rate, then the byte counts, then the bar, keeping the percentage. + for (const text of [`${percent} ${bytes}${rate}`, `${percent} ${bytes}`, percent]) { + const room = columns - text.length - 4 + if (room < MIN_BAR_WIDTH) continue + const width = Math.min(MAX_BAR_WIDTH, room) + const filled = Math.round(fraction * width) + return `[${'#'.repeat(filled)}${'-'.repeat(width - filled)}] ${text}` + } + if (percent.length < columns) return percent + return percent.trim().slice(0, Math.max(0, columns - 1)) } export function uploadProgress (total: number, output: ProgressOutput, now: () => number = Date.now): UploadProgress { diff --git a/test/upload-progress.test.ts b/test/upload-progress.test.ts index 2fcb635..7c0dccb 100644 --- a/test/upload-progress.test.ts +++ b/test/upload-progress.test.ts @@ -2,9 +2,11 @@ import assert from 'node:assert/strict' import { randomBytes } from 'node:crypto' import { writeFileSync } from 'node:fs' import { createServer, request as httpRequest, IncomingMessage, RequestOptions } from 'node:http' +import { Socket } from 'node:net' import { join } from 'node:path' import test, { TestContext } from 'node:test' +import { runInterruptCleanups } from '../src/errors' import { LegacyTransport, postToP4D } from '../src/p4d' import { formatBytes, ProgressOutput, uploadProgress, uploadProgressLine } from '../src/upload-progress' import { temporaryDirectory } from './helpers' @@ -29,13 +31,28 @@ void test('uploadProgressLine shows the bar, percentage, bytes, and rate', () => assert.equal(uploadProgressLine(2000, 2000, 500), `[${'#'.repeat(30)}] 100% 2.0 KB / 2.0 KB 4.0 KB/s`) }) -void test('uploadProgressLine stays narrower than the terminal', () => { - for (const columns of [50, 60, 80, 120]) { - const line = uploadProgressLine(123_456_789, 987_654_321, 12_345, columns) - assert.ok(line.length < columns, `${line.length} < ${columns}: ${line}`) +void test('uploadProgressLine never fills or wraps the terminal', () => { + const samples: Array<[number, number, number]> = [ + [0, 8_400_000, 0], + [123_456, 8_400_000, 900], + [123_456_789, 987_654_321, 12_345], + [987_654_321, 987_654_321, 1] + ] + for (let columns = 1; columns <= 120; columns++) { + for (const [sent, total, elapsed] of samples) { + const line = uploadProgressLine(sent, total, elapsed, columns) + assert.ok(line.length < columns || (columns === 1 && line === ''), `${line.length} < ${columns}: ${line}`) + } } - // Below the minimum bar width the line may wrap, but the bar never vanishes. - assert.match(uploadProgressLine(1, 2, 1, 20), /^\[#{5}-{5}\]/) +}) + +void test('uploadProgressLine sheds detail on narrow terminals but keeps the percentage', () => { + const [sent, total, elapsed] = [123_456, 8_400_000, 900] + assert.equal(uploadProgressLine(sent, total, elapsed, 80), `[${'-'.repeat(30)}] 1% 123.5 KB / 8.4 MB 137.2 KB/s`) + assert.equal(uploadProgressLine(sent, total, elapsed, 40), `[${'-'.repeat(13)}] 1% 123.5 KB / 8.4 MB`) + assert.equal(uploadProgressLine(sent, total, elapsed, 20), `[${'-'.repeat(12)}] 1%`) + assert.equal(uploadProgressLine(sent, total, elapsed, 10), ' 1%') + assert.equal(uploadProgressLine(total, total, elapsed, 4), '100') }) void test('uploadProgress writes nothing when the output is not a terminal', () => { @@ -149,6 +166,73 @@ void test('legacy upload draws progress on a terminal and still sends the exact assert.ok(lines[lines.length - 1].startsWith(`\r[${'#'.repeat(30)}] 100% ${total} / ${total}`), lines[lines.length - 1]) assert.deepEqual(output.writes.filter(text => text === '\n'), ['\n'], 'ends the line exactly once') assert.equal(output.writes[output.writes.length - 1], '\n') + + const written = output.writes.length + runInterruptCleanups() + assert.equal(output.writes.length, written, 'a settled upload leaves no interrupt cleanup behind') +}) + +void test('an interrupt mid-upload ends the progress line before the error is reported', async t => { + const directory = temporaryDirectory(t, 'upload-interrupt') + const archivePath = join(directory, 'build.zip') + // Far more than the loopback socket buffers hold, so with the server not + // reading, the body is provably still being sent when the interrupt lands. + writeFileSync(archivePath, randomBytes(32 * 1024 * 1024)) + + const connections: Socket[] = [] + let requestArrived: () => void = () => {} + const arrived = new Promise(resolve => { requestArrived = resolve }) + const server = createServer(req => { + // Never read the body or answer, so the upload stays open. + req.pause() + requestArrived() + }) + server.on('connection', socket => connections.push(socket)) + t.after(() => { + for (const socket of connections) socket.destroy() + server.close() + }) + const port = await new Promise(resolve => server.listen(0, '127.0.0.1', () => { + const address = server.address() + assert.ok(address !== null && typeof address !== 'string') + resolve(address.port) + })) + const transport = ((options: RequestOptions, callback?: (res: IncomingMessage) => void) => httpRequest({ + ...options, + protocol: 'http:', + hostname: '127.0.0.1', + port, + agent: false + }, callback)) as LegacyTransport + + const originalLog = console.log + console.log = () => {} + const previousTimeout = process.env.POKI_API_TIMEOUT_MS + const previousToken = process.env.POKI_UPLOAD_TOKEN + process.env.POKI_API_TIMEOUT_MS = '300' + process.env.POKI_UPLOAD_TOKEN = 'tok' + t.after(() => { + console.log = originalLog + if (previousTimeout === undefined) delete process.env.POKI_API_TIMEOUT_MS + else process.env.POKI_API_TIMEOUT_MS = previousTimeout + if (previousToken === undefined) delete process.env.POKI_UPLOAD_TOKEN + else process.env.POKI_UPLOAD_TOKEN = previousToken + }) + + const output = recordingOutput(true) + const outcome = postToP4D('game-1', archivePath, 'Release', undefined, false, false, transport, output) + .then(() => undefined, (error: unknown) => error) + await arrived + assert.ok(output.writes.length > 0, 'the progress line is on screen') + assert.notEqual(output.writes[output.writes.length - 1], '\n', 'and still open') + + // What the SIGINT handler in src/process.ts runs before writing the error. + runInterruptCleanups() + assert.equal(output.writes[output.writes.length - 1], '\n') + + // The request then times out; settling must not end the line a second time. + assert.ok(await outcome instanceof Error) + assert.deepEqual(output.writes.filter(text => text === '\n'), ['\n']) }) void test('legacy upload output is unchanged when stdout is not a terminal', async t => {