From 037533e794100306e8e8cca36b01e6612541f95a Mon Sep 17 00:00:00 2001 From: David McKay Date: Fri, 4 Dec 2026 13:00:47 -0800 Subject: [PATCH 1/7] Upload a file in parts, so a slow connection can attach a large one A file attached in one request has to reach the server inside the edge's request timeout. Over a slow upload link a file of a few megabytes can't, however often it is tried. createAttachmentUpload, uploadAttachmentPart and completeAttachmentUpload send it in parts of a size the server chooses, each short enough to arrive, and cancelAttachmentUpload stops one. The deployment says attachmentUploadsInParts where they are served. The one-request uploadConversationAttachment is unchanged. --- api/openapi.yaml | 384 ++++++++++ api/openapi/admin-settings.yaml | 9 + api/openapi/common.yaml | 4 + api/openapi/conversations.yaml | 402 +++++++++++ .../conversations/conversations.msw.ts | 160 +++++ .../generated/conversations/conversations.ts | 673 ++++++++++++++++++ .../conversations/conversations.zod.ts | 206 ++++++ .../model/attachmentTooLargeResponse.ts | 9 + .../model/attachmentUploadConflictResponse.ts | 9 + .../model/attachmentUploadNotFoundResponse.ts | 9 + .../generated/model/attachmentUploadPart.ts | 13 + .../model/attachmentUploadSession.ts | 23 + .../generated/model/attachmentUploadStart.ts | 22 + .../model/cancelAttachmentUploadHeaders.ts | 13 + .../model/completeAttachmentUploadHeaders.ts | 13 + .../model/createAttachmentUploadHeaders.ts | 13 + app/src/lib/api/generated/model/deployment.ts | 2 + app/src/lib/api/generated/model/index.ts | 10 + .../model/uploadAttachmentPartHeaders.ts | 13 + .../organization-settings.msw.ts | 1 + .../organization-settings.zod.ts | 6 + .../generated/conversations/conversations.ts | 159 +++++ .../model/attachmentTooLargeResponse.ts | 9 + .../model/attachmentUploadConflictResponse.ts | 9 + .../model/attachmentUploadNotFoundResponse.ts | 9 + .../generated/model/attachmentUploadPart.ts | 13 + .../model/attachmentUploadSession.ts | 23 + .../generated/model/attachmentUploadStart.ts | 22 + mobile/src/api/generated/model/deployment.ts | 2 + mobile/src/api/generated/model/index.ts | 6 + 30 files changed, 2246 insertions(+) create mode 100644 app/src/lib/api/generated/model/attachmentTooLargeResponse.ts create mode 100644 app/src/lib/api/generated/model/attachmentUploadConflictResponse.ts create mode 100644 app/src/lib/api/generated/model/attachmentUploadNotFoundResponse.ts create mode 100644 app/src/lib/api/generated/model/attachmentUploadPart.ts create mode 100644 app/src/lib/api/generated/model/attachmentUploadSession.ts create mode 100644 app/src/lib/api/generated/model/attachmentUploadStart.ts create mode 100644 app/src/lib/api/generated/model/cancelAttachmentUploadHeaders.ts create mode 100644 app/src/lib/api/generated/model/completeAttachmentUploadHeaders.ts create mode 100644 app/src/lib/api/generated/model/createAttachmentUploadHeaders.ts create mode 100644 app/src/lib/api/generated/model/uploadAttachmentPartHeaders.ts create mode 100644 mobile/src/api/generated/model/attachmentTooLargeResponse.ts create mode 100644 mobile/src/api/generated/model/attachmentUploadConflictResponse.ts create mode 100644 mobile/src/api/generated/model/attachmentUploadNotFoundResponse.ts create mode 100644 mobile/src/api/generated/model/attachmentUploadPart.ts create mode 100644 mobile/src/api/generated/model/attachmentUploadSession.ts create mode 100644 mobile/src/api/generated/model/attachmentUploadStart.ts diff --git a/api/openapi.yaml b/api/openapi.yaml index a100dcece0..49baed20be 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -29575,6 +29575,216 @@ paths: $ref: '#/components/responses/BugReportsUnavailable' default: $ref: '#/components/responses/UnexpectedError' + /api/v2/organizations/{organizationId}/conversations/{conversationId}/attachment-uploads: + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/ConversationId' + post: + tags: + - Conversations + operationId: createAttachmentUpload + summary: Start uploading a file in parts + description: Start an upload of one file to send with the caller's next message in the conversation, sent in parts so that no one request has to carry the whole file. Send each part with uploadAttachmentPart, in any order, then completeAttachmentUpload. The answer says how large each part is (partBytes) and how many there are; every part is exactly partBytes except the last, which holds what is left. An upload not completed by expiresAt is removed with its parts. A file larger than the largest the deployment takes (its attachmentLimits) is refused here (422), before any part is sent. The file is checked when the upload is completed, as uploadConversationAttachment checks it. Offered where the deployment's attachmentUploadsInParts is true. + security: + - webSession: [] + - appOAuth: + - conversations:write + - apiKey: [] + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AttachmentUploadStart' + examples: + example: + $ref: '#/components/examples/AttachmentUploadStartExample' + responses: + '201': + description: The upload is ready for its parts. + headers: + Cache-Control: + $ref: '#/components/headers/PrivateNoStore' + X-Request-Id: + $ref: '#/components/headers/RequestId' + content: + application/json: + schema: + $ref: '#/components/schemas/AttachmentUploadSession' + examples: + example: + $ref: '#/components/examples/AttachmentUploadSessionExample' + '400': + $ref: '#/components/responses/InvalidRequest' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/ConversationNotFound' + '409': + $ref: '#/components/responses/AttachmentConflict' + '422': + $ref: '#/components/responses/AttachmentTooLarge' + '429': + $ref: '#/components/responses/TooManyRequests' + '500': + $ref: '#/components/responses/ServerError' + '503': + $ref: '#/components/responses/ServiceUnavailable' + default: + $ref: '#/components/responses/UnexpectedError' + /api/v2/organizations/{organizationId}/attachment-uploads/{uploadId}: + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/AttachmentUploadId' + delete: + tags: + - Conversations + operationId: cancelAttachmentUpload + summary: Stop an upload + description: Stop an upload the caller started and has not completed, and remove the parts already sent. Stopping one that is already stopped answers 204 again. A completed upload is a file now; remove it with deleteAttachment. + security: + - webSession: [] + - appOAuth: + - conversations:write + - apiKey: [] + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + responses: + '204': + description: The upload is stopped and its parts are removed. + headers: + X-Request-Id: + $ref: '#/components/headers/RequestId' + '400': + $ref: '#/components/responses/InvalidRequest' + '401': + $ref: '#/components/responses/Unauthenticated' + '409': + $ref: '#/components/responses/AttachmentUploadConflict' + '429': + $ref: '#/components/responses/TooManyRequests' + '500': + $ref: '#/components/responses/ServerError' + '503': + $ref: '#/components/responses/ServiceUnavailable' + default: + $ref: '#/components/responses/UnexpectedError' + /api/v2/organizations/{organizationId}/attachment-uploads/{uploadId}/parts/{partNumber}: + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/AttachmentUploadId' + - $ref: '#/components/parameters/AttachmentPartNumber' + put: + tags: + - Conversations + operationId: uploadAttachmentPart + summary: Send one part of a file + description: Send one part of an upload started with createAttachmentUpload, as its bytes. Every part is exactly the upload's partBytes except the last, which holds what is left; a part of any other size is refused. Parts go in any order. Sending a part again replaces it, so after a dropped connection an app sends the part again, with the same Idempotency-Key. + security: + - webSession: [] + - appOAuth: + - conversations:write + - apiKey: [] + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/octet-stream: + schema: + type: string + format: binary + responses: + '200': + description: The part arrived. + headers: + Cache-Control: + $ref: '#/components/headers/PrivateNoStore' + X-Request-Id: + $ref: '#/components/headers/RequestId' + content: + application/json: + schema: + $ref: '#/components/schemas/AttachmentUploadPart' + examples: + example: + $ref: '#/components/examples/AttachmentUploadPartExample' + '400': + $ref: '#/components/responses/InvalidRequest' + '401': + $ref: '#/components/responses/Unauthenticated' + '404': + $ref: '#/components/responses/AttachmentUploadNotFound' + '409': + $ref: '#/components/responses/AttachmentUploadConflict' + '413': + $ref: '#/components/responses/PayloadTooLarge' + '429': + $ref: '#/components/responses/TooManyRequests' + '500': + $ref: '#/components/responses/ServerError' + '503': + $ref: '#/components/responses/ServiceUnavailable' + default: + $ref: '#/components/responses/UnexpectedError' + /api/v2/organizations/{organizationId}/attachment-uploads/{uploadId}/complete: + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/AttachmentUploadId' + post: + tags: + - Conversations + operationId: completeAttachmentUpload + summary: Finish an upload + description: Put an upload's parts together into one file, held for the caller's next message in the conversation exactly as uploadConversationAttachment holds one, and refused for the same reasons. A part that has not arrived is refused (409, naming it); send it and complete again. Completing an upload that was already completed answers the same file again. A refusal for the file itself (its type or its size) ends the upload and removes its parts. + security: + - webSession: [] + - appOAuth: + - conversations:write + - apiKey: [] + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + responses: + '201': + description: The file is held for the next message. + headers: + Cache-Control: + $ref: '#/components/headers/PrivateNoStore' + X-Request-Id: + $ref: '#/components/headers/RequestId' + content: + application/json: + schema: + $ref: '#/components/schemas/Attachment' + examples: + example: + $ref: '#/components/examples/AttachmentExample' + '400': + $ref: '#/components/responses/InvalidRequest' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/AttachmentUploadNotFound' + '409': + $ref: '#/components/responses/AttachmentUploadConflict' + '415': + $ref: '#/components/responses/UnsupportedFile' + '422': + $ref: '#/components/responses/AttachmentTooLarge' + '429': + $ref: '#/components/responses/TooManyRequests' + '500': + $ref: '#/components/responses/ServerError' + '503': + $ref: '#/components/responses/ServiceUnavailable' + default: + $ref: '#/components/responses/UnexpectedError' components: securitySchemes: webSession: @@ -30784,6 +30994,27 @@ components: type: string format: uuid example: 5a1d9e2f-3b4c-4d6e-8f70-9a1b2c3d4e5f + AttachmentUploadId: + name: uploadId + in: path + required: true + description: The upload's id, as createAttachmentUpload gave it. + schema: + type: string + minLength: 1 + maxLength: 256 + pattern: \S + example: 4e2a9c1b-6f0e-4c1e-9d55-2f4a8c1b6e21 + AttachmentPartNumber: + name: partNumber + in: path + required: true + description: Which part of the file, counted from 1. + schema: + type: integer + minimum: 1 + maximum: 10000 + example: 1 headers: PrivateNoStore: description: A Bot is private to the caller. @@ -32314,6 +32545,9 @@ components: description: 'Whether this OpenBot keeps the Windows computers it makes for people (listWindowsComputers and the operations beside it): true even while it can''t make one right now, which the list''s creation says. Absent or false, those operations answer 404, so an app shows nothing about them and doesn''t ask.' attachmentLimits: $ref: '#/components/schemas/AttachmentLimits' + attachmentUploadsInParts: + type: boolean + description: Whether a file can be uploaded in parts (createAttachmentUpload, uploadAttachmentPart and completeAttachmentUpload), so that no one request has to carry the whole file over a slow connection. Absent or false, as from an older OpenBot, send each file in one request with uploadConversationAttachment. attachmentsReadWhole: type: boolean description: Whether a Bot can read the whole of an attached text file or document, page by page, past the first 120000 characters it is shown with the message. Absent or false, as from an older OpenBot, a Bot reads only those first 120000 characters. @@ -51759,6 +51993,63 @@ components: items: type: string format: binary + AttachmentUploadStart: + type: object + additionalProperties: false + required: + - name + - sizeBytes + properties: + name: + type: string + minLength: 1 + maxLength: 1024 + description: The file's name. + sizeBytes: + type: integer + minimum: 1 + description: The file's size, in bytes. The parts must add up to it. + uploadGroup: + type: string + description: Names the message being written, so the files of two windows are counted apart. + maxLength: 200 + AttachmentUploadSession: + type: object + description: An upload waiting for its parts. + required: + - id + - partBytes + - partCount + - expiresAt + properties: + id: + type: string + description: The upload's id. + partBytes: + type: integer + minimum: 1 + description: The size of every part but the last, in bytes. Chosen by OpenBot so that a part reaches it even over a slow connection. + partCount: + type: integer + minimum: 1 + description: How many parts the file is sent in. + expiresAt: + type: string + format: date-time + description: When an upload not yet completed is removed with its parts. + AttachmentUploadPart: + type: object + description: A part that arrived. + required: + - partNumber + - sizeBytes + properties: + partNumber: + type: integer + minimum: 1 + sizeBytes: + type: integer + minimum: 1 responses: InvalidRequest: description: A parameter is malformed. @@ -60433,6 +60724,80 @@ components: retryable: false requestId: req_example traceId: trace_example + AttachmentTooLarge: + description: The file is larger than this OpenBot takes for a file of its kind (the deployment's attachmentLimits). Nothing was kept. + headers: + X-Request-Id: + $ref: '#/components/headers/RequestId' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + tooLarge: + value: + type: https://open.bot/errors/attachment-too-large + title: The file is larger than OpenBot takes. + status: 422 + detail: '''budget.xlsx'' is larger than the 8MB limit for spreadsheets.' + code: ATTACHMENT_TOO_LARGE + category: validation + retryable: false + requestId: req_example + traceId: trace_example + AttachmentUploadConflict: + description: 'The upload cannot take this: a part has not arrived yet, the upload is already completed, the message already holds as many files as it may, or the caller is holding too many unsent files. Or the Idempotency-Key was already used for a different request.' + headers: + X-Request-Id: + $ref: '#/components/headers/RequestId' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + missing: + value: + type: https://open.bot/errors/conflict + title: The request conflicts with the current state. + status: 409 + detail: Part 3 of 'budget.xlsx' hasn't arrived yet. Send it, then finish the upload. + code: CONFLICT + category: conflict + retryable: false + requestId: req_example + traceId: trace_example + reused: + value: + type: https://open.bot/errors/idempotency-key-conflict + title: That Idempotency-Key was used for a different request. + status: 409 + detail: That Idempotency-Key was used for a different request. + code: IDEMPOTENCY_KEY_CONFLICT + category: conflict + retryable: false + requestId: req_example + traceId: trace_example + AttachmentUploadNotFound: + description: The upload does not exist, is another person's, was stopped or has expired, or the organization does not exist. + headers: + X-Request-Id: + $ref: '#/components/headers/RequestId' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + missing: + value: + type: https://open.bot/errors/not-found + title: Not found. + status: 404 + detail: That upload isn't here anymore. Attach the file again. + code: NOT_FOUND + category: not_found + retryable: false + requestId: req_example + traceId: trace_example examples: ReactionPageLast: summary: Every reaction in a conversation, on one page. @@ -60846,6 +61211,7 @@ components: imageBytes: 104857600 documentBytes: 104857600 fileBytes: 104857600 + attachmentUploadsInParts: true attachmentsReadWhole: true api: - v2 @@ -66356,3 +66722,21 @@ components: url: /api/v2/organizations/default/bug-reports/0b6f3c1e-7d2a-4f5b-9c8e-1a2b3c4d5e6f/attachments/5a1d9e2f-3b4c-4d6e-8f70-9a1b2c3d4e5f createdAt: '2026-12-02T18:04:11.000Z' updatedAt: '2026-12-02T18:04:11.000Z' + AttachmentUploadStartExample: + summary: A 10MB workbook to send in parts. + value: + name: budget.xlsx + sizeBytes: 10485760 + uploadGroup: 5d1f0a3e-2c4b-4e6f-8a9d-1b2c3d4e5f60 + AttachmentUploadSessionExample: + summary: Ten parts of 1MB. + value: + id: 4e2a9c1b-6f0e-4c1e-9d55-2f4a8c1b6e21 + partBytes: 1048576 + partCount: 10 + expiresAt: '2026-12-05T12:00:00.000Z' + AttachmentUploadPartExample: + summary: The third part arrived. + value: + partNumber: 3 + sizeBytes: 1048576 diff --git a/api/openapi/admin-settings.yaml b/api/openapi/admin-settings.yaml index f606185529..756e479125 100644 --- a/api/openapi/admin-settings.yaml +++ b/api/openapi/admin-settings.yaml @@ -1486,6 +1486,14 @@ components: shows nothing about them and doesn't ask. attachmentLimits: $ref: '#/components/schemas/AttachmentLimits' + attachmentUploadsInParts: + type: boolean + description: >- + Whether a file can be uploaded in parts (createAttachmentUpload, + uploadAttachmentPart and completeAttachmentUpload), so that no one + request has to carry the whole file over a slow connection. Absent + or false, as from an older OpenBot, send each file in one request + with uploadConversationAttachment. attachmentsReadWhole: type: boolean description: >- @@ -2799,6 +2807,7 @@ components: imageBytes: 104857600 documentBytes: 104857600 fileBytes: 104857600 + attachmentUploadsInParts: true attachmentsReadWhole: true api: [v2] minimumClients: diff --git a/api/openapi/common.yaml b/api/openapi/common.yaml index ab81ffe004..f3848db712 100644 --- a/api/openapi/common.yaml +++ b/api/openapi/common.yaml @@ -642,6 +642,10 @@ paths: /api/v2/organizations/{organizationId}/bug-reports: { $ref: './bug-reports.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1bug-reports' } /api/v2/organizations/{organizationId}/bug-reports/{reportId}: { $ref: './bug-reports.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1bug-reports~1{reportId}' } /api/v2/organizations/{organizationId}/bug-reports/{reportId}/attachments/{attachmentId}: { $ref: './bug-reports.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1bug-reports~1{reportId}~1attachments~1{attachmentId}' } + /api/v2/organizations/{organizationId}/conversations/{conversationId}/attachment-uploads: { $ref: './conversations.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1conversations~1{conversationId}~1attachment-uploads' } + /api/v2/organizations/{organizationId}/attachment-uploads/{uploadId}: { $ref: './conversations.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1attachment-uploads~1{uploadId}' } + /api/v2/organizations/{organizationId}/attachment-uploads/{uploadId}/parts/{partNumber}: { $ref: './conversations.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1attachment-uploads~1{uploadId}~1parts~1{partNumber}' } + /api/v2/organizations/{organizationId}/attachment-uploads/{uploadId}/complete: { $ref: './conversations.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1attachment-uploads~1{uploadId}~1complete' } components: securitySchemes: webSession: diff --git a/api/openapi/conversations.yaml b/api/openapi/conversations.yaml index 4f8c502f33..0d3af36edf 100644 --- a/api/openapi/conversations.yaml +++ b/api/openapi/conversations.yaml @@ -1138,6 +1138,240 @@ paths: $ref: '#/components/responses/ServiceUnavailable' default: $ref: './common.yaml#/components/responses/UnexpectedError' + /api/v2/organizations/{organizationId}/conversations/{conversationId}/attachment-uploads: + parameters: + - $ref: './common.yaml#/components/parameters/OrganizationId' + - $ref: './common.yaml#/components/parameters/ConversationId' + post: + tags: + - Conversations + operationId: createAttachmentUpload + summary: Start uploading a file in parts + description: Start an upload of one file to send with the caller's next + message in the conversation, sent in parts so that no one request has + to carry the whole file. Send each part with uploadAttachmentPart, in + any order, then completeAttachmentUpload. The answer says how large + each part is (partBytes) and how many there are; every part is exactly + partBytes except the last, which holds what is left. An upload not + completed by expiresAt is removed with its parts. A file larger than + the largest the deployment takes (its attachmentLimits) is refused + here (422), before any part is sent. The file is checked when the upload is + completed, as uploadConversationAttachment checks it. Offered where + the deployment's attachmentUploadsInParts is true. + security: + - webSession: [] + - appOAuth: + - conversations:write + - apiKey: [] + parameters: + - $ref: './common.yaml#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AttachmentUploadStart' + examples: + example: + $ref: '#/components/examples/AttachmentUploadStartExample' + responses: + '201': + description: The upload is ready for its parts. + headers: + Cache-Control: + $ref: './common.yaml#/components/headers/PrivateNoStore' + X-Request-Id: + $ref: './common.yaml#/components/headers/RequestId' + content: + application/json: + schema: + $ref: '#/components/schemas/AttachmentUploadSession' + examples: + example: + $ref: '#/components/examples/AttachmentUploadSessionExample' + '400': + $ref: './common.yaml#/components/responses/InvalidRequest' + '401': + $ref: './common.yaml#/components/responses/Unauthenticated' + '403': + $ref: './common.yaml#/components/responses/Forbidden' + '404': + $ref: './common.yaml#/components/responses/ConversationNotFound' + '409': + $ref: '#/components/responses/AttachmentConflict' + '422': + $ref: '#/components/responses/AttachmentTooLarge' + '429': + $ref: './common.yaml#/components/responses/TooManyRequests' + '500': + $ref: './common.yaml#/components/responses/ServerError' + '503': + $ref: '#/components/responses/ServiceUnavailable' + default: + $ref: './common.yaml#/components/responses/UnexpectedError' + /api/v2/organizations/{organizationId}/attachment-uploads/{uploadId}: + parameters: + - $ref: './common.yaml#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/AttachmentUploadId' + delete: + tags: + - Conversations + operationId: cancelAttachmentUpload + summary: Stop an upload + description: Stop an upload the caller started and has not completed, and + remove the parts already sent. Stopping one that is already stopped + answers 204 again. A completed upload is a file now; remove it with + deleteAttachment. + security: + - webSession: [] + - appOAuth: + - conversations:write + - apiKey: [] + parameters: + - $ref: './common.yaml#/components/parameters/IdempotencyKey' + responses: + '204': + description: The upload is stopped and its parts are removed. + headers: + X-Request-Id: + $ref: './common.yaml#/components/headers/RequestId' + '400': + $ref: './common.yaml#/components/responses/InvalidRequest' + '401': + $ref: './common.yaml#/components/responses/Unauthenticated' + '409': + $ref: '#/components/responses/AttachmentUploadConflict' + '429': + $ref: './common.yaml#/components/responses/TooManyRequests' + '500': + $ref: './common.yaml#/components/responses/ServerError' + '503': + $ref: '#/components/responses/ServiceUnavailable' + default: + $ref: './common.yaml#/components/responses/UnexpectedError' + /api/v2/organizations/{organizationId}/attachment-uploads/{uploadId}/parts/{partNumber}: + parameters: + - $ref: './common.yaml#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/AttachmentUploadId' + - $ref: '#/components/parameters/AttachmentPartNumber' + put: + tags: + - Conversations + operationId: uploadAttachmentPart + summary: Send one part of a file + description: Send one part of an upload started with + createAttachmentUpload, as its bytes. Every part is exactly the + upload's partBytes except the last, which holds what is left; a part + of any other size is refused. Parts go in any order. Sending a part + again replaces it, so after a dropped connection an app sends the + part again, with the same Idempotency-Key. + security: + - webSession: [] + - appOAuth: + - conversations:write + - apiKey: [] + parameters: + - $ref: './common.yaml#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/octet-stream: + schema: + type: string + format: binary + responses: + '200': + description: The part arrived. + headers: + Cache-Control: + $ref: './common.yaml#/components/headers/PrivateNoStore' + X-Request-Id: + $ref: './common.yaml#/components/headers/RequestId' + content: + application/json: + schema: + $ref: '#/components/schemas/AttachmentUploadPart' + examples: + example: + $ref: '#/components/examples/AttachmentUploadPartExample' + '400': + $ref: './common.yaml#/components/responses/InvalidRequest' + '401': + $ref: './common.yaml#/components/responses/Unauthenticated' + '404': + $ref: '#/components/responses/AttachmentUploadNotFound' + '409': + $ref: '#/components/responses/AttachmentUploadConflict' + '413': + $ref: './common.yaml#/components/responses/PayloadTooLarge' + '429': + $ref: './common.yaml#/components/responses/TooManyRequests' + '500': + $ref: './common.yaml#/components/responses/ServerError' + '503': + $ref: '#/components/responses/ServiceUnavailable' + default: + $ref: './common.yaml#/components/responses/UnexpectedError' + /api/v2/organizations/{organizationId}/attachment-uploads/{uploadId}/complete: + parameters: + - $ref: './common.yaml#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/AttachmentUploadId' + post: + tags: + - Conversations + operationId: completeAttachmentUpload + summary: Finish an upload + description: Put an upload's parts together into one file, held for the + caller's next message in the conversation exactly as + uploadConversationAttachment holds one, and refused for the same + reasons. A part that has not arrived is refused (409, naming it); send + it and complete again. Completing an upload that was already completed + answers the same file again. A refusal for the file itself (its type + or its size) ends the upload and removes its parts. + security: + - webSession: [] + - appOAuth: + - conversations:write + - apiKey: [] + parameters: + - $ref: './common.yaml#/components/parameters/IdempotencyKey' + responses: + '201': + description: The file is held for the next message. + headers: + Cache-Control: + $ref: './common.yaml#/components/headers/PrivateNoStore' + X-Request-Id: + $ref: './common.yaml#/components/headers/RequestId' + content: + application/json: + schema: + $ref: '#/components/schemas/Attachment' + examples: + example: + $ref: '#/components/examples/AttachmentExample' + '400': + $ref: './common.yaml#/components/responses/InvalidRequest' + '401': + $ref: './common.yaml#/components/responses/Unauthenticated' + '403': + $ref: './common.yaml#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/AttachmentUploadNotFound' + '409': + $ref: '#/components/responses/AttachmentUploadConflict' + '415': + $ref: '#/components/responses/UnsupportedFile' + '422': + $ref: '#/components/responses/AttachmentTooLarge' + '429': + $ref: './common.yaml#/components/responses/TooManyRequests' + '500': + $ref: './common.yaml#/components/responses/ServerError' + '503': + $ref: '#/components/responses/ServiceUnavailable' + default: + $ref: './common.yaml#/components/responses/UnexpectedError' /api/v2/organizations/{organizationId}/conversations/{conversationId}/voice-calls: parameters: - $ref: './common.yaml#/components/parameters/OrganizationId' @@ -2334,6 +2568,27 @@ components: maxLength: 256 pattern: \S example: 0b1c6f0e-7f0e-4c1e-9d55-2f4a8c1b6e21 + AttachmentUploadId: + name: uploadId + in: path + required: true + description: The upload's id, as createAttachmentUpload gave it. + schema: + type: string + minLength: 1 + maxLength: 256 + pattern: \S + example: 4e2a9c1b-6f0e-4c1e-9d55-2f4a8c1b6e21 + AttachmentPartNumber: + name: partNumber + in: path + required: true + description: Which part of the file, counted from 1. + schema: + type: integer + minimum: 1 + maximum: 10000 + example: 1 ConversationThreadId: name: threadId in: path @@ -3428,6 +3683,65 @@ components: description: Names the message being written, so the files of two windows are counted apart. maxLength: 200 + AttachmentUploadStart: + type: object + additionalProperties: false + required: + - name + - sizeBytes + properties: + name: + type: string + minLength: 1 + maxLength: 1024 + description: The file's name. + sizeBytes: + type: integer + minimum: 1 + description: The file's size, in bytes. The parts must add up to it. + uploadGroup: + type: string + description: Names the message being written, so the files of two windows + are counted apart. + maxLength: 200 + AttachmentUploadSession: + type: object + description: An upload waiting for its parts. + required: + - id + - partBytes + - partCount + - expiresAt + properties: + id: + type: string + description: The upload's id. + partBytes: + type: integer + minimum: 1 + description: The size of every part but the last, in bytes. Chosen by + OpenBot so that a part reaches it even over a slow connection. + partCount: + type: integer + minimum: 1 + description: How many parts the file is sent in. + expiresAt: + type: string + format: date-time + description: When an upload not yet completed is removed with its parts. + AttachmentUploadPart: + type: object + description: A part that arrived. + required: + - partNumber + - sizeBytes + properties: + partNumber: + type: integer + minimum: 1 + sizeBytes: + type: integer + minimum: 1 ConversationThread: type: object required: @@ -4138,6 +4452,85 @@ components: retryable: false requestId: req_example traceId: trace_example + AttachmentUploadNotFound: + description: The upload does not exist, is another person's, was stopped or + has expired, or the organization does not exist. + headers: + X-Request-Id: + $ref: './common.yaml#/components/headers/RequestId' + content: + application/problem+json: + schema: + $ref: './common.yaml#/components/schemas/Problem' + examples: + missing: + value: + type: https://open.bot/errors/not-found + title: Not found. + status: 404 + detail: That upload isn't here anymore. Attach the file again. + code: NOT_FOUND + category: not_found + retryable: false + requestId: req_example + traceId: trace_example + AttachmentTooLarge: + description: The file is larger than this OpenBot takes for a file of its + kind (the deployment's attachmentLimits). Nothing was kept. + headers: + X-Request-Id: + $ref: './common.yaml#/components/headers/RequestId' + content: + application/problem+json: + schema: + $ref: './common.yaml#/components/schemas/Problem' + examples: + tooLarge: + value: + type: https://open.bot/errors/attachment-too-large + title: The file is larger than OpenBot takes. + status: 422 + detail: "'budget.xlsx' is larger than the 8MB limit for spreadsheets." + code: ATTACHMENT_TOO_LARGE + category: validation + retryable: false + requestId: req_example + traceId: trace_example + AttachmentUploadConflict: + description: 'The upload cannot take this: a part has not arrived yet, the + upload is already completed, the message already holds as many files as + it may, or the caller is holding too many unsent files. Or the + Idempotency-Key was already used for a different request.' + headers: + X-Request-Id: + $ref: './common.yaml#/components/headers/RequestId' + content: + application/problem+json: + schema: + $ref: './common.yaml#/components/schemas/Problem' + examples: + missing: + value: + type: https://open.bot/errors/conflict + title: The request conflicts with the current state. + status: 409 + detail: Part 3 of 'budget.xlsx' hasn't arrived yet. Send it, then finish the upload. + code: CONFLICT + category: conflict + retryable: false + requestId: req_example + traceId: trace_example + reused: + value: + type: https://open.bot/errors/idempotency-key-conflict + title: That Idempotency-Key was used for a different request. + status: 409 + detail: That Idempotency-Key was used for a different request. + code: IDEMPOTENCY_KEY_CONFLICT + category: conflict + retryable: false + requestId: req_example + traceId: trace_example TaskNotFound: description: The task does not exist or is another person's, or the organization does not exist. @@ -4339,6 +4732,15 @@ components: AttachmentExample: summary: "A spreadsheet held for the next message." value: {"id": "0b1c6f0e-7f0e-4c1e-9d55-2f4a8c1b6e21", "name": "budget.csv", "mimeType": "text/csv", "sizeBytes": 2048} + AttachmentUploadStartExample: + summary: "A 10MB workbook to send in parts." + value: {"name": "budget.xlsx", "sizeBytes": 10485760, "uploadGroup": "5d1f0a3e-2c4b-4e6f-8a9d-1b2c3d4e5f60"} + AttachmentUploadSessionExample: + summary: "Ten parts of 1MB." + value: {"id": "4e2a9c1b-6f0e-4c1e-9d55-2f4a8c1b6e21", "partBytes": 1048576, "partCount": 10, "expiresAt": "2026-12-05T12:00:00.000Z"} + AttachmentUploadPartExample: + summary: "The third part arrived." + value: {"partNumber": 3, "sizeBytes": 1048576} VoiceConnectionExample: summary: "A call over WebRTC." value: {"transport": "webrtc", "sdp": "v=0\r\no=- 0 0 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"} diff --git a/app/src/lib/api/generated/conversations/conversations.msw.ts b/app/src/lib/api/generated/conversations/conversations.msw.ts index 3883da8c4c..883183ca41 100644 --- a/app/src/lib/api/generated/conversations/conversations.msw.ts +++ b/app/src/lib/api/generated/conversations/conversations.msw.ts @@ -9,6 +9,9 @@ import type { AddedConversationMember, Attachment, AttachmentUpload, + AttachmentUploadPart, + AttachmentUploadSession, + AttachmentUploadStart, ConversationActivity, ConversationBusy, ConversationJoinToken, @@ -217,6 +220,24 @@ export const getStopConversationRunResponseMock = () => ({ }, }); +export const getCreateAttachmentUploadResponseMock = + (): AttachmentUploadSession => ({ + id: "4e2a9c1b-6f0e-4c1e-9d55-2f4a8c1b6e21", + partBytes: 1048576, + partCount: 10, + expiresAt: "2026-12-05T12:00:00.000Z", + }); + +export const getUploadAttachmentPartResponseMock = + (): AttachmentUploadPart => ({ partNumber: 3, sizeBytes: 1048576 }); + +export const getCompleteAttachmentUploadResponseMock = (): Attachment => ({ + id: "0b1c6f0e-7f0e-4c1e-9d55-2f4a8c1b6e21", + name: "budget.csv", + mimeType: "text/csv", + sizeBytes: 2048, +}); + export const getCreateConversationJoinTokenMockHandler = ( overrideResponse?: | ConversationJoinToken @@ -1024,6 +1045,141 @@ export const getStopConversationRunMockHandler = ( options, ); }; + +export const getCreateAttachmentUploadMockHandler = ( + overrideResponse?: + | AttachmentUploadSession + | (( + info: Parameters< + HttpResponseResolver< + { organizationId: string; conversationId: string }, + AttachmentUploadStart + > + >[0], + ) => Promise | AttachmentUploadSession), + options?: RequestHandlerOptions, +) => { + return http.post< + { organizationId: string; conversationId: string }, + AttachmentUploadStart + >( + "*/api/v2/organizations/:organizationId/conversations/:conversationId/attachment-uploads", + async ( + info: Parameters< + HttpResponseResolver< + { organizationId: string; conversationId: string }, + AttachmentUploadStart + > + >[0], + ) => { + return HttpResponse.json( + overrideResponse !== undefined + ? typeof overrideResponse === "function" + ? await overrideResponse(info) + : overrideResponse + : getCreateAttachmentUploadResponseMock(), + { status: 201 }, + ); + }, + options, + ); +}; + +export const getCancelAttachmentUploadMockHandler = ( + overrideResponse?: + | void + | (( + info: Parameters< + HttpResponseResolver<{ organizationId: string; uploadId: string }> + >[0], + ) => Promise | void), + options?: RequestHandlerOptions, +) => { + return http.delete<{ organizationId: string; uploadId: string }>( + "*/api/v2/organizations/:organizationId/attachment-uploads/:uploadId", + async ( + info: Parameters< + HttpResponseResolver<{ organizationId: string; uploadId: string }> + >[0], + ) => { + if (typeof overrideResponse === "function") { + await overrideResponse(info); + } + + return new HttpResponse(null, { status: 204 }); + }, + options, + ); +}; + +export const getUploadAttachmentPartMockHandler = ( + overrideResponse?: + | AttachmentUploadPart + | (( + info: Parameters< + HttpResponseResolver< + { organizationId: string; uploadId: string; partNumber: string }, + Blob + > + >[0], + ) => Promise | AttachmentUploadPart), + options?: RequestHandlerOptions, +) => { + return http.put< + { organizationId: string; uploadId: string; partNumber: string }, + Blob + >( + "*/api/v2/organizations/:organizationId/attachment-uploads/:uploadId/parts/:partNumber", + async ( + info: Parameters< + HttpResponseResolver< + { organizationId: string; uploadId: string; partNumber: string }, + Blob + > + >[0], + ) => { + return HttpResponse.json( + overrideResponse !== undefined + ? typeof overrideResponse === "function" + ? await overrideResponse(info) + : overrideResponse + : getUploadAttachmentPartResponseMock(), + { status: 200 }, + ); + }, + options, + ); +}; + +export const getCompleteAttachmentUploadMockHandler = ( + overrideResponse?: + | Attachment + | (( + info: Parameters< + HttpResponseResolver<{ organizationId: string; uploadId: string }> + >[0], + ) => Promise | Attachment), + options?: RequestHandlerOptions, +) => { + return http.post<{ organizationId: string; uploadId: string }>( + "*/api/v2/organizations/:organizationId/attachment-uploads/:uploadId/complete", + async ( + info: Parameters< + HttpResponseResolver<{ organizationId: string; uploadId: string }> + >[0], + ) => { + return HttpResponse.json( + overrideResponse !== undefined + ? typeof overrideResponse === "function" + ? await overrideResponse(info) + : overrideResponse + : getCompleteAttachmentUploadResponseMock(), + { status: 201 }, + ); + }, + options, + ); +}; export const getConversationsMock = () => [ getCreateConversationJoinTokenMockHandler(), getListConversationsMockHandler(), @@ -1049,4 +1205,8 @@ export const getConversationsMock = () => [ getCreateTranscriptionMockHandler(), getGetConversationRunMockHandler(), getStopConversationRunMockHandler(), + getCreateAttachmentUploadMockHandler(), + getCancelAttachmentUploadMockHandler(), + getUploadAttachmentPartMockHandler(), + getCompleteAttachmentUploadMockHandler(), ]; diff --git a/app/src/lib/api/generated/conversations/conversations.ts b/app/src/lib/api/generated/conversations/conversations.ts index 0668dc67c3..2ca71e0a7d 100644 --- a/app/src/lib/api/generated/conversations/conversations.ts +++ b/app/src/lib/api/generated/conversations/conversations.ts @@ -24,8 +24,16 @@ import type { Attachment, AttachmentConflictResponse, AttachmentNotFoundResponse, + AttachmentTooLargeResponse, AttachmentUpload, + AttachmentUploadConflictResponse, + AttachmentUploadNotFoundResponse, + AttachmentUploadPart, + AttachmentUploadSession, + AttachmentUploadStart, BotNotFoundResponse, + CancelAttachmentUploadHeaders, + CompleteAttachmentUploadHeaders, ConversationActivity, ConversationBusy, ConversationConflictResponse, @@ -40,6 +48,7 @@ import type { ConversationRunResponse, ConversationThread, ConversationThreadStatus, + CreateAttachmentUploadHeaders, CreateConversationHeaders, CreateConversationJoinTokenHeaders, CreateConversationRequest, @@ -84,6 +93,7 @@ import type { UpdateConversationHeaders, UpdateConversationRequest, UpdatedConversation, + UploadAttachmentPartHeaders, UploadConversationAttachmentHeaders, } from "../model"; @@ -4723,3 +4733,666 @@ export const useStopConversationRun = < queryClient, ); }; +export const getCreateAttachmentUploadUrl = ( + organizationId: string, + conversationId: string, +) => { + return `/api/v2/organizations/${encodeURIComponent(String(organizationId))}/conversations/${encodeURIComponent(String(conversationId))}/attachment-uploads`; +}; + +/** + * Start an upload of one file to send with the caller's next message in the conversation, sent in parts so that no one request has to carry the whole file. Send each part with uploadAttachmentPart, in any order, then completeAttachmentUpload. The answer says how large each part is (partBytes) and how many there are; every part is exactly partBytes except the last, which holds what is left. An upload not completed by expiresAt is removed with its parts. A file larger than the largest the deployment takes (its attachmentLimits) is refused here (422), before any part is sent. The file is checked when the upload is completed, as uploadConversationAttachment checks it. Offered where the deployment's attachmentUploadsInParts is true. + * @summary Start uploading a file in parts + */ +export const createAttachmentUpload = async ( + organizationId: string, + conversationId: string, + attachmentUploadStart: AttachmentUploadStart, + headers: CreateAttachmentUploadHeaders, + options?: Parameters[1], +): Promise => { + const getHeaders = ( + h?: NonNullable, + ): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from( + h as Iterable>, + (entry) => Array.from(entry) as [string, string], + ), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries< + string | readonly string[] | undefined + >(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; + return apiRequest( + getCreateAttachmentUploadUrl(organizationId, conversationId), + { + ...options, + method: "POST", + headers: { + "Content-Type": "application/json", + ...headers, + ...getHeaders(options?.headers), + }, + body: JSON.stringify(attachmentUploadStart), + }, + ); +}; + +export const getCreateAttachmentUploadMutationKey = () => + ["createAttachmentUpload"] as const; + +export const getCreateAttachmentUploadMutationOptions = < + TError = + | InvalidRequestResponse + | UnauthenticatedResponse + | ForbiddenResponse + | ConversationNotFoundResponse + | AttachmentConflictResponse + | AttachmentTooLargeResponse + | TooManyRequestsResponse + | ServerErrorResponse + | ServiceUnavailableResponse + | UnexpectedErrorResponse, + TContext = unknown, +>(options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + CreateAttachmentUploadMutationVariables, + TContext + >; + request?: SecondParameter; +}): UseMutationOptions< + Awaited>, + TError, + CreateAttachmentUploadMutationVariables, + TContext +> => { + const mutationKey = getCreateAttachmentUploadMutationKey(); + const { mutation: mutationOptions, request: requestOptions } = options + ? options.mutation && + "mutationKey" in options.mutation && + options.mutation.mutationKey + ? options + : { ...options, mutation: { ...options.mutation, mutationKey } } + : { mutation: { mutationKey }, request: undefined }; + + const mutationFn: MutationFunction< + Awaited>, + CreateAttachmentUploadMutationVariables + > = (props) => { + const { organizationId, conversationId, data, headers } = props ?? {}; + + return createAttachmentUpload( + organizationId, + conversationId, + data, + headers, + requestOptions, + ); + }; + + return { mutationFn, ...mutationOptions }; +}; + +export type CreateAttachmentUploadMutationResult = NonNullable< + Awaited> +>; +export type CreateAttachmentUploadMutationBody = AttachmentUploadStart; +export type CreateAttachmentUploadMutationError = + | InvalidRequestResponse + | UnauthenticatedResponse + | ForbiddenResponse + | ConversationNotFoundResponse + | AttachmentConflictResponse + | AttachmentTooLargeResponse + | TooManyRequestsResponse + | ServerErrorResponse + | ServiceUnavailableResponse + | UnexpectedErrorResponse; +export type CreateAttachmentUploadMutationVariables = { + organizationId: string; + conversationId: string; + data: AttachmentUploadStart; + headers: CreateAttachmentUploadHeaders; +}; + +/** + * @summary Start uploading a file in parts + */ +export const useCreateAttachmentUpload = < + TError = + | InvalidRequestResponse + | UnauthenticatedResponse + | ForbiddenResponse + | ConversationNotFoundResponse + | AttachmentConflictResponse + | AttachmentTooLargeResponse + | TooManyRequestsResponse + | ServerErrorResponse + | ServiceUnavailableResponse + | UnexpectedErrorResponse, + TContext = unknown, +>( + options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + CreateAttachmentUploadMutationVariables, + TContext + >; + request?: SecondParameter; + }, + queryClient?: QueryClient, +): UseMutationResult< + Awaited>, + TError, + CreateAttachmentUploadMutationVariables, + TContext +> => { + return useMutation( + getCreateAttachmentUploadMutationOptions(options), + queryClient, + ); +}; +export const getCancelAttachmentUploadUrl = ( + organizationId: string, + uploadId: string, +) => { + return `/api/v2/organizations/${encodeURIComponent(String(organizationId))}/attachment-uploads/${encodeURIComponent(String(uploadId))}`; +}; + +/** + * Stop an upload the caller started and has not completed, and remove the parts already sent. Stopping one that is already stopped answers 204 again. A completed upload is a file now; remove it with deleteAttachment. + * @summary Stop an upload + */ +export const cancelAttachmentUpload = async ( + organizationId: string, + uploadId: string, + headers: CancelAttachmentUploadHeaders, + options?: Parameters[1], +): Promise => { + const getHeaders = ( + h?: NonNullable, + ): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from( + h as Iterable>, + (entry) => Array.from(entry) as [string, string], + ), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries< + string | readonly string[] | undefined + >(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; + return apiRequest( + getCancelAttachmentUploadUrl(organizationId, uploadId), + { + ...options, + method: "DELETE", + headers: { ...headers, ...getHeaders(options?.headers) }, + }, + ); +}; + +export const getCancelAttachmentUploadMutationKey = () => + ["cancelAttachmentUpload"] as const; + +export const getCancelAttachmentUploadMutationOptions = < + TError = + | InvalidRequestResponse + | UnauthenticatedResponse + | AttachmentUploadConflictResponse + | TooManyRequestsResponse + | ServerErrorResponse + | ServiceUnavailableResponse + | UnexpectedErrorResponse, + TContext = unknown, +>(options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + CancelAttachmentUploadMutationVariables, + TContext + >; + request?: SecondParameter; +}): UseMutationOptions< + Awaited>, + TError, + CancelAttachmentUploadMutationVariables, + TContext +> => { + const mutationKey = getCancelAttachmentUploadMutationKey(); + const { mutation: mutationOptions, request: requestOptions } = options + ? options.mutation && + "mutationKey" in options.mutation && + options.mutation.mutationKey + ? options + : { ...options, mutation: { ...options.mutation, mutationKey } } + : { mutation: { mutationKey }, request: undefined }; + + const mutationFn: MutationFunction< + Awaited>, + CancelAttachmentUploadMutationVariables + > = (props) => { + const { organizationId, uploadId, headers } = props ?? {}; + + return cancelAttachmentUpload( + organizationId, + uploadId, + headers, + requestOptions, + ); + }; + + return { mutationFn, ...mutationOptions }; +}; + +export type CancelAttachmentUploadMutationResult = NonNullable< + Awaited> +>; + +export type CancelAttachmentUploadMutationError = + | InvalidRequestResponse + | UnauthenticatedResponse + | AttachmentUploadConflictResponse + | TooManyRequestsResponse + | ServerErrorResponse + | ServiceUnavailableResponse + | UnexpectedErrorResponse; +export type CancelAttachmentUploadMutationVariables = { + organizationId: string; + uploadId: string; + headers: CancelAttachmentUploadHeaders; +}; + +/** + * @summary Stop an upload + */ +export const useCancelAttachmentUpload = < + TError = + | InvalidRequestResponse + | UnauthenticatedResponse + | AttachmentUploadConflictResponse + | TooManyRequestsResponse + | ServerErrorResponse + | ServiceUnavailableResponse + | UnexpectedErrorResponse, + TContext = unknown, +>( + options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + CancelAttachmentUploadMutationVariables, + TContext + >; + request?: SecondParameter; + }, + queryClient?: QueryClient, +): UseMutationResult< + Awaited>, + TError, + CancelAttachmentUploadMutationVariables, + TContext +> => { + return useMutation( + getCancelAttachmentUploadMutationOptions(options), + queryClient, + ); +}; +export const getUploadAttachmentPartUrl = ( + organizationId: string, + uploadId: string, + partNumber: number, +) => { + return `/api/v2/organizations/${encodeURIComponent(String(organizationId))}/attachment-uploads/${encodeURIComponent(String(uploadId))}/parts/${encodeURIComponent(String(partNumber))}`; +}; + +/** + * Send one part of an upload started with createAttachmentUpload, as its bytes. Every part is exactly the upload's partBytes except the last, which holds what is left; a part of any other size is refused. Parts go in any order. Sending a part again replaces it, so after a dropped connection an app sends the part again, with the same Idempotency-Key. + * @summary Send one part of a file + */ +export const uploadAttachmentPart = async ( + organizationId: string, + uploadId: string, + partNumber: number, + uploadAttachmentPartBody: Blob, + headers: UploadAttachmentPartHeaders, + options?: Parameters[1], +): Promise => { + const getHeaders = ( + h?: NonNullable, + ): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from( + h as Iterable>, + (entry) => Array.from(entry) as [string, string], + ), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries< + string | readonly string[] | undefined + >(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; + return apiRequest( + getUploadAttachmentPartUrl(organizationId, uploadId, partNumber), + { + ...options, + method: "PUT", + headers: { + "Content-Type": "application/octet-stream", + ...headers, + ...getHeaders(options?.headers), + }, + body: uploadAttachmentPartBody, + }, + ); +}; + +export const getUploadAttachmentPartMutationKey = () => + ["uploadAttachmentPart"] as const; + +export const getUploadAttachmentPartMutationOptions = < + TError = + | InvalidRequestResponse + | UnauthenticatedResponse + | AttachmentUploadNotFoundResponse + | AttachmentUploadConflictResponse + | PayloadTooLargeResponse + | TooManyRequestsResponse + | ServerErrorResponse + | ServiceUnavailableResponse + | UnexpectedErrorResponse, + TContext = unknown, +>(options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + UploadAttachmentPartMutationVariables, + TContext + >; + request?: SecondParameter; +}): UseMutationOptions< + Awaited>, + TError, + UploadAttachmentPartMutationVariables, + TContext +> => { + const mutationKey = getUploadAttachmentPartMutationKey(); + const { mutation: mutationOptions, request: requestOptions } = options + ? options.mutation && + "mutationKey" in options.mutation && + options.mutation.mutationKey + ? options + : { ...options, mutation: { ...options.mutation, mutationKey } } + : { mutation: { mutationKey }, request: undefined }; + + const mutationFn: MutationFunction< + Awaited>, + UploadAttachmentPartMutationVariables + > = (props) => { + const { organizationId, uploadId, partNumber, data, headers } = props ?? {}; + + return uploadAttachmentPart( + organizationId, + uploadId, + partNumber, + data, + headers, + requestOptions, + ); + }; + + return { mutationFn, ...mutationOptions }; +}; + +export type UploadAttachmentPartMutationResult = NonNullable< + Awaited> +>; +export type UploadAttachmentPartMutationBody = Blob; +export type UploadAttachmentPartMutationError = + | InvalidRequestResponse + | UnauthenticatedResponse + | AttachmentUploadNotFoundResponse + | AttachmentUploadConflictResponse + | PayloadTooLargeResponse + | TooManyRequestsResponse + | ServerErrorResponse + | ServiceUnavailableResponse + | UnexpectedErrorResponse; +export type UploadAttachmentPartMutationVariables = { + organizationId: string; + uploadId: string; + partNumber: number; + data: Blob; + headers: UploadAttachmentPartHeaders; +}; + +/** + * @summary Send one part of a file + */ +export const useUploadAttachmentPart = < + TError = + | InvalidRequestResponse + | UnauthenticatedResponse + | AttachmentUploadNotFoundResponse + | AttachmentUploadConflictResponse + | PayloadTooLargeResponse + | TooManyRequestsResponse + | ServerErrorResponse + | ServiceUnavailableResponse + | UnexpectedErrorResponse, + TContext = unknown, +>( + options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + UploadAttachmentPartMutationVariables, + TContext + >; + request?: SecondParameter; + }, + queryClient?: QueryClient, +): UseMutationResult< + Awaited>, + TError, + UploadAttachmentPartMutationVariables, + TContext +> => { + return useMutation( + getUploadAttachmentPartMutationOptions(options), + queryClient, + ); +}; +export const getCompleteAttachmentUploadUrl = ( + organizationId: string, + uploadId: string, +) => { + return `/api/v2/organizations/${encodeURIComponent(String(organizationId))}/attachment-uploads/${encodeURIComponent(String(uploadId))}/complete`; +}; + +/** + * Put an upload's parts together into one file, held for the caller's next message in the conversation exactly as uploadConversationAttachment holds one, and refused for the same reasons. A part that has not arrived is refused (409, naming it); send it and complete again. Completing an upload that was already completed answers the same file again. A refusal for the file itself (its type or its size) ends the upload and removes its parts. + * @summary Finish an upload + */ +export const completeAttachmentUpload = async ( + organizationId: string, + uploadId: string, + headers: CompleteAttachmentUploadHeaders, + options?: Parameters[1], +): Promise => { + const getHeaders = ( + h?: NonNullable, + ): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from( + h as Iterable>, + (entry) => Array.from(entry) as [string, string], + ), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries< + string | readonly string[] | undefined + >(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; + return apiRequest( + getCompleteAttachmentUploadUrl(organizationId, uploadId), + { + ...options, + method: "POST", + headers: { ...headers, ...getHeaders(options?.headers) }, + }, + ); +}; + +export const getCompleteAttachmentUploadMutationKey = () => + ["completeAttachmentUpload"] as const; + +export const getCompleteAttachmentUploadMutationOptions = < + TError = + | InvalidRequestResponse + | UnauthenticatedResponse + | ForbiddenResponse + | AttachmentUploadNotFoundResponse + | AttachmentUploadConflictResponse + | UnsupportedFileResponse + | AttachmentTooLargeResponse + | TooManyRequestsResponse + | ServerErrorResponse + | ServiceUnavailableResponse + | UnexpectedErrorResponse, + TContext = unknown, +>(options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + CompleteAttachmentUploadMutationVariables, + TContext + >; + request?: SecondParameter; +}): UseMutationOptions< + Awaited>, + TError, + CompleteAttachmentUploadMutationVariables, + TContext +> => { + const mutationKey = getCompleteAttachmentUploadMutationKey(); + const { mutation: mutationOptions, request: requestOptions } = options + ? options.mutation && + "mutationKey" in options.mutation && + options.mutation.mutationKey + ? options + : { ...options, mutation: { ...options.mutation, mutationKey } } + : { mutation: { mutationKey }, request: undefined }; + + const mutationFn: MutationFunction< + Awaited>, + CompleteAttachmentUploadMutationVariables + > = (props) => { + const { organizationId, uploadId, headers } = props ?? {}; + + return completeAttachmentUpload( + organizationId, + uploadId, + headers, + requestOptions, + ); + }; + + return { mutationFn, ...mutationOptions }; +}; + +export type CompleteAttachmentUploadMutationResult = NonNullable< + Awaited> +>; + +export type CompleteAttachmentUploadMutationError = + | InvalidRequestResponse + | UnauthenticatedResponse + | ForbiddenResponse + | AttachmentUploadNotFoundResponse + | AttachmentUploadConflictResponse + | UnsupportedFileResponse + | AttachmentTooLargeResponse + | TooManyRequestsResponse + | ServerErrorResponse + | ServiceUnavailableResponse + | UnexpectedErrorResponse; +export type CompleteAttachmentUploadMutationVariables = { + organizationId: string; + uploadId: string; + headers: CompleteAttachmentUploadHeaders; +}; + +/** + * @summary Finish an upload + */ +export const useCompleteAttachmentUpload = < + TError = + | InvalidRequestResponse + | UnauthenticatedResponse + | ForbiddenResponse + | AttachmentUploadNotFoundResponse + | AttachmentUploadConflictResponse + | UnsupportedFileResponse + | AttachmentTooLargeResponse + | TooManyRequestsResponse + | ServerErrorResponse + | ServiceUnavailableResponse + | UnexpectedErrorResponse, + TContext = unknown, +>( + options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + CompleteAttachmentUploadMutationVariables, + TContext + >; + request?: SecondParameter; + }, + queryClient?: QueryClient, +): UseMutationResult< + Awaited>, + TError, + CompleteAttachmentUploadMutationVariables, + TContext +> => { + return useMutation( + getCompleteAttachmentUploadMutationOptions(options), + queryClient, + ); +}; diff --git a/app/src/lib/api/generated/conversations/conversations.zod.ts b/app/src/lib/api/generated/conversations/conversations.zod.ts index 7888efb0d2..75ffb87fca 100644 --- a/app/src/lib/api/generated/conversations/conversations.zod.ts +++ b/app/src/lib/api/generated/conversations/conversations.zod.ts @@ -1767,3 +1767,209 @@ export const StopConversationRunResponse = zod.object({ }) .describe("One of a Bot's runs in a conversation, and how it ended."), }); + +/** + * Start an upload of one file to send with the caller's next message in the conversation, sent in parts so that no one request has to carry the whole file. Send each part with uploadAttachmentPart, in any order, then completeAttachmentUpload. The answer says how large each part is (partBytes) and how many there are; every part is exactly partBytes except the last, which holds what is left. An upload not completed by expiresAt is removed with its parts. A file larger than the largest the deployment takes (its attachmentLimits) is refused here (422), before any part is sent. The file is checked when the upload is completed, as uploadConversationAttachment checks it. Offered where the deployment's attachmentUploadsInParts is true. + * @summary Start uploading a file in parts + */ + +export const createAttachmentUploadPathConversationIdRegExp = new RegExp("\\S"); + +export const CreateAttachmentUploadParams = zod.object({ + organizationId: zod + .string() + .min(1) + .describe( + "The organization, by its id or its slug. One the caller is not a member of answers as one that does not exist, `default` included.", + ), + conversationId: zod + .string() + .min(1) + .regex(createAttachmentUploadPathConversationIdRegExp) + .describe("The conversation's id."), +}); + +export const createAttachmentUploadHeaderIdempotencyKeyMax = 128; + +export const CreateAttachmentUploadHeader = zod.object({ + "Idempotency-Key": zod + .string() + .min(1) + .max(createAttachmentUploadHeaderIdempotencyKeyMax) + .describe( + "Generated by the caller for each write it means to make once. Reuse the same key and the same request for 24 hours after an uncertain response; the same key with a different request is a conflict.", + ), +}); + +export const createAttachmentUploadBodyNameMax = 1024; + +export const createAttachmentUploadBodyUploadGroupMax = 200; + +export const CreateAttachmentUploadBody = zod.object({ + name: zod + .string() + .min(1) + .max(createAttachmentUploadBodyNameMax) + .describe("The file's name."), + sizeBytes: zod + .int() + .min(1) + .describe("The file's size, in bytes. The parts must add up to it."), + uploadGroup: zod + .string() + .max(createAttachmentUploadBodyUploadGroupMax) + .optional() + .describe( + "Names the message being written, so the files of two windows are counted apart.", + ), +}); + +export const CreateAttachmentUploadResponse = zod + .object({ + id: zod.string().describe("The upload's id."), + partBytes: zod + .int() + .min(1) + .describe( + "The size of every part but the last, in bytes. Chosen by OpenBot so that a part reaches it even over a slow connection.", + ), + partCount: zod.int().min(1).describe("How many parts the file is sent in."), + expiresAt: zod.iso + .datetime({ offset: true }) + .describe("When an upload not yet completed is removed with its parts."), + }) + .describe("An upload waiting for its parts."); + +/** + * Stop an upload the caller started and has not completed, and remove the parts already sent. Stopping one that is already stopped answers 204 again. A completed upload is a file now; remove it with deleteAttachment. + * @summary Stop an upload + */ + +export const cancelAttachmentUploadPathUploadIdMax = 256; + +export const cancelAttachmentUploadPathUploadIdRegExp = new RegExp("\\S"); + +export const CancelAttachmentUploadParams = zod.object({ + organizationId: zod + .string() + .min(1) + .describe( + "The organization, by its id or its slug. One the caller is not a member of answers as one that does not exist, `default` included.", + ), + uploadId: zod + .string() + .min(1) + .max(cancelAttachmentUploadPathUploadIdMax) + .regex(cancelAttachmentUploadPathUploadIdRegExp) + .describe("The upload's id, as createAttachmentUpload gave it."), +}); + +export const cancelAttachmentUploadHeaderIdempotencyKeyMax = 128; + +export const CancelAttachmentUploadHeader = zod.object({ + "Idempotency-Key": zod + .string() + .min(1) + .max(cancelAttachmentUploadHeaderIdempotencyKeyMax) + .describe( + "Generated by the caller for each write it means to make once. Reuse the same key and the same request for 24 hours after an uncertain response; the same key with a different request is a conflict.", + ), +}); + +export const CancelAttachmentUploadResponse = zod.void(); + +/** + * Send one part of an upload started with createAttachmentUpload, as its bytes. Every part is exactly the upload's partBytes except the last, which holds what is left; a part of any other size is refused. Parts go in any order. Sending a part again replaces it, so after a dropped connection an app sends the part again, with the same Idempotency-Key. + * @summary Send one part of a file + */ + +export const uploadAttachmentPartPathUploadIdMax = 256; + +export const uploadAttachmentPartPathUploadIdRegExp = new RegExp("\\S"); +export const uploadAttachmentPartPathPartNumberMax = 10000; + +export const UploadAttachmentPartParams = zod.object({ + organizationId: zod + .string() + .min(1) + .describe( + "The organization, by its id or its slug. One the caller is not a member of answers as one that does not exist, `default` included.", + ), + uploadId: zod + .string() + .min(1) + .max(uploadAttachmentPartPathUploadIdMax) + .regex(uploadAttachmentPartPathUploadIdRegExp) + .describe("The upload's id, as createAttachmentUpload gave it."), + partNumber: zod + .int() + .min(1) + .max(uploadAttachmentPartPathPartNumberMax) + .describe("Which part of the file, counted from 1."), +}); + +export const uploadAttachmentPartHeaderIdempotencyKeyMax = 128; + +export const UploadAttachmentPartHeader = zod.object({ + "Idempotency-Key": zod + .string() + .min(1) + .max(uploadAttachmentPartHeaderIdempotencyKeyMax) + .describe( + "Generated by the caller for each write it means to make once. Reuse the same key and the same request for 24 hours after an uncertain response; the same key with a different request is a conflict.", + ), +}); + +export const UploadAttachmentPartResponse = zod + .object({ + partNumber: zod.int().min(1), + sizeBytes: zod.int().min(1), + }) + .describe("A part that arrived."); + +/** + * Put an upload's parts together into one file, held for the caller's next message in the conversation exactly as uploadConversationAttachment holds one, and refused for the same reasons. A part that has not arrived is refused (409, naming it); send it and complete again. Completing an upload that was already completed answers the same file again. A refusal for the file itself (its type or its size) ends the upload and removes its parts. + * @summary Finish an upload + */ + +export const completeAttachmentUploadPathUploadIdMax = 256; + +export const completeAttachmentUploadPathUploadIdRegExp = new RegExp("\\S"); + +export const CompleteAttachmentUploadParams = zod.object({ + organizationId: zod + .string() + .min(1) + .describe( + "The organization, by its id or its slug. One the caller is not a member of answers as one that does not exist, `default` included.", + ), + uploadId: zod + .string() + .min(1) + .max(completeAttachmentUploadPathUploadIdMax) + .regex(completeAttachmentUploadPathUploadIdRegExp) + .describe("The upload's id, as createAttachmentUpload gave it."), +}); + +export const completeAttachmentUploadHeaderIdempotencyKeyMax = 128; + +export const CompleteAttachmentUploadHeader = zod.object({ + "Idempotency-Key": zod + .string() + .min(1) + .max(completeAttachmentUploadHeaderIdempotencyKeyMax) + .describe( + "Generated by the caller for each write it means to make once. Reuse the same key and the same request for 24 hours after an uncertain response; the same key with a different request is a conflict.", + ), +}); + +export const completeAttachmentUploadResponseSizeBytesMin = 0; + +export const CompleteAttachmentUploadResponse = zod + .object({ + id: zod.string().describe("The attachment's id."), + name: zod.string().describe("The file's name."), + mimeType: zod.string().describe("The type OpenBot recognised it as."), + sizeBytes: zod.int().min(completeAttachmentUploadResponseSizeBytesMin), + }) + .describe("A file held for a message, or sent with one."); diff --git a/app/src/lib/api/generated/model/attachmentTooLargeResponse.ts b/app/src/lib/api/generated/model/attachmentTooLargeResponse.ts new file mode 100644 index 0000000000..24c79e8f18 --- /dev/null +++ b/app/src/lib/api/generated/model/attachmentTooLargeResponse.ts @@ -0,0 +1,9 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { Problem } from "./problem"; + +/** + * The file is larger than this OpenBot takes for a file of its kind (the deployment's attachmentLimits). Nothing was kept. + */ +export type AttachmentTooLargeResponse = Problem; diff --git a/app/src/lib/api/generated/model/attachmentUploadConflictResponse.ts b/app/src/lib/api/generated/model/attachmentUploadConflictResponse.ts new file mode 100644 index 0000000000..571e9060b8 --- /dev/null +++ b/app/src/lib/api/generated/model/attachmentUploadConflictResponse.ts @@ -0,0 +1,9 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { Problem } from "./problem"; + +/** + * The upload cannot take this: a part has not arrived yet, the upload is already completed, the message already holds as many files as it may, or the caller is holding too many unsent files. Or the Idempotency-Key was already used for a different request. + */ +export type AttachmentUploadConflictResponse = Problem; diff --git a/app/src/lib/api/generated/model/attachmentUploadNotFoundResponse.ts b/app/src/lib/api/generated/model/attachmentUploadNotFoundResponse.ts new file mode 100644 index 0000000000..8083ea6709 --- /dev/null +++ b/app/src/lib/api/generated/model/attachmentUploadNotFoundResponse.ts @@ -0,0 +1,9 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { Problem } from "./problem"; + +/** + * The upload does not exist, is another person's, was stopped or has expired, or the organization does not exist. + */ +export type AttachmentUploadNotFoundResponse = Problem; diff --git a/app/src/lib/api/generated/model/attachmentUploadPart.ts b/app/src/lib/api/generated/model/attachmentUploadPart.ts new file mode 100644 index 0000000000..e6cd258574 --- /dev/null +++ b/app/src/lib/api/generated/model/attachmentUploadPart.ts @@ -0,0 +1,13 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ + +/** + * A part that arrived. + */ +export interface AttachmentUploadPart { + /** @minimum 1 */ + partNumber: number; + /** @minimum 1 */ + sizeBytes: number; +} diff --git a/app/src/lib/api/generated/model/attachmentUploadSession.ts b/app/src/lib/api/generated/model/attachmentUploadSession.ts new file mode 100644 index 0000000000..5f9b486590 --- /dev/null +++ b/app/src/lib/api/generated/model/attachmentUploadSession.ts @@ -0,0 +1,23 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ + +/** + * An upload waiting for its parts. + */ +export interface AttachmentUploadSession { + /** The upload's id. */ + id: string; + /** + * The size of every part but the last, in bytes. Chosen by OpenBot so that a part reaches it even over a slow connection. + * @minimum 1 + */ + partBytes: number; + /** + * How many parts the file is sent in. + * @minimum 1 + */ + partCount: number; + /** When an upload not yet completed is removed with its parts. */ + expiresAt: string; +} diff --git a/app/src/lib/api/generated/model/attachmentUploadStart.ts b/app/src/lib/api/generated/model/attachmentUploadStart.ts new file mode 100644 index 0000000000..6aae938421 --- /dev/null +++ b/app/src/lib/api/generated/model/attachmentUploadStart.ts @@ -0,0 +1,22 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ + +export interface AttachmentUploadStart { + /** + * The file's name. + * @minLength 1 + * @maxLength 1024 + */ + name: string; + /** + * The file's size, in bytes. The parts must add up to it. + * @minimum 1 + */ + sizeBytes: number; + /** + * Names the message being written, so the files of two windows are counted apart. + * @maxLength 200 + */ + uploadGroup?: string; +} diff --git a/app/src/lib/api/generated/model/cancelAttachmentUploadHeaders.ts b/app/src/lib/api/generated/model/cancelAttachmentUploadHeaders.ts new file mode 100644 index 0000000000..7c86cf9792 --- /dev/null +++ b/app/src/lib/api/generated/model/cancelAttachmentUploadHeaders.ts @@ -0,0 +1,13 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { IdempotencyKeyParameter } from "./idempotencyKeyParameter"; + +export type CancelAttachmentUploadHeaders = { + /** + * Generated by the caller for each write it means to make once. Reuse the same key and the same request for 24 hours after an uncertain response; the same key with a different request is a conflict. + * @minLength 1 + * @maxLength 128 + */ + "Idempotency-Key": IdempotencyKeyParameter; +}; diff --git a/app/src/lib/api/generated/model/completeAttachmentUploadHeaders.ts b/app/src/lib/api/generated/model/completeAttachmentUploadHeaders.ts new file mode 100644 index 0000000000..67e118556f --- /dev/null +++ b/app/src/lib/api/generated/model/completeAttachmentUploadHeaders.ts @@ -0,0 +1,13 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { IdempotencyKeyParameter } from "./idempotencyKeyParameter"; + +export type CompleteAttachmentUploadHeaders = { + /** + * Generated by the caller for each write it means to make once. Reuse the same key and the same request for 24 hours after an uncertain response; the same key with a different request is a conflict. + * @minLength 1 + * @maxLength 128 + */ + "Idempotency-Key": IdempotencyKeyParameter; +}; diff --git a/app/src/lib/api/generated/model/createAttachmentUploadHeaders.ts b/app/src/lib/api/generated/model/createAttachmentUploadHeaders.ts new file mode 100644 index 0000000000..7e5a146876 --- /dev/null +++ b/app/src/lib/api/generated/model/createAttachmentUploadHeaders.ts @@ -0,0 +1,13 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { IdempotencyKeyParameter } from "./idempotencyKeyParameter"; + +export type CreateAttachmentUploadHeaders = { + /** + * Generated by the caller for each write it means to make once. Reuse the same key and the same request for 24 hours after an uncertain response; the same key with a different request is a conflict. + * @minLength 1 + * @maxLength 128 + */ + "Idempotency-Key": IdempotencyKeyParameter; +}; diff --git a/app/src/lib/api/generated/model/deployment.ts b/app/src/lib/api/generated/model/deployment.ts index 608a2e49a8..46c2eb5ed5 100644 --- a/app/src/lib/api/generated/model/deployment.ts +++ b/app/src/lib/api/generated/model/deployment.ts @@ -53,6 +53,8 @@ export interface Deployment { /** Whether this OpenBot keeps the Windows computers it makes for people (listWindowsComputers and the operations beside it): true even while it can't make one right now, which the list's creation says. Absent or false, those operations answer 404, so an app shows nothing about them and doesn't ask. */ managedWindowsComputers?: boolean; attachmentLimits?: AttachmentLimits; + /** Whether a file can be uploaded in parts (createAttachmentUpload, uploadAttachmentPart and completeAttachmentUpload), so that no one request has to carry the whole file over a slow connection. Absent or false, as from an older OpenBot, send each file in one request with uploadConversationAttachment. */ + attachmentUploadsInParts?: boolean; /** Whether a Bot can read the whole of an attached text file or document, page by page, past the first 120000 characters it is shown with the message. Absent or false, as from an older OpenBot, a Bot reads only those first 120000 characters. */ attachmentsReadWhole?: boolean; /** diff --git a/app/src/lib/api/generated/model/index.ts b/app/src/lib/api/generated/model/index.ts index 88cdc26459..fd14b6969b 100644 --- a/app/src/lib/api/generated/model/index.ts +++ b/app/src/lib/api/generated/model/index.ts @@ -301,7 +301,13 @@ export * from "./attachment"; export * from "./attachmentConflictResponse"; export * from "./attachmentLimits"; export * from "./attachmentNotFoundResponse"; +export * from "./attachmentTooLargeResponse"; export * from "./attachmentUpload"; +export * from "./attachmentUploadConflictResponse"; +export * from "./attachmentUploadNotFoundResponse"; +export * from "./attachmentUploadPart"; +export * from "./attachmentUploadSession"; +export * from "./attachmentUploadStart"; export * from "./auditActorParameter"; export * from "./auditAnswer"; export * from "./auditAnswerAnswerable"; @@ -552,6 +558,7 @@ export * from "./callArtifactPageAppActionRequest"; export * from "./callArtifactPageAppActionRequestArgs"; export * from "./callComponentFunctionHeaders"; export * from "./cancelAccountDeletionHeaders"; +export * from "./cancelAttachmentUploadHeaders"; export * from "./cancelComputerControlHeaders"; export * from "./cancelFollowUpHeaders"; export * from "./cancelManagementEnrollmentHeaders"; @@ -620,6 +627,7 @@ export * from "./companySignInProvidersItem"; export * from "./companySignInTicket"; export * from "./companySignInTicketConflictResponse"; export * from "./companySignInTicketForbiddenResponse"; +export * from "./completeAttachmentUploadHeaders"; export * from "./completeGoalHeaders"; export * from "./completeOnboardingHeaders"; export * from "./component"; @@ -805,6 +813,7 @@ export * from "./createArtifactHeaders"; export * from "./createArtifactInviteHeaders"; export * from "./createArtifactInviteRequest"; export * from "./createArtifactRequest"; +export * from "./createAttachmentUploadHeaders"; export * from "./createAutomaticLearningSpaceHeaders"; export * from "./createBotAgentHeaders"; export * from "./createBotAgentRequest"; @@ -1953,6 +1962,7 @@ export * from "./updateTeamRequest"; export * from "./updateWindowsAllowlistHeaders"; export * from "./updateWindowsAllowlistRequest"; export * from "./uploadArtifactAssetHeaders"; +export * from "./uploadAttachmentPartHeaders"; export * from "./uploadConversationAttachmentHeaders"; export * from "./uploadImportPartHeaders"; export * from "./useSavedLoginHeaders"; diff --git a/app/src/lib/api/generated/model/uploadAttachmentPartHeaders.ts b/app/src/lib/api/generated/model/uploadAttachmentPartHeaders.ts new file mode 100644 index 0000000000..2d1dd8bfbc --- /dev/null +++ b/app/src/lib/api/generated/model/uploadAttachmentPartHeaders.ts @@ -0,0 +1,13 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { IdempotencyKeyParameter } from "./idempotencyKeyParameter"; + +export type UploadAttachmentPartHeaders = { + /** + * Generated by the caller for each write it means to make once. Reuse the same key and the same request for 24 hours after an uncertain response; the same key with a different request is a conflict. + * @minLength 1 + * @maxLength 128 + */ + "Idempotency-Key": IdempotencyKeyParameter; +}; diff --git a/app/src/lib/api/generated/organization-settings/organization-settings.msw.ts b/app/src/lib/api/generated/organization-settings/organization-settings.msw.ts index c501ebc432..187115fd64 100644 --- a/app/src/lib/api/generated/organization-settings/organization-settings.msw.ts +++ b/app/src/lib/api/generated/organization-settings/organization-settings.msw.ts @@ -43,6 +43,7 @@ export const getGetDeploymentResponseMock = (): Deployment => ({ documentBytes: 104857600, fileBytes: 104857600, }, + attachmentUploadsInParts: true, attachmentsReadWhole: true, api: ["v2"], minimumClients: { desktop: "1.2.0" }, diff --git a/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts b/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts index 134a9db922..eda52cb9f9 100644 --- a/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts +++ b/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts @@ -162,6 +162,12 @@ export const GetDeploymentResponse = zod .describe( "How large a file attached to a message may be, by kind, in bytes. An upload over its kind's limit is refused. Absent, as from an older OpenBot, the limits are 8388608 for an image or a document (a PDF, or a Word, Excel or PowerPoint file) and 1048576 for any other file. The limits can rise while OpenBot runs, so a client reads them again rather than keeping them for good. What a Bot's model is shown of a large file is a separate matter: the file is kept and can be downloaded whatever the model can read of it.", ), + attachmentUploadsInParts: zod + .boolean() + .optional() + .describe( + "Whether a file can be uploaded in parts (createAttachmentUpload, uploadAttachmentPart and completeAttachmentUpload), so that no one request has to carry the whole file over a slow connection. Absent or false, as from an older OpenBot, send each file in one request with uploadConversationAttachment.", + ), attachmentsReadWhole: zod .boolean() .optional() diff --git a/mobile/src/api/generated/conversations/conversations.ts b/mobile/src/api/generated/conversations/conversations.ts index 1169296b43..699f35984c 100644 --- a/mobile/src/api/generated/conversations/conversations.ts +++ b/mobile/src/api/generated/conversations/conversations.ts @@ -6,6 +6,9 @@ import type { AddedConversationMember, Attachment, AttachmentUpload, + AttachmentUploadPart, + AttachmentUploadSession, + AttachmentUploadStart, ConversationActivity, ConversationBusy, ConversationJoinToken, @@ -891,3 +894,159 @@ export const stopConversationRun = async ( }, ); }; + +export const getCreateAttachmentUploadUrl = ( + organizationId: string, + conversationId: string, +) => { + return `/api/v2/organizations/${encodeURIComponent(String(organizationId))}/conversations/${encodeURIComponent(String(conversationId))}/attachment-uploads`; +}; + +/** + * Start an upload of one file to send with the caller's next message in the conversation, sent in parts so that no one request has to carry the whole file. Send each part with uploadAttachmentPart, in any order, then completeAttachmentUpload. The answer says how large each part is (partBytes) and how many there are; every part is exactly partBytes except the last, which holds what is left. An upload not completed by expiresAt is removed with its parts. A file larger than the largest the deployment takes (its attachmentLimits) is refused here (422), before any part is sent. The file is checked when the upload is completed, as uploadConversationAttachment checks it. Offered where the deployment's attachmentUploadsInParts is true. + * @summary Start uploading a file in parts + */ +export const createAttachmentUpload = async ( + organizationId: string, + conversationId: string, + attachmentUploadStart: AttachmentUploadStart, + options?: Parameters[1], +): Promise => { + const getHeaders = ( + h?: NonNullable, + ): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from( + h as Iterable>, + (entry) => Array.from(entry) as [string, string], + ), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries< + string | readonly string[] | undefined + >(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; + return apiRequest( + getCreateAttachmentUploadUrl(organizationId, conversationId), + { + ...options, + method: "POST", + headers: { + "Content-Type": "application/json", + ...getHeaders(options?.headers), + }, + body: JSON.stringify(attachmentUploadStart), + }, + ); +}; + +export const getCancelAttachmentUploadUrl = ( + organizationId: string, + uploadId: string, +) => { + return `/api/v2/organizations/${encodeURIComponent(String(organizationId))}/attachment-uploads/${encodeURIComponent(String(uploadId))}`; +}; + +/** + * Stop an upload the caller started and has not completed, and remove the parts already sent. Stopping one that is already stopped answers 204 again. A completed upload is a file now; remove it with deleteAttachment. + * @summary Stop an upload + */ +export const cancelAttachmentUpload = async ( + organizationId: string, + uploadId: string, + options?: Parameters[1], +): Promise => { + return apiRequest( + getCancelAttachmentUploadUrl(organizationId, uploadId), + { + ...options, + method: "DELETE", + }, + ); +}; + +export const getUploadAttachmentPartUrl = ( + organizationId: string, + uploadId: string, + partNumber: number, +) => { + return `/api/v2/organizations/${encodeURIComponent(String(organizationId))}/attachment-uploads/${encodeURIComponent(String(uploadId))}/parts/${encodeURIComponent(String(partNumber))}`; +}; + +/** + * Send one part of an upload started with createAttachmentUpload, as its bytes. Every part is exactly the upload's partBytes except the last, which holds what is left; a part of any other size is refused. Parts go in any order. Sending a part again replaces it, so after a dropped connection an app sends the part again, with the same Idempotency-Key. + * @summary Send one part of a file + */ +export const uploadAttachmentPart = async ( + organizationId: string, + uploadId: string, + partNumber: number, + uploadAttachmentPartBody: Blob, + options?: Parameters[1], +): Promise => { + const getHeaders = ( + h?: NonNullable, + ): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from( + h as Iterable>, + (entry) => Array.from(entry) as [string, string], + ), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries< + string | readonly string[] | undefined + >(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; + return apiRequest( + getUploadAttachmentPartUrl(organizationId, uploadId, partNumber), + { + ...options, + method: "PUT", + headers: { + "Content-Type": "application/octet-stream", + ...getHeaders(options?.headers), + }, + body: uploadAttachmentPartBody, + }, + ); +}; + +export const getCompleteAttachmentUploadUrl = ( + organizationId: string, + uploadId: string, +) => { + return `/api/v2/organizations/${encodeURIComponent(String(organizationId))}/attachment-uploads/${encodeURIComponent(String(uploadId))}/complete`; +}; + +/** + * Put an upload's parts together into one file, held for the caller's next message in the conversation exactly as uploadConversationAttachment holds one, and refused for the same reasons. A part that has not arrived is refused (409, naming it); send it and complete again. Completing an upload that was already completed answers the same file again. A refusal for the file itself (its type or its size) ends the upload and removes its parts. + * @summary Finish an upload + */ +export const completeAttachmentUpload = async ( + organizationId: string, + uploadId: string, + options?: Parameters[1], +): Promise => { + return apiRequest( + getCompleteAttachmentUploadUrl(organizationId, uploadId), + { + ...options, + method: "POST", + }, + ); +}; diff --git a/mobile/src/api/generated/model/attachmentTooLargeResponse.ts b/mobile/src/api/generated/model/attachmentTooLargeResponse.ts new file mode 100644 index 0000000000..24c79e8f18 --- /dev/null +++ b/mobile/src/api/generated/model/attachmentTooLargeResponse.ts @@ -0,0 +1,9 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { Problem } from "./problem"; + +/** + * The file is larger than this OpenBot takes for a file of its kind (the deployment's attachmentLimits). Nothing was kept. + */ +export type AttachmentTooLargeResponse = Problem; diff --git a/mobile/src/api/generated/model/attachmentUploadConflictResponse.ts b/mobile/src/api/generated/model/attachmentUploadConflictResponse.ts new file mode 100644 index 0000000000..571e9060b8 --- /dev/null +++ b/mobile/src/api/generated/model/attachmentUploadConflictResponse.ts @@ -0,0 +1,9 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { Problem } from "./problem"; + +/** + * The upload cannot take this: a part has not arrived yet, the upload is already completed, the message already holds as many files as it may, or the caller is holding too many unsent files. Or the Idempotency-Key was already used for a different request. + */ +export type AttachmentUploadConflictResponse = Problem; diff --git a/mobile/src/api/generated/model/attachmentUploadNotFoundResponse.ts b/mobile/src/api/generated/model/attachmentUploadNotFoundResponse.ts new file mode 100644 index 0000000000..8083ea6709 --- /dev/null +++ b/mobile/src/api/generated/model/attachmentUploadNotFoundResponse.ts @@ -0,0 +1,9 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { Problem } from "./problem"; + +/** + * The upload does not exist, is another person's, was stopped or has expired, or the organization does not exist. + */ +export type AttachmentUploadNotFoundResponse = Problem; diff --git a/mobile/src/api/generated/model/attachmentUploadPart.ts b/mobile/src/api/generated/model/attachmentUploadPart.ts new file mode 100644 index 0000000000..e6cd258574 --- /dev/null +++ b/mobile/src/api/generated/model/attachmentUploadPart.ts @@ -0,0 +1,13 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ + +/** + * A part that arrived. + */ +export interface AttachmentUploadPart { + /** @minimum 1 */ + partNumber: number; + /** @minimum 1 */ + sizeBytes: number; +} diff --git a/mobile/src/api/generated/model/attachmentUploadSession.ts b/mobile/src/api/generated/model/attachmentUploadSession.ts new file mode 100644 index 0000000000..5f9b486590 --- /dev/null +++ b/mobile/src/api/generated/model/attachmentUploadSession.ts @@ -0,0 +1,23 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ + +/** + * An upload waiting for its parts. + */ +export interface AttachmentUploadSession { + /** The upload's id. */ + id: string; + /** + * The size of every part but the last, in bytes. Chosen by OpenBot so that a part reaches it even over a slow connection. + * @minimum 1 + */ + partBytes: number; + /** + * How many parts the file is sent in. + * @minimum 1 + */ + partCount: number; + /** When an upload not yet completed is removed with its parts. */ + expiresAt: string; +} diff --git a/mobile/src/api/generated/model/attachmentUploadStart.ts b/mobile/src/api/generated/model/attachmentUploadStart.ts new file mode 100644 index 0000000000..6aae938421 --- /dev/null +++ b/mobile/src/api/generated/model/attachmentUploadStart.ts @@ -0,0 +1,22 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ + +export interface AttachmentUploadStart { + /** + * The file's name. + * @minLength 1 + * @maxLength 1024 + */ + name: string; + /** + * The file's size, in bytes. The parts must add up to it. + * @minimum 1 + */ + sizeBytes: number; + /** + * Names the message being written, so the files of two windows are counted apart. + * @maxLength 200 + */ + uploadGroup?: string; +} diff --git a/mobile/src/api/generated/model/deployment.ts b/mobile/src/api/generated/model/deployment.ts index 608a2e49a8..46c2eb5ed5 100644 --- a/mobile/src/api/generated/model/deployment.ts +++ b/mobile/src/api/generated/model/deployment.ts @@ -53,6 +53,8 @@ export interface Deployment { /** Whether this OpenBot keeps the Windows computers it makes for people (listWindowsComputers and the operations beside it): true even while it can't make one right now, which the list's creation says. Absent or false, those operations answer 404, so an app shows nothing about them and doesn't ask. */ managedWindowsComputers?: boolean; attachmentLimits?: AttachmentLimits; + /** Whether a file can be uploaded in parts (createAttachmentUpload, uploadAttachmentPart and completeAttachmentUpload), so that no one request has to carry the whole file over a slow connection. Absent or false, as from an older OpenBot, send each file in one request with uploadConversationAttachment. */ + attachmentUploadsInParts?: boolean; /** Whether a Bot can read the whole of an attached text file or document, page by page, past the first 120000 characters it is shown with the message. Absent or false, as from an older OpenBot, a Bot reads only those first 120000 characters. */ attachmentsReadWhole?: boolean; /** diff --git a/mobile/src/api/generated/model/index.ts b/mobile/src/api/generated/model/index.ts index 3a61b36e1f..46fe6a8e41 100644 --- a/mobile/src/api/generated/model/index.ts +++ b/mobile/src/api/generated/model/index.ts @@ -163,7 +163,13 @@ export * from "./attachment"; export * from "./attachmentConflictResponse"; export * from "./attachmentLimits"; export * from "./attachmentNotFoundResponse"; +export * from "./attachmentTooLargeResponse"; export * from "./attachmentUpload"; +export * from "./attachmentUploadConflictResponse"; +export * from "./attachmentUploadNotFoundResponse"; +export * from "./attachmentUploadPart"; +export * from "./attachmentUploadSession"; +export * from "./attachmentUploadStart"; export * from "./authorizationStart"; export * from "./authorizeActionRequest"; export * from "./bot"; From ae79bdfd50554bd1a077d707d2d43ec62324d73b Mon Sep 17 00:00:00 2001 From: David McKay Date: Fri, 4 Dec 2026 13:54:23 -0800 Subject: [PATCH 2/7] Attach a large file over a slow connection: send it in parts, and try again by itself MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a slow upload link no file over a few megabytes could be attached: the whole file went up in one request, and the edge in front of OpenBot Cloud closes any request whose body takes more than 125 seconds to arrive, so trying again only failed again. Where the deployment offers it (attachmentUploadsInParts), a file over 1MB now goes up in parts of the size OpenBot chooses (createAttachmentUpload, uploadAttachmentPart, completeAttachmentUpload), as OpenAI's Uploads, Slack's external uploads, Microsoft Graph's upload sessions and Google's resumable uploads do. One part is in flight at a time across the tab, so files sent together don't split a slow link and push every part past the limit. A file of 1MB or less, and every file on an OpenBot that doesn't offer parts, still goes in one request. Every request (each part, the start, the finish and the one-request upload) is tried again by itself while its failure may pass: no answer, 408, 429, a 5xx (Cloudflare's 520 to 524 among them) or a refusal OpenBot marks retryable, honouring Retry-After. Up to 8 tries, about 1s doubling to 30s apart with jitter (p-retry), as Google's and AWS's storage clients retry. A part that is sent again keeps its Idempotency-Key. A part the finish says is missing (ATTACHMENT_PARTS_MISSING) is sent again once and the finish asked again with a new key. An upload that never gets through is stopped on the server (cancelAttachmentUpload), and the file is refused in words that don't ask the person to try again. The tile shows how far a file sent in parts has got: "Uploading…" with the percentage and a thin bar, and the same bar along a picture's placeholder, read from XMLHttpRequest's upload progress (fetch reports none in any browser). It goes through lib/client.ts's one transport, with the same cookie, headers, refusals and reachability as fetch. Removing a file while it goes up in parts stops it, and nothing is said about it. upload-in-parts-browser.test.tsx drives the real message box in Chromium and WebKit against a server that answers as the spec says (checked with its zod schemas) and answers 524 to any body that took too long to arrive, with Chromium's network throttled: in one request the file is refused, in parts it arrives whole. --- .github/workflows/ci.yml | 1 + api/client-boundary.allow.ts | 6 + app/package.json | 2 + .../channels/composer/attachment-strip.tsx | 67 +- .../channels/composer/attachments.ts | 44 +- .../components/channels/composer/composer.tsx | 64 +- .../channels/composer/placeholder-files.ts | 53 + app/src/lib/api/request.ts | 19 +- app/src/lib/channels/start.ts | 10 +- app/src/lib/channels/upload-progress.ts | 109 ++ app/src/lib/channels/upload.ts | 340 ++++++ app/src/lib/client.ts | 95 +- app/src/lib/deployment/queries.ts | 8 + app/tests/composer-attachments.test.ts | 108 +- app/tests/upload-in-parts-browser.test.tsx | 1081 +++++++++++++++++ app/tests/upload-in-parts.fixture.tsx | 69 ++ bun.lock | 12 +- 17 files changed, 2043 insertions(+), 45 deletions(-) create mode 100644 app/src/components/channels/composer/placeholder-files.ts create mode 100644 app/src/lib/channels/upload-progress.ts create mode 100644 app/src/lib/channels/upload.ts create mode 100644 app/tests/upload-in-parts-browser.test.tsx create mode 100644 app/tests/upload-in-parts.fixture.tsx diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1e81c018af..c16376e668 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -817,6 +817,7 @@ jobs: app/tests/transcript-table-end.test.tsx app/tests/trusted-types-build.test.ts app/tests/trusted-types.test.ts + app/tests/upload-in-parts-browser.test.tsx app/tests/web-push-browser.test.tsx app/tests/what-if-handle-browser.test.tsx app/tests/work-folded-layout.test.tsx diff --git a/api/client-boundary.allow.ts b/api/client-boundary.allow.ts index d3314b185f..22fb93b2ab 100644 --- a/api/client-boundary.allow.ts +++ b/api/client-boundary.allow.ts @@ -164,6 +164,12 @@ export const ALLOWED: Allowed[] = [ rule: "transport", why: "the app's one request function, which the generated client's mutator calls", }, + { + file: "app/src/lib/client.ts", + what: "new XMLHttpRequest()", + rule: "transport", + why: "the app's one request function, sending a request whose caller follows its upload's progress, which fetch reports in no browser", + }, { file: "app/serve.ts", what: /^\/api(\/|\/v2\/organizations\/\[\^\/\]\+)?$/, diff --git a/app/package.json b/app/package.json index 26f8b10789..c125d616dd 100644 --- a/app/package.json +++ b/app/package.json @@ -48,6 +48,8 @@ "lru-cache": "11.5.3", "mermaid": "12.3.0", "motion": "^13.1.0", + "p-limit": "7.3.3", + "p-retry": "9.0.0", "prompt-area": "^0.6.3", "react": "^19.2.0", "react-dom": "^19.2.0", diff --git a/app/src/components/channels/composer/attachment-strip.tsx b/app/src/components/channels/composer/attachment-strip.tsx index 11d3e2af24..41aaab2b54 100644 --- a/app/src/components/channels/composer/attachment-strip.tsx +++ b/app/src/components/channels/composer/attachment-strip.tsx @@ -2,7 +2,9 @@ import { motion, useReducedMotion } from "motion/react"; import { useState } from "react"; import { IconPhoto, IconX } from "@/components/icons"; +import { Progress, ProgressValue } from "@/components/ui/progress"; import { Skeleton } from "@/components/ui/skeleton"; +import { useUploadPercent } from "@/lib/channels/upload-progress"; import { kindLabel } from "@/lib/computers/sent-file"; import { EASE_OUT, ENTRANCE_SECONDS } from "@/lib/motion"; import { FileTypeIcon } from "../file-icon"; @@ -45,6 +47,8 @@ export type StagedImage = { /** The type the server found in the bytes, once it has them. */ mimeType?: string; size?: number; + /** The file being uploaded, whose progress the tile shows while it is sent in parts. */ + uploadingFile?: File; }; export type StagedFile = { @@ -60,6 +64,8 @@ export type StagedFile = { * truncated — warned on the tile, never refused. */ mayTruncate?: boolean; + /** The file being uploaded, whose progress the tile shows while it is sent in parts. */ + uploadingFile?: File; }; export function AttachmentStrip({ @@ -125,7 +131,7 @@ export function AttachmentStrip({ {file.name}

{file.loading ? ( -

Uploading…

+ ) : file.size === undefined ? null : ( /* * ON THE SIZE LINE, NOT UNDER IT, AND THAT IS A LAYOUT CONSTRAINT RATHER THAN A @@ -161,6 +167,52 @@ export function AttachmentStrip({ ); } +/** + * A file's tile while it uploads: "Uploading…", and for a file sent in parts how much has gone, as a + * percentage and a thin bar under it, as the upload tiles of chat apps draw it. + * + * The bar is a progressbar named for the file, with its value, for a screen reader; never a live + * region, so eight files going up don't speak over each other. A file sent in one request has no + * progress to tell (`useUploadPercent` is nothing for it) and keeps the line as it was. + * + * Two lines and the bar still fit the tile's fixed height: a 20px icon, the name's 16px line, and + * this one's 16px with 4px and the 4px bar under it, 60px of the 62px inside. + */ +function UploadingLine({ file, name }: { file?: File; name: string }) { + const percent = useUploadPercent(file); + if (percent === undefined) + return

Uploading…

; + return ( + + Uploading… + + + ); +} + +/** A picture's placeholder while it is sent in parts: the same thin bar, along its foot. */ +function PictureProgress({ file, name }: { file?: File; name: string }) { + const percent = useUploadPercent(file); + if (percent === undefined) return null; + return ( + + ); +} + +/** + * The track drawn in the line color. The primitive's track is `muted`, which is the tile's own + * fill here, so the part still to go would not show: a file waiting its turn would have no bar. + */ +const TRACK_ON_MUTED = "*:data-[slot=progress-track]:bg-border"; + /** A file's tile: the height of a thumbnail, so a row of both reads as one row. */ const FILE_TILE = "flex h-20 w-40 flex-col justify-between rounded-md border border-border bg-muted p-2"; @@ -218,11 +270,14 @@ function StagedPicture({ * A name, not an announcement. `role="status"` would make each of these a live * region, and a paste of eight images would interrupt eight times to say so. */ - + <> + + + ) : ( {image.alt Promise { return async (file: File): Promise => { // Named after the file rather than left empty, for every way this can go wrong. It is the only @@ -64,15 +66,25 @@ export function uploadToChannel( ); let body: unknown; try { - body = await uploadConversationAttachment( - organizationId(), + body = await uploadAttachment({ channelId, - { file, uploadGroup }, - { "Idempotency-Key": idempotencyKey() }, + file, + uploadGroup, + inParts, // What is said when the server sent no sentence of its own, a proxy's error page included. - { fallback: couldNotUpload.message }, - ); + fallback: couldNotUpload.message, + }); } catch (error) { + // Taken off the composer by the person: the composer says nothing for it (`wasCancelled`). + if (wasCancelled(file)) throw error; + /* + * Tried again until it was no use: the connection, or OpenBot, never let it through. Trying + * once more by hand would only do the same, so the sentence doesn't ask for that. + */ + if (mayPass(error)) + throw new Error( + `'${file.name}' couldn't be uploaded. Check your connection, then attach it again.`, + ); // The server phrases refusals in the product's voice — naming the mime type or the limit // that was actually hit — so its sentence is preferred whenever it has really sent one. throw ( @@ -226,8 +238,10 @@ export function attachmentsConfigFor( * gone. See {@link previewUrlOf}. */ onPreview: (previewUrl: string) => void = () => {}, + /** Whether this OpenBot takes a large file in parts (the deployment's `attachmentUploadsInParts`). */ + inParts = false, ): AttachmentsConfig { - const upload = uploadToChannel(channelId, uploadGroup); + const upload = uploadToChannel(channelId, uploadGroup, inParts); return { enabled: true, accept: "*/*", @@ -392,9 +406,11 @@ export function heldFileOf( export async function uploadHeldFiles( channelId: string, attachments: readonly Attachment[], + /** Whether this OpenBot takes a large file in parts (the deployment's `attachmentUploadsInParts`). */ + inParts = false, ): Promise { // One group for one message: the set the server's per-message cap counts. - const upload = uploadToChannel(channelId, newId()); + const upload = uploadToChannel(channelId, newId(), inParts); const created: string[] = []; const settled = await Promise.allSettled( attachments.map(async (attachment): Promise => { diff --git a/app/src/components/channels/composer/composer.tsx b/app/src/components/channels/composer/composer.tsx index 3892e93b82..2b99776953 100644 --- a/app/src/components/channels/composer/composer.tsx +++ b/app/src/components/channels/composer/composer.tsx @@ -41,6 +41,7 @@ import { mediaTypeOf, shouldClaimPaste, } from "@/lib/channels/attachments"; +import { cancelUpload, wasCancelled } from "@/lib/channels/upload-progress"; import type { ComposerAttachmentLimits } from "@/lib/deployment/queries"; import { newId } from "@/lib/new-id"; import { stopIfNeedsCard } from "@/lib/plan/queries"; @@ -73,6 +74,7 @@ import { } from "./draft"; import { MESSAGE_BOX_FRAME } from "./frame"; import { screenPickedFiles } from "./picked-files"; +import { usePlaceholderFiles } from "./placeholder-files"; import { type RejectedFile, RejectedFiles } from "./rejected-files"; import { loadHeldFiles, @@ -558,6 +560,8 @@ export function Composer({ * would never arrive. Every upload refusal in the app comes through here. */ const limits = attachmentLimits?.limits ?? DEFAULT_ATTACHMENT_LIMITS; + // Whether this OpenBot takes a large file in parts, so a slow connection can still send it. + const inParts = attachmentLimits?.inParts === true; // Whether the Bot can read a large text file to its end: then nothing on the tile warns it is cut. const readsWhole = attachmentLimits?.readsWhole === true; /* @@ -568,6 +572,8 @@ export function Composer({ refreshLimits.current = attachmentLimits?.refresh; const recordRejection = useCallback((failure: UploadFailure) => { + // Stopped because the person removed it: what they asked for, so nothing to say. + if (wasCancelled(failure.file)) return; setRejected((current) => [ ...current, { @@ -667,6 +673,7 @@ export function Composer({ recordUpload, limits, recordHeld, + inParts, ) : holdsFilesUntilSent ? heldAttachmentsConfig(recordRejection, recordHeld, limits) @@ -679,6 +686,7 @@ export function Composer({ recordUpload, recordHeld, limits, + inParts, ], ); @@ -726,6 +734,20 @@ export function Composer({ removeAttachment, } = useAttachments({ config: attachmentsConfig }); + /* + * Which `File` each uploading tile is, so a file sent in parts shows how far it has got and stops + * when it is removed. Every file reaches `processFiles` through `processNoted`, which notes it + * first; see `usePlaceholderFiles`. + */ + const { willProcess, fileOf } = usePlaceholderFiles(attachments); + const processNoted = useCallback( + (files: File[]) => { + willProcess(files); + return processFiles(files); + }, + [willProcess, processFiles], + ); + /** * THERE IS A CHANNEL TO UPLOAD TO **AND** THIS CONVERSATION CAN STILL TAKE A MESSAGE. * @@ -795,8 +817,20 @@ export function Composer({ const discardAttachment = useCallback( // Unconditional: the person asked for the chip to be gone, and nothing here is allowed to make // that wait on a round trip. - (id: string) => removeAttachment(id), - [removeAttachment], + (id: string) => { + /* + * A file still going up in parts stops, so it no longer holds the line every file's parts + * share. Its tile is the one being removed, so nothing is said about it (`recordRejection`). + */ + const uploading = attachments.find( + (attachment) => + attachment.id === id && attachment.status === "uploading", + ); + const file = uploading ? fileOf(uploading) : undefined; + if (file) cancelUpload(file); + removeAttachment(id); + }, + [attachments, fileOf, removeAttachment], ); /** @@ -968,12 +1002,12 @@ export function Composer({ stagedCount.current += screened.accepted.length; staging.current += screened.accepted.length; try { - await processFiles(screened.accepted.map(withMediaTypeOnly)); + await processNoted(screened.accepted.map(withMediaTypeOnly)); } finally { staging.current -= screened.accepted.length; } }, - [disabled, processFiles, queuedAttachmentCount, limits], + [disabled, processNoted, queuedAttachmentCount, limits], ); /** `initialFiles` has been put back once, and is not owed again for the life of this composer. */ @@ -1028,7 +1062,7 @@ export function Composer({ stagedCount.current += restorable.length; staging.current += restorable.length; try { - await processFiles(restorable.map(restoringFile)); + await processNoted(restorable.map(restoringFile)); } finally { staging.current -= restorable.length; } @@ -1047,7 +1081,7 @@ export function Composer({ canAttach, channelId, holdsFilesUntilSent, - processFiles, + processNoted, savedKey, stageFiles, ]); @@ -1377,6 +1411,18 @@ export function Composer({ [stageFiles], ); + /* + * The `File` behind each uploading tile, read for every attachment in the order the SDK added + * them (which is what `fileOf` matches on), so a tile sent in parts shows how far it has got. + */ + const uploadingFiles = useMemo( + () => + new Map( + attachments.map((attachment) => [attachment.id, fileOf(attachment)]), + ), + [attachments, fileOf], + ); + /** * PromptArea already draws an attachment strip, so these map onto its props rather than adding a * second one. An upload in flight has no preview to show — its placeholder source is an empty @@ -1410,6 +1456,7 @@ export function Composer({ .filter((attachment) => stagedModality(attachment) === "image") .map((attachment) => ({ id: attachment.id, + uploadingFile: uploadingFiles.get(attachment.id), // Where the tile loads the picture from. While it uploads that is the browser's own // preview; once the server has it, the upload answers with the form a sent message // stores, and the file is read from the API's address for it. @@ -1426,7 +1473,7 @@ export function Composer({ ? { mimeType: attachment.source.mimeType } : {}), })), - [staged], + [staged, uploadingFiles], ); /** @@ -1448,6 +1495,7 @@ export function Composer({ size: attachment.size, mimeType: stagedMimeType(attachment), loading: attachment.status === "uploading", + uploadingFile: uploadingFiles.get(attachment.id), /* * Warned, never refused. The server accepts the whole file and the * model reads its first MAX_EXTRACTED_CHARACTERS; mayBeTruncatedForModel @@ -1480,7 +1528,7 @@ export function Composer({ !stagedIsDocument(attachment) && mayBeTruncatedForModel(attachment.size), })), - [staged, readsWhole], + [staged, readsWhole, uploadingFiles], ); const isBusy = pending || isSubmitting; diff --git a/app/src/components/channels/composer/placeholder-files.ts b/app/src/components/channels/composer/placeholder-files.ts new file mode 100644 index 0000000000..3260b8f110 --- /dev/null +++ b/app/src/components/channels/composer/placeholder-files.ts @@ -0,0 +1,53 @@ +import type { Attachment } from "@copilotkit/react-core/v2"; +import { useCallback, useEffect, useRef } from "react"; + +/** + * WHICH `File` EACH UPLOADING TILE IS, SO THE TILE CAN SHOW HOW FAR IT HAS GOT AND STOP IT. + * + * The SDK makes a placeholder for each file handed to `processFiles`, with an id of its own, and + * calls `onUpload` with the `File` alone: it never says which placeholder a call is for. What it + * does keep is the order. Every placeholder is appended to the attachments in the order its file + * was handed over, with that file's name and size. So each file is noted here as it is handed over + * (`willProcess`), and the next new placeholder with its name and size is that file + * (`fileOf`). A file the SDK turned away makes no placeholder; it is passed over by the name and + * size of the next one, and let go once nothing is uploading. + */ +export function usePlaceholderFiles(attachments: readonly Attachment[]): { + willProcess: (files: readonly File[]) => void; + fileOf: (attachment: Attachment) => File | undefined; +} { + const waiting = useRef([]); + const known = useRef(new Map()); + + const willProcess = useCallback((files: readonly File[]) => { + waiting.current.push(...files); + }, []); + + /* + * Called while drawing, for each attachment in order. It only ever adds what is certain (a new + * placeholder and the first file it can be), so drawing twice changes nothing. + */ + const fileOf = useCallback((attachment: Attachment): File | undefined => { + const seen = known.current.get(attachment.id); + if (seen || attachment.status !== "uploading") return seen; + const index = waiting.current.findIndex( + (file) => + file.name === attachment.filename && file.size === attachment.size, + ); + if (index < 0) return undefined; + const [file] = waiting.current.splice(index, 1); + known.current.set(attachment.id, file); + return file; + }, []); + + // Nothing kept for a tile that has gone, nor, once nothing is uploading, for a file still waiting. + useEffect(() => { + const present = new Set(attachments.map((attachment) => attachment.id)); + for (const id of known.current.keys()) + if (!present.has(id)) known.current.delete(id); + if (!attachments.some((attachment) => attachment.status === "uploading")) + waiting.current = []; + }, [attachments]); + + return { willProcess, fileOf }; +} diff --git a/app/src/lib/api/request.ts b/app/src/lib/api/request.ts index 7c68d0376e..47037cdb54 100644 --- a/app/src/lib/api/request.ts +++ b/app/src/lib/api/request.ts @@ -6,7 +6,7 @@ * carries the session the way every other request in the app does, and a refusal reaches a screen as * the same `ClientError` with the server's own sentence, or the `fallback` the caller named. */ -import { clientRequest } from "@/lib/client"; +import { clientRequest, type UploadProgress } from "@/lib/client"; /** What a caller of a generated function may add to the request it makes. */ export type ApiRequestOptions = RequestInit & { @@ -33,6 +33,12 @@ export type ApiRequestOptions = RequestInit & { * sent again. The window's report of a Desktop installation (lib/auth/window-session.ts). */ renew?: false; + /** + * Told how many bytes of the body have gone out, as they go: a file's part on a slow connection, + * whose tile shows how far it has got. The request is then sent with XMLHttpRequest, the one way a + * browser reports an upload's progress (`sendFollowingUpload` in lib/client.ts). + */ + onUploadProgress?: UploadProgress; }; /** @@ -75,13 +81,20 @@ export async function apiRequest( url: string, options: ApiRequestOptions = {}, ): Promise { - const { fallback, onResponse, kept, renew, ...init } = options; + const { fallback, onResponse, kept, renew, onUploadProgress, ...init } = + options; if (kept) { const headers = new Headers(init.headers); headers.set("If-None-Match", kept.etag); init.headers = headers; } - const response = await clientRequest(url, init, fallback, renew); + const response = await clientRequest( + url, + init, + fallback, + renew, + onUploadProgress, + ); onResponse?.(response); if (response.status === 304 && kept) return kept.body as T; if (response.status === 204) return undefined as T; diff --git a/app/src/lib/channels/start.ts b/app/src/lib/channels/start.ts index 412b83de03..e7ee1e223c 100644 --- a/app/src/lib/channels/start.ts +++ b/app/src/lib/channels/start.ts @@ -10,6 +10,7 @@ import { forgetSavedDraft } from "@/components/channels/composer/saved-draft"; import { stashFirstMessage } from "@/components/channels/transcript-messages"; import { newConversationBot } from "@/lib/agents/default-agent"; import type { AgentProfile } from "@/lib/agents/queries"; +import { attachmentLimitsQueryOptions } from "@/lib/deployment/queries"; import { createGroupMutationOptions, groupQueryOptions, @@ -207,7 +208,14 @@ export function useStartChannel( ...(files.length > 0 ? { upload: async (channelId: string) => { - attachments = await uploadHeldFiles(channelId, files); + attachments = await uploadHeldFiles( + channelId, + files, + // As the screen's composer read it (`useAttachmentLimits`): in parts where offered. + queryClient.getQueryData( + attachmentLimitsQueryOptions().queryKey, + )?.inParts === true, + ); }, } : {}), diff --git a/app/src/lib/channels/upload-progress.ts b/app/src/lib/channels/upload-progress.ts new file mode 100644 index 0000000000..e4b65fd5e1 --- /dev/null +++ b/app/src/lib/channels/upload-progress.ts @@ -0,0 +1,109 @@ +import { useSyncExternalStore } from "react"; + +/** + * HOW FAR EACH FILE SENT IN PARTS HAS GOT, FOR ITS TILE ON THE COMPOSER, AND THE WAY TO STOP ONE. + * + * The SDK's attachment has no progress of its own, and its `onUpload` is handed a `File` and never + * told which tile that file is drawn as. So the progress is kept here, by the `File` itself: the + * upload writes to it (`trackUpload`), and the composer, which knows which `File` each tile stands + * for (`usePlaceholderFiles`), reads it for that tile (`useUploadPercent`). Only a tile that is + * showing a file's progress re-renders as it moves, and only when its whole percentage changes. + * + * A file sent in one request is never tracked: its tile keeps today's "Uploading…". + */ +type Tracked = { + size: number; + percent: number; + controller: AbortController; +}; + +const tracked = new Map(); +const cancelled = new WeakSet(); +const listeners = new Set<() => void>(); + +function changed() { + for (const listener of listeners) listener(); +} + +/** Why an upload stopped: the person took its file off the composer. */ +export class UploadCancelled extends Error { + constructor(file: File) { + super(`'${file.name}' was removed before it finished uploading.`); + this.name = "UploadCancelled"; + } +} + +/** + * Start following one file's upload. `sent` reports the bytes the server has, or is being sent, so + * far; `signal` is aborted when the person removes the file; `done` forgets it once it has settled. + */ +export function trackUpload(file: File): { + sent: (bytes: number) => void; + signal: AbortSignal; + done: () => void; +} { + const entry: Tracked = { + size: file.size, + percent: 0, + controller: new AbortController(), + }; + tracked.set(file, entry); + changed(); + return { + sent: (bytes) => { + /* + * Whole percent, and never 100 until it has finished: a full bar on a file that isn't on the + * strip yet reads as done while the server is still putting the parts together. + */ + const percent = Math.min( + 99, + Math.floor((bytes / Math.max(1, entry.size)) * 100), + ); + if (percent === entry.percent || tracked.get(file) !== entry) return; + entry.percent = percent; + changed(); + }, + signal: entry.controller.signal, + done: () => { + if (tracked.get(file) !== entry) return; + tracked.delete(file); + changed(); + }, + }; +} + +/** + * Stop the upload of a file the person took off the composer, so it no longer holds the line that + * every file's parts share. A file that isn't being followed (sent in one request, or finished) is + * left as it is: the composer gives back whatever it uploaded once its tile has gone. + */ +export function cancelUpload(file: File): void { + const entry = tracked.get(file); + if (!entry) return; + cancelled.add(file); + entry.controller.abort(new UploadCancelled(file)); +} + +/** Whether this file's upload was stopped because the person removed it, so no refusal is shown. */ +export function wasCancelled(file: File): boolean { + return cancelled.has(file); +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener); + return () => listeners.delete(listener); +} + +/** The whole percentage of this file that has gone, while it is sent in parts; otherwise nothing. */ +export function uploadPercent(file: File | undefined): number | undefined { + return file ? tracked.get(file)?.percent : undefined; +} + +/** {@link uploadPercent}, kept current for a component. */ +export function useUploadPercent(file: File | undefined): number | undefined { + return useSyncExternalStore( + subscribe, + () => uploadPercent(file), + () => undefined, + ); +} diff --git a/app/src/lib/channels/upload.ts b/app/src/lib/channels/upload.ts new file mode 100644 index 0000000000..0a4d2fb948 --- /dev/null +++ b/app/src/lib/channels/upload.ts @@ -0,0 +1,340 @@ +import pLimit from "p-limit"; +import pRetry, { AbortError } from "p-retry"; +import { + cancelAttachmentUpload, + completeAttachmentUpload, + createAttachmentUpload, + uploadAttachmentPart, + uploadConversationAttachment, +} from "@/lib/api/generated/conversations/conversations"; +import type { Attachment } from "@/lib/api/generated/model"; +import { idempotencyKey, organizationId } from "@/lib/api/request"; +import { ClientError } from "@/lib/client"; +import { trackUpload } from "./upload-progress"; + +/** + * SENDING ONE PICKED FILE TO A CONVERSATION, SO THAT A SLOW CONNECTION CAN STILL SEND A LARGE ONE. + * + * A file sent in one request has to reach OpenBot before whatever stands in front of it gives up on + * the request: Cloudflare, in front of OpenBot Cloud, closes any request whose body takes more than + * 125 seconds to arrive. At 15 KB/s that is under 2MB, and sending it again changes nothing. So + * where OpenBot offers it (the deployment's `attachmentUploadsInParts`), a file over + * {@link PARTS_ABOVE_BYTES} goes in parts of the size OpenBot chooses, then is put together: the shape + * of OpenAI's Uploads, Slack's external uploads, Microsoft Graph's upload sessions and Google's + * resumable uploads. Each part is short enough to arrive, and a part that fails is sent again on its + * own. + * + * Every request is tried again by itself when the failure is one that passes: no answer, a timeout, + * a server that is busy or broken, or an edge that gave up (Cloudflare's 520 to 524). A refusal + * (any other 4xx) is the answer and is not asked again. See {@link sendRetrying}. + */ + +/** Files up to this size go in one request even where parts are offered: one part's worth. */ +export const PARTS_ABOVE_BYTES = 1024 * 1024; + +/** + * ONE PART IN FLIGHT AT A TIME, ACROSS EVERY FILE IN THIS TAB. + * + * Several files uploading at once share one connection. Sent side by side, two parts each get half + * of it, so each takes twice as long, and on the slow connection this exists for that pushes every + * one of them past the edge's limit: a 1MB part at 15 KB/s takes about 70 seconds alone, and 140 + * shared. One at a time, every part takes as long as it would alone, and the files still finish + * as soon as the connection allows. Starting and finishing an upload carry no file and don't wait. + */ +const partLane = pLimit(1); + +/** + * How each request is tried again: up to 8 tries, waiting about 1, 2, 4 and 8 seconds and then at + * most 30, each wait drawn at random between one and two times its step (jitter), so tabs that + * failed together don't all come back at once. The defaults of Google's and AWS's storage clients. + */ +const RETRIES = { + retries: 7, + minTimeout: 1000, + factor: 2, + maxTimeout: 30_000, + randomize: true, +} as const; + +/** The longest a server's `Retry-After` is waited out before the next try. */ +const LONGEST_RETRY_AFTER_MS = 60_000; + +/** + * Whether a failed request may succeed if it is sent again unchanged, as Google's and AWS's + * guidance for retrying uploads has it: no answer at all, a timeout (408), too many requests (429), + * any server error (5xx, Cloudflare's 520 to 524 among them), or a refusal OpenBot itself marks + * `retryable` (the same request's first try still running, 409 `IDEMPOTENCY_IN_PROGRESS`). Never + * any other refusal. + */ +export function mayPass(error: unknown): boolean { + // No answer at all: the connection dropped, or the browser gave up (`NoAnswerError`). + if (error instanceof TypeError) return true; + if (!(error instanceof ClientError)) return false; + return ( + error.status === 408 || + error.status === 429 || + (error.status >= 500 && error.status <= 599) || + error.body?.retryable === true + ); +} + +/** + * A failure that may pass, as p-retry is handed it. p-retry never tries a TypeError again unless + * its words are a browser's own for a lost connection, and the app says a lost connection in + * OpenBot's words (`NoAnswerError`), so each failure worth another try goes in wrapped. + */ +class MayPass extends Error { + constructor(readonly failure: unknown) { + super("This request may pass if it is sent again."); + this.name = "MayPass"; + } +} + +function asError(value: unknown): Error { + return value instanceof Error ? value : new Error(String(value)); +} + +function waitFor(ms: number, signal?: AbortSignal): Promise { + return new Promise((resolve) => { + const timer = setTimeout(resolve, ms); + signal?.addEventListener( + "abort", + () => { + clearTimeout(timer); + resolve(); + }, + { once: true }, + ); + }); +} + +/** Send a request, and again while its failure may pass. Throws the last failure as it came. */ +export async function sendRetrying( + send: () => Promise, + signal?: AbortSignal, +): Promise { + try { + return await pRetry( + async () => { + try { + return await send(); + } catch (error) { + if (signal?.aborted || !mayPass(error)) + throw new AbortError(asError(error)); + throw new MayPass(error); + } + }, + { + ...RETRIES, + signal, + // A server that said how long to leave it is left that long, not only the step's wait. + onFailedAttempt: async ({ error, retriesLeft, retryDelay }) => { + if (retriesLeft === 0 || !(error instanceof MayPass)) return; + const { failure } = error; + const asked = + failure instanceof ClientError ? failure.retryAfterMs : undefined; + if (asked !== undefined && asked > retryDelay) + await waitFor( + Math.min(asked, LONGEST_RETRY_AFTER_MS) - retryDelay, + signal, + ); + }, + }, + ); + } catch (error) { + throw error instanceof MayPass ? error.failure : error; + } +} + +/** The refusal to finish an upload that is missing a part. */ +const PARTS_MISSING = "ATTACHMENT_PARTS_MISSING"; + +/** + * The parts a refusal to finish says haven't arrived: 409 `ATTACHMENT_PARTS_MISSING`, which lists + * them item by item (`problems`, one `partNumber` each), or every part when it lists none. Any other + * refusal (the message already holds as many files as it may) names none, and re-sending the parts + * wouldn't change it. + */ +export function missingPartsIn(error: unknown, partCount: number): number[] { + if ( + !(error instanceof ClientError) || + error.status !== 409 || + error.code !== PARTS_MISSING + ) + return []; + const every = Array.from({ length: partCount }, (_, index) => index + 1); + const problems = error.body?.problems; + if (!Array.isArray(problems)) return every; + const parts = new Set(); + for (const problem of problems) { + const partNumber = (problem as { partNumber?: unknown } | null)?.partNumber; + if ( + Number.isInteger(partNumber) && + (partNumber as number) >= 1 && + (partNumber as number) <= partCount + ) + parts.add(partNumber as number); + } + return parts.size === 0 ? every : [...parts].sort((a, b) => a - b); +} + +export type UploadInput = { + channelId: string; + file: File; + /** Names the message being written, so the server counts the files of one composer. */ + uploadGroup?: string; + /** Whether this OpenBot takes a file in parts (the deployment's `attachmentUploadsInParts`). */ + inParts: boolean; + /** What a person reads when OpenBot refused without saying why. */ + fallback: string; +}; + +/** + * Send one file to a conversation, held for the next message, and answer what OpenBot stored. + * + * In parts where OpenBot takes them and the file is larger than one part; otherwise in one + * request, as every OpenBot takes it. Throws the last failure when a request was refused or never + * passed; an upload in parts that doesn't finish is stopped on the server, so its parts don't wait + * there for the day it takes to expire. + */ +export async function uploadAttachment({ + channelId, + file, + uploadGroup, + inParts, + fallback, +}: UploadInput): Promise { + if (!inParts || file.size <= PARTS_ABOVE_BYTES) { + // One key for every try, so OpenBot recognises a try whose answer was lost as the same upload. + const key = idempotencyKey(); + return sendRetrying(() => + uploadConversationAttachment( + organizationId(), + channelId, + { file, uploadGroup }, + { "Idempotency-Key": key }, + { fallback }, + ), + ); + } + const progress = trackUpload(file); + try { + return await uploadInParts({ + channelId, + file, + uploadGroup, + fallback, + progress, + }); + } finally { + progress.done(); + } +} + +async function uploadInParts({ + channelId, + file, + uploadGroup, + fallback, + progress, +}: Omit & { + progress: ReturnType; +}): Promise { + const { signal } = progress; + const startKey = idempotencyKey(); + /* + * Not stopped half way when the file is removed: the upload it starts is one only its answer + * names, and it is stopped on the server just below once that answer is in. + */ + const upload = await sendRetrying(() => + createAttachmentUpload( + organizationId(), + channelId, + { + name: file.name, + sizeBytes: file.size, + ...(uploadGroup === undefined ? {} : { uploadGroup }), + }, + { "Idempotency-Key": startKey }, + { fallback }, + ), + ); + let finished = false; + /** Send one part, one part at a time across the tab, and again while its failure may pass. */ + const sendPart = async (partNumber: number, arrived: number) => { + const start = (partNumber - 1) * upload.partBytes; + const part = file.slice(start, start + upload.partBytes); + // The same key for every try of this part: sending a part again replaces it. + const key = idempotencyKey(); + await sendRetrying( + () => + partLane(() => { + signal.throwIfAborted(); + return uploadAttachmentPart( + organizationId(), + upload.id, + partNumber, + part, + { "Idempotency-Key": key }, + { + fallback, + signal, + // What has arrived, and as much of this part as has gone so far. + onUploadProgress: (sent) => + progress.sent(arrived + Math.min(sent, part.size)), + }, + ); + }), + signal, + ); + return part.size; + }; + /* + * From the finish on, the upload completes even if the file is removed: once OpenBot has stored + * it, the composer gives back a file with no tile like any other (its reconciler), and a request + * stopped half way could leave one stored that nothing knows about. A new key each time it is + * asked: a refusal is remembered under its key, and asking again after sending what was missing + * is a different request. + */ + const finish = () => { + const key = idempotencyKey(); + return sendRetrying(() => + completeAttachmentUpload( + organizationId(), + upload.id, + { "Idempotency-Key": key }, + { fallback }, + ), + ); + }; + try { + let arrived = 0; + for (let partNumber = 1; partNumber <= upload.partCount; partNumber++) { + arrived += await sendPart(partNumber, arrived); + progress.sent(arrived); + } + signal.throwIfAborted(); + let attachment: Attachment; + try { + attachment = await finish(); + } catch (error) { + /* + * A part OpenBot says hasn't arrived, though it answered for every one: send those again, + * once (sending a part again replaces it), and finish again. Any other refusal is the answer. + */ + const missing = missingPartsIn(error, upload.partCount); + if (missing.length === 0) throw error; + for (const partNumber of missing) await sendPart(partNumber, arrived); + attachment = await finish(); + } + finished = true; + return attachment; + } finally { + if (!finished) { + // Best effort: an upload nobody stops is removed when it expires. + void cancelAttachmentUpload(organizationId(), upload.id, { + "Idempotency-Key": idempotencyKey(), + }).catch(() => undefined); + } + } +} diff --git a/app/src/lib/client.ts b/app/src/lib/client.ts index 92bb8b5a7e..eb5b2c5d40 100644 --- a/app/src/lib/client.ts +++ b/app/src/lib/client.ts @@ -173,6 +173,74 @@ function answeredByAPage(response: Response): boolean { return /^\s*(text\/html|application\/xhtml\+xml)\b/i.test(type); } +/** How many bytes of a request's body have gone out so far. */ +export type UploadProgress = (sentBytes: number) => void; + +/** + * A request whose caller follows its body going out, for a file's part on a slow connection. + * + * XMLHttpRequest, because `fetch` says nothing while a body is being sent: no browser reports a + * `fetch` upload's progress. `upload.onprogress` is the one way every browser reports it. Everything else is + * what `fetch` would do: the same method, headers, body and cookie, a `Response` with the status, + * headers and body the server sent, a TypeError when there is no answer at all, and an + * AbortError when the caller gives up. + */ +function sendFollowingUpload( + url: string, + init: RequestInit, + onUploadProgress: UploadProgress, +): Promise { + return new Promise((resolve, reject) => { + const { signal } = init; + if (signal?.aborted) { + reject(signal.reason); + return; + } + const xhr = new XMLHttpRequest(); + xhr.open(init.method ?? "GET", url); + xhr.withCredentials = init.credentials === "include"; + xhr.responseType = "blob"; + for (const [name, value] of new Headers(init.headers)) + xhr.setRequestHeader(name, value); + xhr.upload.onprogress = (event) => onUploadProgress(event.loaded); + const abort = () => xhr.abort(); + signal?.addEventListener("abort", abort, { once: true }); + const settle = () => signal?.removeEventListener("abort", abort); + xhr.onload = () => { + settle(); + // A status that has no body may not be given one (the Fetch standard's null body statuses). + const empty = [101, 103, 204, 205, 304].includes(xhr.status); + resolve( + new Response(empty ? null : (xhr.response as Blob), { + status: xhr.status, + statusText: xhr.statusText, + headers: headersOf(xhr.getAllResponseHeaders()), + }), + ); + }; + xhr.onerror = xhr.ontimeout = () => { + settle(); + reject(new TypeError("Network request failed")); + }; + xhr.onabort = () => { + settle(); + reject(signal?.reason ?? new DOMException("Aborted", "AbortError")); + }; + xhr.send((init.body ?? null) as XMLHttpRequestBodyInit | null); + }); +} + +/** The headers `getAllResponseHeaders` lists, one `name: value` to a line. */ +function headersOf(raw: string): Headers { + const headers = new Headers(); + for (const line of raw.trim().split(/[\r\n]+/)) { + const colon = line.indexOf(":"); + if (colon > 0) + headers.append(line.slice(0, colon).trim(), line.slice(colon + 1).trim()); + } + return headers; +} + /** * The one `fetch`. Each outcome is reported to `lib/desktop/reachability.ts`, which is how the app * knows the OpenBot it talks to stopped answering, and answers again. A web page answering an API @@ -189,17 +257,24 @@ function answeredByAPage(response: Response): boolean { * seconds are each kept for the troubleshooting logs, and inside OpenBot Desktop handed to its log * (`lib/desktop/problems.ts`): its method, its path without the query, and the server's request id. */ -async function attempt(path: string, init: RequestInit): Promise { +async function attempt( + path: string, + init: RequestInit, + onUploadProgress?: UploadProgress, +): Promise { // A request that fails, gets no answer, or is slow is kept for the troubleshooting logs. const watch = watchRequest(path, init.method); let response: Response; try { - response = await fetch(apiUrl(path), { + const sent: RequestInit = { ...init, headers: withClientName(init.headers), // The session's cookie, unless the caller asks as nobody (`readDeployment` for somebody in no organization). credentials: init.credentials ?? "include", - }); + }; + response = onUploadProgress + ? await sendFollowingUpload(apiUrl(path), sent, onUploadProgress) + : await fetch(apiUrl(path), sent); } catch (error) { watch.rejected(error); noteNoAnswer(error); @@ -231,8 +306,12 @@ async function attempt(path: string, init: RequestInit): Promise { * send. A hosted sign-in's own renewal (`OpenBot-Sign-In`, `lib/auth/renewal.ts`) is left to that, * and nothing renews while a hover's preload reads (`withoutEmbedRenewal`). */ -async function request(path: string, init: RequestInit): Promise { - const response = await attempt(path, init); +async function request( + path: string, + init: RequestInit, + onUploadProgress?: UploadProgress, +): Promise { + const response = await attempt(path, init, onUploadProgress); if ( response.status !== 401 || !embedConfig() || @@ -242,7 +321,7 @@ async function request(path: string, init: RequestInit): Promise { ) return response; if ((await renewEmbedSession()) !== "ok") return response; - return attempt(path, init); + return attempt(path, init, onUploadProgress); } /** Every request in this app is authenticated, and every one of them is JSON or nothing. */ @@ -408,8 +487,10 @@ export async function clientRequest( fallback?: string, /** `false`: a refusal that asks for a renewal starts none, and nothing is kept to send again. */ renew?: false, + /** Told how much of the body has gone out, as it goes (`sendFollowingUpload`). */ + onUploadProgress?: UploadProgress, ): Promise { - const response = await request(path, init); + const response = await request(path, init, onUploadProgress); // A 304 is an answer only to a request that named the copy it holds (`If-None-Match`). if (response.status === 304 && new Headers(init.headers).has("If-None-Match")) return response; diff --git a/app/src/lib/deployment/queries.ts b/app/src/lib/deployment/queries.ts index 087bac9866..20da3b0f29 100644 --- a/app/src/lib/deployment/queries.ts +++ b/app/src/lib/deployment/queries.ts @@ -287,6 +287,7 @@ export function attachmentLimitsQueryOptions() { return { limits: attachmentLimitsFrom(body.attachmentLimits), readsWhole: body.attachmentsReadWhole === true, + inParts: body.attachmentUploadsInParts === true, }; }, }); @@ -321,6 +322,12 @@ export type AttachmentReading = { limits: AttachmentLimits; /** Whether a Bot can read the whole of a text file past the part it is first shown. */ readsWhole: boolean; + /** + * Whether a large file can be sent in parts (`attachmentUploadsInParts`), so a slow connection can + * still attach it. Read with the limits because it too changes when the server is upgraded. + * Absent is no: an older server takes each file in one request. + */ + inParts?: boolean; }; /** The limits a composer screens a pick against, and how it asks for them again. */ @@ -341,6 +348,7 @@ export function useAttachmentLimits(): ComposerAttachmentLimits { () => ({ limits: query.data?.limits ?? DEFAULT_ATTACHMENT_LIMITS, readsWhole: query.data?.readsWhole ?? false, + inParts: query.data?.inParts ?? false, refresh: () => void refetch(), }), [query.data, refetch], diff --git a/app/tests/composer-attachments.test.ts b/app/tests/composer-attachments.test.ts index fbc72ba8d1..24cacddf01 100644 --- a/app/tests/composer-attachments.test.ts +++ b/app/tests/composer-attachments.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, jest, test } from "bun:test"; import { attachmentsConfigFor, FILE_PICKER_ACCEPT, @@ -106,10 +106,11 @@ describe("uploadToChannel", () => { ).rejects.toThrow(/SVG/); }); + // A refusal (a 4xx that isn't worth asking again): a 5xx is now sent again by itself. test("a non-JSON error body throws a named fallback, not a JSON parse error", async () => { global.fetch = (async () => - new Response("Internal Server Error", { - status: 500, + new Response("Bad Request", { + status: 400, headers: { "content-type": "text/plain" }, })) as unknown as typeof fetch; @@ -123,7 +124,7 @@ describe("uploadToChannel", () => { test("a JSON error body with no `detail` throws the named fallback, not an empty message", async () => { global.fetch = (async () => - jsonResponse({}, 500)) as unknown as typeof fetch; + jsonResponse({}, 400)) as unknown as typeof fetch; await expect( uploadToChannel("chan_1", "group_1")(file("receipt.png", "image/png")), @@ -196,6 +197,105 @@ describe("uploadToChannel", () => { }); }); +/** + * A FAILURE THAT MAY PASS IS SENT AGAIN BY ITSELF, AND ONLY ONE THAT NEVER DOES REACHES THE PERSON. + * + * The upload is tried again as Google's and AWS's storage clients try one (8 tries, about 1s + * doubling to 30s apart, with jitter), so the timers are the test's to run. What it proves: a server + * that broke once costs the person nothing, a refusal is never asked again, and a file that never + * got through is refused in words that don't promise another try will work. + */ +describe("uploadToChannel tries again by itself", () => { + /** Run the retries' waits as they come, until the upload settles. */ + async function settle(pending: Promise): Promise { + let done = false; + const watched = pending.finally(() => { + done = true; + }); + watched.catch(() => undefined); + while (!done) { + await new Promise((resolve) => setImmediate(resolve)); + jest.advanceTimersByTime(60_000); + } + return watched; + } + + beforeEach(() => { + jest.useFakeTimers(); + }); + afterEach(() => { + jest.useRealTimers(); + }); + + test("a server that failed once is asked again with the same key, and the file arrives", async () => { + const keys: (string | null)[] = []; + global.fetch = (async (_path: string, init: RequestInit) => { + keys.push(new Headers(init.headers).get("Idempotency-Key")); + return keys.length === 1 + ? jsonResponse(problemBody(503, "OpenBot is busy."), 503) + : jsonResponse( + { + id: "att_1", + name: "receipt.png", + mimeType: "image/png", + sizeBytes: 10, + }, + 201, + ); + }) as typeof fetch; + + const result = await settle( + uploadToChannel("chan_1", "group_1")(file("receipt.png", "image/png")), + ); + + expect(result.value).toBe("/api/attachments/att_1"); + expect(keys).toHaveLength(2); + expect(keys[0]).toBeTruthy(); + expect(keys[1]).toBe(keys[0] as string); + }); + + test("a refusal is not asked again", async () => { + let asked = 0; + global.fetch = (async () => { + asked += 1; + return jsonResponse( + problemBody( + 415, + "'icon.svg' can't be attached. SVG files aren't accepted.", + ), + 415, + ); + }) as unknown as typeof fetch; + + await expect( + settle( + uploadToChannel("chan_1", "group_1")(file("icon.svg", "image/svg+xml")), + ), + ).rejects.toThrow(/SVG/); + expect(asked).toBe(1); + }); + + test("a file that never got through is refused after 8 tries, without asking to try again", async () => { + let asked = 0; + global.fetch = (async () => { + asked += 1; + return new Response("A timeout occurred", { + status: 524, + headers: { "content-type": "text/html" }, + }); + }) as unknown as typeof fetch; + + await expect( + settle( + uploadToChannel("chan_1", "group_1")(file("receipt.png", "image/png")), + ), + ).rejects.toThrow( + "'receipt.png' couldn't be uploaded. Check your connection, then attach it again.", + ); + expect(asked).toBe(8); + }); +}); + describe("attachmentsConfigFor", () => { test("maxSize is the largest of the limits the screen used", () => { const config = attachmentsConfigFor( diff --git a/app/tests/upload-in-parts-browser.test.tsx b/app/tests/upload-in-parts-browser.test.tsx new file mode 100644 index 0000000000..f273cc9f35 --- /dev/null +++ b/app/tests/upload-in-parts-browser.test.tsx @@ -0,0 +1,1081 @@ +import { afterAll, beforeAll, describe, expect } from "bun:test"; +import { randomBytes } from "node:crypto"; +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { deflateSync } from "node:zlib"; +import type { Browser, BrowserType, Page } from "playwright-core"; +import { compile } from "tailwindcss"; +import { + CompleteAttachmentUploadHeader, + CompleteAttachmentUploadParams, + CompleteAttachmentUploadResponse, + CancelAttachmentUploadHeader, + CancelAttachmentUploadParams, + CreateAttachmentUploadBody, + CreateAttachmentUploadHeader, + CreateAttachmentUploadParams, + CreateAttachmentUploadResponse, + UploadAttachmentPartHeader, + UploadAttachmentPartParams, + UploadAttachmentPartResponse, + UploadConversationAttachmentHeader, + UploadConversationAttachmentParams, + UploadConversationAttachmentResponse, +} from "@/lib/api/generated/conversations/conversations.zod"; +import { getGetDeploymentResponseMock } from "@/lib/api/generated/organization-settings/organization-settings.msw"; +import { GetDeploymentResponse } from "@/lib/api/generated/organization-settings/organization-settings.zod"; +import { still } from "./page-still"; +import { test } from "./renderer-crash"; + +/** + * A large file attaches over a connection too slow to send it in one request, in a real browser. + * + * Reported from OpenBot Cloud: on an upload link of 15 to 35 KB/s, no file over about 4.5MB could + * be attached, however often it was tried. Cloudflare closes any request whose body takes more than + * 125 seconds to arrive, and the attachment went up in one request. Now, where the deployment + * offers it (`attachmentUploadsInParts`), a file over 1MB goes in parts, one at a time, each tried + * again by itself, and its tile shows how far it has got. + * + * The real message box, bundled from the fixture beside this file, uploads to a server here that + * answers every operation as api/openapi.yaml says, checked against the spec's own schemas, and + * stands in for the edge as well: any request whose body took longer than {@link EDGE_LIMIT_MS} to + * arrive is answered 524, as Cloudflare answers it. The connection is made slow in Chromium with its + * own network throttling, so the edge's limit is scaled down with it: the whole file takes several + * times the limit, one part well inside it. + * + * OPENBOT_APP_BROWSER=1 bun test app/tests/upload-in-parts-browser.test.tsx + * + * Chromium by default; OPENBOT_APP_ENGINES=chromium,webkit adds WebKit (the throttled test runs in + * Chromium only: WebKit has no network throttling). With OPENBOT_APP_SHOTS= the tiles are saved + * mid-upload and done, light and dark, wide and on a phone. + */ +const asked = process.env.OPENBOT_APP_BROWSER === "1"; +const shots = process.env.OPENBOT_APP_SHOTS; +const engines = (process.env.OPENBOT_APP_ENGINES ?? "chromium") + .split(",") + .map((engine) => engine.trim()) + .filter((engine) => engine === "chromium" || engine === "webkit") as ( + | "chromium" + | "webkit" +)[]; + +const APP = join(import.meta.dir, ".."); +const ORGANIZATION = "/api/v2/organizations/default"; + +/** The part size this server chooses, scaled down with the connection. */ +const PART_BYTES = 256 * 1024; +/** The edge's limit on how long a request's body may take to arrive, scaled down with the connection. */ +const EDGE_LIMIT_MS = 6_000; +/** The slow connection: 128 KB/s, so a 256KB part takes 2 seconds and the whole file about 17. */ +const UPLOAD_BYTES_PER_SECOND = 128 * 1024; + +/** A PDF of a little over 2MB: nine parts, the last one short. */ +const DOCUMENT = { + name: "site-survey.pdf", + mimeType: "application/pdf", + buffer: Buffer.concat([ + Buffer.from("%PDF-1.7\n"), + randomBytes(2 * 1024 * 1024 + 4321), + ]), +}; + +/** A picture of a little over 1MB, so it too goes in parts. */ +function picture(): Buffer { + const side = 620; + const row = side * 3 + 1; + const raw = Buffer.alloc(row * side); + const noise = randomBytes(row * side); + for (let y = 0; y < side; y++) + for (let x = 0; x < side; x++) { + const at = y * row + 1 + x * 3; + const sky = y < side * 0.6; + raw[at] = (sky ? 80 : 50) + (noise[at] % 40); + raw[at + 1] = (sky ? 150 : 120) + (noise[at + 1] % 40); + raw[at + 2] = (sky ? 225 : 70) + (noise[at + 2] % 30); + } + const table = Array.from({ length: 256 }, (_, n) => { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; + }); + const chunk = (type: string, data: Buffer) => { + const typed = Buffer.concat([Buffer.from(type, "ascii"), data]); + let crc = 0xffffffff; + for (const byte of typed) crc = table[(crc ^ byte) & 0xff] ^ (crc >>> 8); + const length = Buffer.alloc(4); + length.writeUInt32BE(data.length); + const sum = Buffer.alloc(4); + sum.writeUInt32BE((crc ^ 0xffffffff) >>> 0); + return Buffer.concat([length, typed, sum]); + }; + const header = Buffer.alloc(13); + header.writeUInt32BE(side, 0); + header.writeUInt32BE(side, 4); + header[8] = 8; + header[9] = 2; + return Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + chunk("IHDR", header), + chunk("IDAT", deflateSync(raw, { level: 0 })), + chunk("IEND", Buffer.alloc(0)), + ]); +} +const PICTURE = { + name: "roof-photo.png", + mimeType: "image/png", + buffer: picture(), +}; + +/** A text file well under one part: always one request. */ +const NOTES = { + name: "notes.txt", + mimeType: "text/plain", + buffer: Buffer.from( + "Gutters on the north side need replacing.\n".repeat(800), + ), +}; + +type Upload = { + id: string; + name: string; + sizeBytes: number; + partCount: number; + parts: Map; + cancelled: boolean; + completed?: { id: string; name: string; mimeType: string; sizeBytes: number }; +}; + +/** What the server was asked and what it did, per test. */ +type Server = { + inParts: boolean; + uploads: Map; + /** Every file stored, by its attachment id. */ + stored: Map; + /** Each request, as `METHOD what`, with the key it carried. */ + log: { what: string; key: string | null; status: number }[]; + /** Requests the spec's schemas refused: the app sent something the API doesn't take. */ + refused: string[]; + /** A part to answer 503 the first time it arrives, as a broken server does. */ + failPartOnce?: number; + /** A part answered 503 every time, as a server that stays broken. */ + failPartAlways?: number; + /** A part answered as taken the first time and then lost, so finishing finds it missing. */ + losePartOnce?: number; + /** A part whose answer waits until the test lets it go, so a tile can be seen mid-upload. */ + hold?: { part: number; until: Promise }; + /** Holds the one-request upload too, for the photographs of the tile before this change. */ + holdWhole?: Promise; + /** How long each part's body took to arrive, in milliseconds. */ + bodyTimes: number[]; +}; + +let server: Server; + +/** What the test is waiting for the server to have been asked. */ +let waiters: { check: () => boolean; resolve: () => void }[] = []; + +/** Once the server's log says `check`: woken by each request it answers, never by a clock. */ +function serverSaw(check: () => boolean): Promise { + if (check()) return Promise.resolve(); + return new Promise((resolve) => waiters.push({ check, resolve })); +} + +function freshServer(inParts: boolean): Server { + return { + inParts, + uploads: new Map(), + stored: new Map(), + log: [], + refused: [], + bodyTimes: [], + }; +} + +let port = 0; +let http: ReturnType | undefined; +const origin = () => `http://127.0.0.1:${port}`; + +/** + * The edge in front of the server: a body that took too long to arrive is answered 524. How long + * each took is kept, so a test can say the connection really was slow. + */ +async function bodyOf(request: Request): Promise { + const started = performance.now(); + const bytes = Buffer.from(await request.arrayBuffer()); + const took = performance.now() - started; + server.bodyTimes.push(took); + return took > EDGE_LIMIT_MS ? null : bytes; +} + +const timedOut = () => + new Response("A timeout occurred", { + status: 524, + headers: { "content-type": "text/html" }, + }); + +function checked(what: string, parse: () => T): T | undefined { + try { + return parse(); + } catch (error) { + server.refused.push(`${what}: ${String(error)}`); + return undefined; + } +} + +const badRequest = () => + Response.json( + { + type: "about:blank", + title: "Bad request.", + status: 400, + detail: "Bad request.", + }, + { status: 400, headers: { "content-type": "application/problem+json" } }, + ); + +async function answer(request: Request, path: string): Promise { + const key = request.headers.get("Idempotency-Key"); + const logged = (what: string, response: Response) => { + server.log.push({ + what: `${request.method} ${what}`, + key, + status: response.status, + }); + waiters = waiters.filter((waiter) => { + if (!waiter.check()) return true; + waiter.resolve(); + return false; + }); + return response; + }; + const json = ( + schema: { parse: (value: unknown) => unknown }, + body: unknown, + status: number, + ) => Response.json(schema.parse(body), { status }); + + if (path === `${ORGANIZATION}/deployment`) { + const body = GetDeploymentResponse.parse({ + ...getGetDeploymentResponseMock(), + edition: "team", + generativeUi: true, + transcription: false, + voice: false, + attachmentLimits: { + imageBytes: 100 * 1024 * 1024, + documentBytes: 100 * 1024 * 1024, + fileBytes: 100 * 1024 * 1024, + }, + attachmentsReadWhole: true, + attachmentUploadsInParts: server.inParts, + }); + return Response.json(body); + } + + // The one-request upload, as every OpenBot takes it. + const whole = path.match( + /^\/api\/v2\/organizations\/([^/]+)\/conversations\/([^/]+)\/attachments$/, + ); + if (whole && request.method === "POST") { + const ok = + checked("uploadConversationAttachment params", () => + UploadConversationAttachmentParams.parse({ + organizationId: whole[1], + conversationId: whole[2], + }), + ) && + checked("uploadConversationAttachment header", () => + UploadConversationAttachmentHeader.parse({ "Idempotency-Key": key }), + ); + const form = await (async () => { + const started = performance.now(); + const data = await request.formData(); + const took = performance.now() - started; + server.bodyTimes.push(took); + return took > EDGE_LIMIT_MS ? null : data; + })(); + if (!form) return logged("attachments", timedOut()); + if (!ok) return logged("attachments", badRequest()); + await server.holdWhole; + const file = form.get("file") as File; + const id = `stored-${server.stored.size + 1}`; + server.stored.set(id, { + name: file.name, + bytes: Buffer.from(await file.arrayBuffer()), + }); + return logged( + "attachments", + json( + UploadConversationAttachmentResponse, + { + id, + name: file.name, + mimeType: file.type || "application/octet-stream", + sizeBytes: file.size, + }, + 201, + ), + ); + } + + const create = path.match( + /^\/api\/v2\/organizations\/([^/]+)\/conversations\/([^/]+)\/attachment-uploads$/, + ); + if (create && request.method === "POST") { + const started = (await request.json()) as unknown; + const input = + checked("createAttachmentUpload params", () => + CreateAttachmentUploadParams.parse({ + organizationId: create[1], + conversationId: create[2], + }), + ) && + checked("createAttachmentUpload header", () => + CreateAttachmentUploadHeader.parse({ "Idempotency-Key": key }), + ) && + checked("createAttachmentUpload body", () => + CreateAttachmentUploadBody.parse(started), + ); + if (!input) return logged("attachment-uploads", badRequest()); + const id = `upload-${server.uploads.size + 1}`; + const partCount = Math.ceil(input.sizeBytes / PART_BYTES); + server.uploads.set(id, { + id, + name: input.name, + sizeBytes: input.sizeBytes, + partCount, + parts: new Map(), + cancelled: false, + }); + return logged( + "attachment-uploads", + json( + CreateAttachmentUploadResponse, + { + id, + partBytes: PART_BYTES, + partCount, + expiresAt: new Date(Date.now() + 86_400_000).toISOString(), + }, + 201, + ), + ); + } + + const part = path.match( + /^\/api\/v2\/organizations\/([^/]+)\/attachment-uploads\/([^/]+)\/parts\/(\d+)$/, + ); + if (part && request.method === "PUT") { + const partNumber = Number(part[3]); + const what = `parts/${partNumber}`; + const ok = + checked("uploadAttachmentPart params", () => + UploadAttachmentPartParams.parse({ + organizationId: part[1], + uploadId: part[2], + partNumber, + }), + ) && + checked("uploadAttachmentPart header", () => + UploadAttachmentPartHeader.parse({ "Idempotency-Key": key }), + ) && + request.headers.get("content-type") === "application/octet-stream"; + const bytes = await bodyOf(request); + if (!bytes) return logged(what, timedOut()); + const upload = server.uploads.get(part[2]); + if (!ok || !upload) return logged(what, badRequest()); + const expected = + partNumber < upload.partCount + ? PART_BYTES + : upload.sizeBytes - PART_BYTES * (upload.partCount - 1); + if (bytes.length !== expected) { + server.refused.push( + `part ${partNumber} was ${bytes.length} bytes, not ${expected}`, + ); + return logged(what, badRequest()); + } + if ( + server.failPartOnce === partNumber || + server.failPartAlways === partNumber + ) { + server.failPartOnce = undefined; + return logged( + what, + Response.json( + { + type: "about:blank", + title: "Unavailable.", + status: 503, + detail: "OpenBot is busy.", + }, + { + status: 503, + headers: { "content-type": "application/problem+json" }, + }, + ), + ); + } + // Answered as taken but lost, as a part can be when storage fails behind the answer. + if (server.losePartOnce === partNumber) server.losePartOnce = undefined; + else upload.parts.set(partNumber, bytes); + if (server.hold?.part === partNumber) await server.hold.until; + return logged( + what, + json( + UploadAttachmentPartResponse, + { partNumber, sizeBytes: bytes.length }, + 200, + ), + ); + } + + const complete = path.match( + /^\/api\/v2\/organizations\/([^/]+)\/attachment-uploads\/([^/]+)\/complete$/, + ); + if (complete && request.method === "POST") { + const ok = + checked("completeAttachmentUpload params", () => + CompleteAttachmentUploadParams.parse({ + organizationId: complete[1], + uploadId: complete[2], + }), + ) && + checked("completeAttachmentUpload header", () => + CompleteAttachmentUploadHeader.parse({ "Idempotency-Key": key }), + ); + const upload = server.uploads.get(complete[2]); + if (!ok || !upload) return logged("complete", badRequest()); + const missing = Array.from( + { length: upload.partCount }, + (_, index) => index + 1, + ).filter((partNumber) => !upload.parts.has(partNumber)); + if (!upload.completed && missing.length > 0) + return logged( + "complete", + Response.json( + { + type: "https://open.bot/errors/conflict", + title: "The request conflicts with the current state.", + status: 409, + detail: `Part ${missing[0]} of '${upload.name}' hasn't arrived yet. Send it, then finish the upload.`, + code: "ATTACHMENT_PARTS_MISSING", + problems: missing.map((partNumber) => ({ + partNumber, + detail: `Part ${partNumber} hasn't arrived yet.`, + })), + }, + { + status: 409, + headers: { "content-type": "application/problem+json" }, + }, + ), + ); + if (!upload.completed) { + const bytes = Buffer.concat( + Array.from( + { length: upload.partCount }, + (_, index) => upload.parts.get(index + 1) ?? Buffer.alloc(0), + ), + ); + const id = `stored-${server.stored.size + 1}`; + server.stored.set(id, { name: upload.name, bytes }); + upload.completed = { + id, + name: upload.name, + mimeType: upload.name.endsWith(".png") + ? "image/png" + : "application/pdf", + sizeBytes: bytes.length, + }; + } + return logged( + "complete", + json(CompleteAttachmentUploadResponse, upload.completed, 201), + ); + } + + const cancel = path.match( + /^\/api\/v2\/organizations\/([^/]+)\/attachment-uploads\/([^/]+)$/, + ); + if (cancel && request.method === "DELETE") { + const ok = + checked("cancelAttachmentUpload params", () => + CancelAttachmentUploadParams.parse({ + organizationId: cancel[1], + uploadId: cancel[2], + }), + ) && + checked("cancelAttachmentUpload header", () => + CancelAttachmentUploadHeader.parse({ "Idempotency-Key": key }), + ); + if (!ok) return logged("cancel", badRequest()); + const upload = server.uploads.get(cancel[2]); + if (upload) upload.cancelled = true; + return logged("cancel", new Response(null, { status: 204 })); + } + + return Response.json( + { + type: "about:blank", + title: "Not found.", + status: 404, + detail: "Not found.", + }, + { status: 404, headers: { "content-type": "application/problem+json" } }, + ); +} + +/** The fixture bundled for the browser. `@/lib/marks` is Vite's `import.meta.glob`, so no marks. */ +async function bundle(entry: string): Promise { + const built = await Bun.build({ + entrypoints: [join(import.meta.dir, entry)], + target: "browser", + define: { "process.env.NODE_ENV": JSON.stringify("production") }, + plugins: [ + { + name: "no-marks", + setup(build) { + build.onResolve({ filter: /^@\/lib\/marks$/ }, () => ({ + path: "marks", + namespace: "no-marks", + })); + build.onLoad({ filter: /.*/, namespace: "no-marks" }, () => ({ + contents: "export const markFor = () => null;", + loader: "js", + })); + }, + }, + ], + }); + if (!built.success) throw new AggregateError(built.logs, "bundle failed"); + const output = built.outputs.find((one) => one.kind === "entry-point"); + if (!output) throw new Error("bundle has no entry point"); + return output.text(); +} + +function packageDir(name: string): string { + const dir = [ + join(APP, "node_modules", name), + join(APP, "..", "node_modules", name), + ].find(existsSync); + if (!dir) throw new Error(`no package ${name}`); + return dir; +} + +function packageStylesheet(id: string): string { + const parts = id.split("/"); + const name = id.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]; + const dir = packageDir(name); + const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + const entry = pkg.exports?.[`.${id.slice(name.length)}`]; + const file = + typeof entry === "string" + ? entry + : (entry?.style ?? entry?.default ?? pkg.main ?? "index.css"); + return join(dir, file); +} + +/** The app's stylesheet, built by Tailwind for these classes, as the app's build does. */ +async function stylesheet(classes: string[]): Promise { + const tailwind = dirname(Bun.resolveSync("tailwindcss/package.json", APP)); + const entry = join(APP, "src", "styles.css"); + const compiler = await compile(readFileSync(entry, "utf8"), { + base: dirname(entry), + loadStylesheet: async (id, base) => { + const path = + id === "tailwindcss" + ? join(tailwind, "index.css") + : id.startsWith(".") + ? join(base, id) + : packageStylesheet(id); + return { path, base: dirname(path), content: readFileSync(path, "utf8") }; + }, + }); + return compiler.build(classes); +} + +const browsers = new Map(); +let script = ""; + +async function reply(request: Request): Promise { + const url = new URL(request.url); + if (url.pathname === "/composer.js") + return new Response(script, { + headers: { "content-type": "text/javascript" }, + }); + if (url.pathname.startsWith("/files/")) { + const font = join( + packageDir("@fontsource-variable/figtree"), + "files", + url.pathname.split("/").pop() ?? "", + ); + if (existsSync(font)) return new Response(Bun.file(font)); + } + if (url.pathname.startsWith("/api/")) return answer(request, url.pathname); + const theme = url.searchParams.get("theme") === "dark" ? "dark" : "light"; + return new Response( + `
`, + { headers: { "content-type": "text/html" } }, + ); +} + +beforeAll(async () => { + if (!asked) return; + server = freshServer(true); + // No idle timeout: a held part waits on the test, and a slow body is the edge's to time out. + http = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + idleTimeout: 0, + fetch: reply, + }); + port = http.port ?? 0; + script = await bundle("upload-in-parts.fixture.tsx"); + const playwright = await import("playwright-core"); + for (const engine of engines) { + const type: BrowserType = playwright[engine]; + // The CI job installs full Chromium without the headless shell. + browsers.set( + engine, + await type.launch(engine === "chromium" ? { channel: "chromium" } : {}), + ); + } +}, 120_000); + +afterAll(async () => { + for (const browser of browsers.values()) await browser.close(); + http?.stop(true); +}); + +/** The message box, once it has read how this OpenBot takes files. */ +async function open( + engine: string, + options: { + theme?: "light" | "dark"; + viewport?: { width: number; height: number }; + /** The page's timers run only when the test runs them (Playwright's clock). */ + clock?: boolean; + } = {}, +): Promise { + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const theme = options.theme ?? "light"; + const context = await browser.newContext({ + viewport: options.viewport ?? { width: 1000, height: 640 }, + colorScheme: theme, + reducedMotion: "reduce", + }); + if (options.clock) await context.clock.install(); + const page = await context.newPage(); + page.on("pageerror", (error) => console.error(error)); + await page.goto(`${origin()}/?theme=${theme}`); + await page + .locator('[data-deployment-read="yes"]') + .waitFor({ timeout: 15_000 }); + /* + * Every percentage a progress bar reaches, kept on the page as it changes, so the test can say a + * tile showed how far it had got mid-upload however quickly the upload then finished. + */ + await page.evaluate(() => { + const seen: number[] = []; + (window as unknown as { progressSeen: number[] }).progressSeen = seen; + const note = () => { + for (const bar of document.querySelectorAll( + '[role="progressbar"][aria-valuenow]', + )) + seen.push(Number(bar.getAttribute("aria-valuenow"))); + }; + new MutationObserver(note).observe(document.body, { + subtree: true, + childList: true, + attributes: true, + attributeFilter: ["aria-valuenow"], + }); + }); + return page; +} + +async function attach( + page: Page, + files: { name: string; mimeType: string; buffer: Buffer }[], +) { + await page.locator('input[type="file"]').setInputFiles(files); +} + +/** Until no tile says it is uploading, or a refusal is shown: whichever happens first. */ +async function settled(page: Page) { + await page.waitForFunction( + () => { + const text = document.body.innerText; + return ( + text.includes("couldn't be uploaded") || !text.includes("Uploading") + ); + }, + undefined, + { timeout: 110_000 }, + ); +} + +async function refusalShown(page: Page): Promise { + const text = await page.evaluate(() => document.body.innerText); + return ( + text.split("\n").find((line) => line.includes("couldn't be uploaded")) ?? + null + ); +} + +/** The percentages a progress bar showed, from its first to its last. */ +const progressSeen = (page: Page) => + page.evaluate( + () => (window as unknown as { progressSeen: number[] }).progressSeen, + ); + +/** A part held at the server until `release` is called. */ +function holdPart(part: number): () => void { + let release = () => {}; + const until = new Promise((resolve) => { + release = resolve; + }); + server.hold = { part, until }; + return () => { + server.hold = undefined; + release(); + }; +} + +const storedBytes = (name: string) => + [...server.stored.values()].find((file) => file.name === name)?.bytes; + +async function shoot(page: Page, name: string) { + if (!shots) return; + mkdirSync(shots, { recursive: true }); + const classes = await page.evaluate(() => + [...document.querySelectorAll("[class]")].flatMap((element) => [ + ...element.classList, + ]), + ); + await page.addStyleTag({ content: await stylesheet([...new Set(classes)]) }); + await still(page); + await page.screenshot({ path: join(shots, `upload-in-parts-${name}.png`) }); +} + +describe.skipIf(!asked)("a large file attaches over a slow connection", () => { + /* + * THE REPORT ITSELF. The connection is slow enough that the whole file takes several times the + * edge's limit to send, and one part well inside it. Sent in one request (OpenBot before this + * change) the edge answers 524 and the file is refused; sent in parts it arrives whole. + */ + if (engines.includes("chromium")) + test("a file too large to send in one request arrives in parts, showing its progress, in chromium", async () => { + server = freshServer(true); + const page = await open("chromium"); + try { + const cdp = await page.context().newCDPSession(page); + await cdp.send("Network.enable"); + await cdp.send("Network.emulateNetworkConditions", { + offline: false, + latency: 0, + downloadThroughput: -1, + uploadThroughput: UPLOAD_BYTES_PER_SECOND, + }); + await attach(page, [DOCUMENT]); + await settled(page); + + // The edge never had to give up on a request: every one arrived inside its limit. + expect(server.log.filter((entry) => entry.status === 524)).toEqual([]); + expect(await refusalShown(page)).toBeNull(); + expect(server.refused).toEqual([]); + // One part at a time, each once, then put together. + expect(server.log.map((entry) => entry.what)).toEqual([ + "POST attachment-uploads", + ...Array.from({ length: 9 }, (_, index) => `PUT parts/${index + 1}`), + "POST complete", + ]); + expect(storedBytes(DOCUMENT.name)?.equals(DOCUMENT.buffer)).toBe(true); + // The connection really was slow: a whole part took a good part of the edge's limit. + expect(Math.max(...server.bodyTimes)).toBeGreaterThan( + EDGE_LIMIT_MS / 6, + ); + // The tile showed how far it had got on the way, and is now the file, ready to send. + const seen = await progressSeen(page); + expect(seen.some((percent) => percent > 0 && percent < 100)).toBe(true); + await page.getByText("2.0MB").waitFor(); + } finally { + await page.context().close(); + } + }, 120_000); + + for (const engine of engines) { + test(`a tile shows the percentage that has gone while a file goes up in parts, in ${engine}`, async () => { + server = freshServer(true); + const page = await open(engine); + // The fifth part waits at the server until the tile has been seen part way. + const release = holdPart(5); + try { + await attach(page, [DOCUMENT]); + const bar = page.getByRole("progressbar", { + name: `Uploading ${DOCUMENT.name}`, + }); + await page.waitForFunction(() => { + const now = Number( + document + .querySelector('[role="progressbar"]') + ?.getAttribute("aria-valuenow") ?? 0, + ); + return now >= 40; + }); + const percent = Number(await bar.getAttribute("aria-valuenow")); + expect(percent).toBeGreaterThanOrEqual(40); + expect(percent).toBeLessThan(100); + // The line says so in words, with the number a person reads. + await page.getByText("Uploading…").waitFor(); + await page.getByText(`${percent}%`).waitFor(); + release(); + await settled(page); + expect(await refusalShown(page)).toBeNull(); + expect(await bar.count()).toBe(0); + expect(storedBytes(DOCUMENT.name)?.equals(DOCUMENT.buffer)).toBe(true); + expect(server.refused).toEqual([]); + } finally { + release(); + await page.context().close(); + } + }, 60_000); + + test(`a part the server failed is sent again by itself, and the file arrives, in ${engine}`, async () => { + server = freshServer(true); + server.failPartOnce = 3; + const page = await open(engine); + try { + await attach(page, [DOCUMENT]); + await settled(page); + expect(await refusalShown(page)).toBeNull(); + const third = server.log.filter( + (entry) => entry.what === "PUT parts/3", + ); + // Refused once, sent again with the same key, taken. + expect(third.map((entry) => entry.status)).toEqual([503, 200]); + expect(third[0]?.key).toBe(third[1]?.key ?? ""); + expect(storedBytes(DOCUMENT.name)?.equals(DOCUMENT.buffer)).toBe(true); + expect(server.refused).toEqual([]); + } finally { + await page.context().close(); + } + }, 60_000); + } + + if (engines.includes("chromium")) { + test("a part the server lost is sent again when finishing finds it missing, in chromium", async () => { + server = freshServer(true); + server.losePartOnce = 4; + const page = await open("chromium"); + try { + await attach(page, [DOCUMENT]); + await settled(page); + expect(await refusalShown(page)).toBeNull(); + const finishes = server.log.filter( + (entry) => entry.what === "POST complete", + ); + expect(finishes.map((entry) => entry.status)).toEqual([409, 201]); + // Asked again with a new key: the refusal is kept under the first. + expect(finishes[0]?.key).not.toBe(finishes[1]?.key ?? ""); + expect( + server.log.filter((entry) => entry.what === "PUT parts/4").length, + ).toBe(2); + expect(storedBytes(DOCUMENT.name)?.equals(DOCUMENT.buffer)).toBe(true); + expect(server.refused).toEqual([]); + } finally { + await page.context().close(); + } + }, 60_000); + + test("a file of 1MB or less still goes in one request, in chromium", async () => { + server = freshServer(true); + const page = await open("chromium"); + try { + await attach(page, [NOTES]); + await settled(page); + expect(await refusalShown(page)).toBeNull(); + expect(server.log.map((entry) => entry.what)).toEqual([ + "POST attachments", + ]); + expect(storedBytes(NOTES.name)?.equals(NOTES.buffer)).toBe(true); + expect(server.refused).toEqual([]); + } finally { + await page.context().close(); + } + }, 60_000); + + test("an OpenBot that doesn't offer parts gets every file in one request, in chromium", async () => { + server = freshServer(false); + const page = await open("chromium"); + try { + await attach(page, [DOCUMENT]); + await settled(page); + expect(await refusalShown(page)).toBeNull(); + expect(server.log.map((entry) => entry.what)).toEqual([ + "POST attachments", + ]); + expect(storedBytes(DOCUMENT.name)?.equals(DOCUMENT.buffer)).toBe(true); + } finally { + await page.context().close(); + } + }, 60_000); + + /* + * A part that never gets through: tried 8 times, about 1 second doubling to 30 apart, then the + * upload is stopped on the server and the file refused in words that don't ask to try again. + * The page's clock is the test's, so the waits between tries take no time. + */ + test("a part that never gets through stops the upload and says so, in chromium", async () => { + server = freshServer(true); + server.failPartAlways = 2; + const page = await open("chromium", { clock: true }); + const triesOfPart2 = () => + server.log.filter((entry) => entry.what === "PUT parts/2").length; + /* + * The page's clock, a second at a time, until the server has had the next try: the wait + * before it is drawn at random, at most 60 seconds, and the try then arrives in real time. + */ + const nextTry = async (tries: number) => { + for (let second = 0; second < 61 && triesOfPart2() < tries; second++) + await page.clock.runFor(1_000); + await serverSaw(() => triesOfPart2() >= tries); + }; + try { + await attach(page, [DOCUMENT]); + await serverSaw(() => triesOfPart2() === 1); + for (let tries = 2; tries <= 8; tries++) await nextTry(tries); + // Shown after the file's name, as every refusal on the composer is. + await page + .getByRole("alert") + .getByText( + `${DOCUMENT.name}: couldn't be uploaded. Check your connection, then attach it again.`, + ) + .waitFor(); + await serverSaw(() => + server.log.some((entry) => entry.what === "DELETE cancel"), + ); + // No ninth try, however long it is left. + await page.clock.runFor(120_000); + expect(triesOfPart2()).toBe(8); + expect(server.log.some((entry) => entry.what === "PUT parts/3")).toBe( + false, + ); + expect(server.refused).toEqual([]); + } finally { + await page.context().close(); + } + }, 60_000); + + test("a file removed while it goes up in parts stops, and nothing is said about it, in chromium", async () => { + server = freshServer(true); + const page = await open("chromium"); + const release = holdPart(2); + try { + await attach(page, [DOCUMENT]); + await page + .getByRole("progressbar", { name: `Uploading ${DOCUMENT.name}` }) + .waitFor(); + await page.waitForFunction(() => document.body.innerText.includes("%")); + await page + .getByRole("button", { name: `Remove ${DOCUMENT.name}` }) + .click(); + release(); + // The upload is stopped on the server, and no more parts go. + await serverSaw(() => + server.log.some((entry) => entry.what === "DELETE cancel"), + ); + expect(server.log.some((entry) => entry.what === "PUT parts/3")).toBe( + false, + ); + expect(server.log.some((entry) => entry.what === "POST complete")).toBe( + false, + ); + expect(await refusalShown(page)).toBeNull(); + } finally { + release(); + await page.context().close(); + } + }, 60_000); + } + + /* + * The tiles photographed mid-upload (a document and a picture, both in parts) and done, light + * and dark, wide and on a phone. + */ + for (const engine of engines) + test.skipIf(!shots)( + `the tiles mid-upload and done, in ${engine}`, + async () => { + for (const theme of ["light", "dark"] as const) + for (const [shape, viewport] of [ + ["wide", { width: 1000, height: 640 }], + ["phone", { width: 390, height: 844 }], + ] as const) { + server = freshServer(true); + let release = holdPart(5); + let releaseWhole = () => {}; + server.holdWhole = new Promise((resolve) => { + releaseWhole = resolve; + }); + const page = await open(engine, { theme, viewport }); + try { + await attach(page, [DOCUMENT, PICTURE]); + /* + * Mid-upload: the document part way, the picture waiting its turn in the line. A file + * sent in one request (an OpenBot before parts, photographed for comparison) has no bar, + * only its "Uploading…", and is held at the server instead. + */ + await page.waitForFunction(() => { + const bars = [ + ...document.querySelectorAll('[role="progressbar"]'), + ]; + return bars.length === 0 + ? document.body.innerText.includes("Uploading…") + : bars.some( + (bar) => Number(bar.getAttribute("aria-valuenow")) >= 40, + ); + }); + await shoot(page, `mid-${engine}-${theme}-${shape}`); + const inParts = (await page.getByRole("progressbar").count()) > 0; + release(); + if (inParts) { + // Then the picture, part way, with the document done beside it. + release = holdPart(3); + // Attached, not visible: its classes reach the page's stylesheet only at the next photograph. + await page + .getByRole("progressbar", { + name: `Uploading ${PICTURE.name}`, + }) + .waitFor({ state: "attached" }); + await page.waitForFunction( + (name) => + Number( + document + .querySelector( + `[role="progressbar"][aria-label="Uploading ${name}"]`, + ) + ?.getAttribute("aria-valuenow") ?? 0, + ) >= 40, + PICTURE.name, + ); + await shoot(page, `picture-${engine}-${theme}-${shape}`); + release(); + } + releaseWhole(); + await settled(page); + await page + .getByRole("button", { name: `Remove ${PICTURE.name}` }) + .waitFor(); + await shoot(page, `done-${engine}-${theme}-${shape}`); + } finally { + release(); + releaseWhole(); + await page.context().close(); + } + } + }, + 240_000, + ); +}); diff --git a/app/tests/upload-in-parts.fixture.tsx b/app/tests/upload-in-parts.fixture.tsx new file mode 100644 index 0000000000..6b536f8394 --- /dev/null +++ b/app/tests/upload-in-parts.fixture.tsx @@ -0,0 +1,69 @@ +import { CopilotKitProvider } from "@copilotkit/react-core/v2"; +import { QueryClientProvider, useQuery } from "@tanstack/react-query"; +import { createRoot } from "react-dom/client"; +import { Composer } from "@/components/channels/composer/composer"; +import { authKeys } from "@/lib/auth/queries"; +import { + attachmentLimitsQueryOptions, + deploymentKeys, + useAttachmentLimits, +} from "@/lib/deployment/queries"; +import { setCurrentOrganization } from "@/lib/organizations/current"; +import { queryClient } from "@/query-client"; + +/** + * A conversation's message box on a page of its own, for upload-in-parts-browser.test.tsx to bundle + * and load in a browser against its own server. The box uploads to the conversation `conversation-1` + * and reads how this OpenBot takes files (`useAttachmentLimits`) from that server's deployment + * answer, as a conversation's screen does. `?theme=dark` draws it dark. + */ +const params = new URLSearchParams(location.search); +if (params.get("theme") === "dark") + document.documentElement.classList.add("dark"); + +setCurrentOrganization("default"); +queryClient.setQueryData(deploymentKeys.capabilities(), { + generativeUi: true, + transcription: false, +}); +queryClient.setQueryData(authKeys.currentUser(), { + id: "u-1", + name: "Dana Reyes", + email: "dana@example.com", +}); + +function Conversation() { + const attachmentLimits = useAttachmentLimits(); + // Says when the deployment answer has been read, so the test attaches only after it. + const read = useQuery(attachmentLimitsQueryOptions()).isSuccess; + return ( +
+
+ A conversation above the box. +
+
+ {}} + /> +
+
+ ); +} + +const root = document.getElementById("root"); +if (root) { + createRoot(root).render( + + + + + , + ); +} diff --git a/bun.lock b/bun.lock index a4a8f845dc..df6c91d347 100644 --- a/bun.lock +++ b/bun.lock @@ -58,6 +58,8 @@ "lru-cache": "11.5.3", "mermaid": "12.3.0", "motion": "^13.1.0", + "p-limit": "7.3.3", + "p-retry": "9.0.0", "prompt-area": "^0.6.3", "react": "^19.2.0", "react-dom": "^19.2.0", @@ -2048,13 +2050,13 @@ "p-finally": ["p-finally@1.0.0", "", {}, "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow=="], - "p-limit": ["p-limit@2.3.0", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="], + "p-limit": ["p-limit@7.3.3", "", { "dependencies": { "yocto-queue": "^1.2.1" } }, "sha512-SKgVvDU5TNIxQ4r30U75BNLC6a+6GOEjngrk/ysM5+Zu3oJuk1SC5ApzIzY/7PjCEjoVPMWJ0zho/4QUiEB7TQ=="], "p-locate": ["p-locate@3.0.0", "", { "dependencies": { "p-limit": "^2.0.0" } }, "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ=="], "p-queue": ["p-queue@6.6.2", "", { "dependencies": { "eventemitter3": "^4.0.4", "p-timeout": "^3.2.0" } }, "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ=="], - "p-retry": ["p-retry@7.1.1", "", { "dependencies": { "is-network-error": "^1.1.0" } }, "sha512-J5ApzjyRkkf601HpEeykoiCvzHQjWxPAHhyjFcEUP2SWq0+35NKh8TLhpLw+Dkq5TZBFvUM6UigdE9hIVYTl5w=="], + "p-retry": ["p-retry@9.0.0", "", { "dependencies": { "is-network-error": "^1.3.2" } }, "sha512-HuEats8gYn/UUYa5uyveyQGv75mQmwdFtuMgnZlS12dj/7bdnJSO6keaTjgcZUhvkANTj5EO3lACUmV3xmgj0Q=="], "p-timeout": ["p-timeout@3.2.0", "", { "dependencies": { "p-finally": "^1.0.0" } }, "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg=="], @@ -2552,6 +2554,8 @@ "yauzl": ["yauzl@2.10.0", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="], + "yocto-queue": ["yocto-queue@1.2.2", "", {}, "sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ=="], + "yocto-spinner": ["yocto-spinner@1.2.2", "", { "dependencies": { "yoctocolors": "^2.1.1" } }, "sha512-DODGl1wJjA/s5pnJFKau9lIYHT81lnhob1i3e1TjxZRxEhWRKl74nTbWE6H5KlkViQQTo/Z29YFdxzTZAMY3ng=="], "yoctocolors": ["yoctocolors@2.2.0", "", {}, "sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg=="], @@ -2654,6 +2658,8 @@ "@langchain/langgraph-sdk/p-queue": ["p-queue@9.3.3", "", { "dependencies": { "eventemitter3": "^5.0.4", "p-timeout": "^7.0.0" } }, "sha512-NXAOdnEe5FsZJfT4oK84lE1Y5cFFdWlRuOo5tww8DyNMxyRXwn39fIkUtNLKppcPC+UYU/bXujNCUGDv01y7CA=="], + "@langchain/langgraph-sdk/p-retry": ["p-retry@7.1.1", "", { "dependencies": { "is-network-error": "^1.1.0" } }, "sha512-J5ApzjyRkkf601HpEeykoiCvzHQjWxPAHhyjFcEUP2SWq0+35NKh8TLhpLw+Dkq5TZBFvUM6UigdE9hIVYTl5w=="], + "@modelcontextprotocol/sdk/zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="], "@mswjs/interceptors/@open-draft/deferred-promise": ["@open-draft/deferred-promise@2.2.0", "", {}, "sha512-CecwLWx3rhxVQF6V4bAgPS5t+So2sTbPgAzafKkVizyi7tlwpcFpdFqq+wqF2OwNBmqFuu6tOyouTuxgpMfzmA=="], @@ -2942,6 +2948,8 @@ "openid-client/jose": ["jose@6.2.19", "", {}, "sha512-NnThKzdK4dJTUQOBoMB0bF3Xmw4EtbFTo4xzeLaoBwcuOdBVDQcKB3/86DUTWjVMXkZOdaqZVo2OU6DllhS+9Q=="], + "p-locate/p-limit": ["p-limit@2.3.0", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="], + "p-queue/eventemitter3": ["eventemitter3@4.0.7", "", {}, "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw=="], "parse5/entities": ["entities@6.0.1", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="], From 701f05ea69782228d49eba3150466dbb5b05f215 Mon Sep 17 00:00:00 2001 From: David McKay Date: Fri, 4 Dec 2026 13:58:25 -0800 Subject: [PATCH 3/7] Name a missing part of an upload in parts by its own code completeAttachmentUpload refuses an upload with a part missing under ATTACHMENT_PARTS_MISSING, listing each part in problems, so an app sends exactly those again without reading the sentence, and tells it apart from a full message. --- api/openapi.yaml | 18 +++++++++++-- api/openapi/conversations.yaml | 26 +++++++++++++++---- .../model/attachmentUploadConflictResponse.ts | 2 +- .../model/attachmentUploadConflictResponse.ts | 2 +- 4 files changed, 39 insertions(+), 9 deletions(-) diff --git a/api/openapi.yaml b/api/openapi.yaml index 49baed20be..67eac10bf8 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -60746,7 +60746,7 @@ components: requestId: req_example traceId: trace_example AttachmentUploadConflict: - description: 'The upload cannot take this: a part has not arrived yet, the upload is already completed, the message already holds as many files as it may, or the caller is holding too many unsent files. Or the Idempotency-Key was already used for a different request.' + description: 'The upload cannot take this: a part has not arrived yet (code ATTACHMENT_PARTS_MISSING, with each missing part in problems, as partNumber), the upload is already completed, the message already holds as many files as it may, or the caller is holding too many unsent files. Or the Idempotency-Key was already used for a different request.' headers: X-Request-Id: $ref: '#/components/headers/RequestId' @@ -60756,11 +60756,25 @@ components: $ref: '#/components/schemas/Problem' examples: missing: + value: + type: https://open.bot/errors/attachment-parts-missing + title: Some parts of the file haven't arrived. + status: 409 + detail: Part 3 of 'budget.xlsx' hasn't arrived yet. Send it, then finish the upload. + code: ATTACHMENT_PARTS_MISSING + category: conflict + retryable: false + problems: + - partNumber: 3 + detail: Part 3 hasn't arrived yet. + requestId: req_example + traceId: trace_example + full: value: type: https://open.bot/errors/conflict title: The request conflicts with the current state. status: 409 - detail: Part 3 of 'budget.xlsx' hasn't arrived yet. Send it, then finish the upload. + detail: You can attach 8 files to a message, and 8 are already waiting to send. code: CONFLICT category: conflict retryable: false diff --git a/api/openapi/conversations.yaml b/api/openapi/conversations.yaml index 0d3af36edf..c7ed809496 100644 --- a/api/openapi/conversations.yaml +++ b/api/openapi/conversations.yaml @@ -4497,10 +4497,12 @@ components: requestId: req_example traceId: trace_example AttachmentUploadConflict: - description: 'The upload cannot take this: a part has not arrived yet, the - upload is already completed, the message already holds as many files as - it may, or the caller is holding too many unsent files. Or the - Idempotency-Key was already used for a different request.' + description: 'The upload cannot take this: a part has not arrived yet + (code ATTACHMENT_PARTS_MISSING, with each missing part in problems, as + partNumber), the upload is already completed, the message already holds + as many files as it may, or the caller is holding too many unsent + files. Or the Idempotency-Key was already used for a different + request.' headers: X-Request-Id: $ref: './common.yaml#/components/headers/RequestId' @@ -4510,11 +4512,25 @@ components: $ref: './common.yaml#/components/schemas/Problem' examples: missing: + value: + type: https://open.bot/errors/attachment-parts-missing + title: Some parts of the file haven't arrived. + status: 409 + detail: Part 3 of 'budget.xlsx' hasn't arrived yet. Send it, then finish the upload. + code: ATTACHMENT_PARTS_MISSING + category: conflict + retryable: false + problems: + - partNumber: 3 + detail: Part 3 hasn't arrived yet. + requestId: req_example + traceId: trace_example + full: value: type: https://open.bot/errors/conflict title: The request conflicts with the current state. status: 409 - detail: Part 3 of 'budget.xlsx' hasn't arrived yet. Send it, then finish the upload. + detail: You can attach 8 files to a message, and 8 are already waiting to send. code: CONFLICT category: conflict retryable: false diff --git a/app/src/lib/api/generated/model/attachmentUploadConflictResponse.ts b/app/src/lib/api/generated/model/attachmentUploadConflictResponse.ts index 571e9060b8..b156b234da 100644 --- a/app/src/lib/api/generated/model/attachmentUploadConflictResponse.ts +++ b/app/src/lib/api/generated/model/attachmentUploadConflictResponse.ts @@ -4,6 +4,6 @@ import type { Problem } from "./problem"; /** - * The upload cannot take this: a part has not arrived yet, the upload is already completed, the message already holds as many files as it may, or the caller is holding too many unsent files. Or the Idempotency-Key was already used for a different request. + * The upload cannot take this: a part has not arrived yet (code ATTACHMENT_PARTS_MISSING, with each missing part in problems, as partNumber), the upload is already completed, the message already holds as many files as it may, or the caller is holding too many unsent files. Or the Idempotency-Key was already used for a different request. */ export type AttachmentUploadConflictResponse = Problem; diff --git a/mobile/src/api/generated/model/attachmentUploadConflictResponse.ts b/mobile/src/api/generated/model/attachmentUploadConflictResponse.ts index 571e9060b8..b156b234da 100644 --- a/mobile/src/api/generated/model/attachmentUploadConflictResponse.ts +++ b/mobile/src/api/generated/model/attachmentUploadConflictResponse.ts @@ -4,6 +4,6 @@ import type { Problem } from "./problem"; /** - * The upload cannot take this: a part has not arrived yet, the upload is already completed, the message already holds as many files as it may, or the caller is holding too many unsent files. Or the Idempotency-Key was already used for a different request. + * The upload cannot take this: a part has not arrived yet (code ATTACHMENT_PARTS_MISSING, with each missing part in problems, as partNumber), the upload is already completed, the message already holds as many files as it may, or the caller is holding too many unsent files. Or the Idempotency-Key was already used for a different request. */ export type AttachmentUploadConflictResponse = Problem; From a93fe0447d0e62365b649834439bc6d924dcd5a7 Mon Sep 17 00:00:00 2001 From: David McKay Date: Fri, 4 Dec 2026 14:23:03 -0800 Subject: [PATCH 4/7] Decide whether a file goes in parts when it is sent, from the deployment answer A file picked the moment the message box appeared, before the page had read the deployment answer, went in one request for good: whether to send it in parts was read from what the screen drew, and that reads as no until the answer arrives. On a slow connection that is exactly when the answer takes longest, so every try of the file was cut off at the edge and it was refused. Found on the real stack at phone width. The upload now asks for the deployment answer itself when it sends a file larger than one part: the one already held, or the one on its way. Only a deployment that can't be read sends the file in one request. The conversation composer, the new-conversation screen and the held files of a first message all go through it, so nothing passes the flag around any more. upload-in-parts-browser.test.tsx holds the deployment answer until the file is picked: before this, the file went as one POST .../attachments; now it goes in parts, in Chromium and WebKit. --- .../channels/composer/attachments.ts | 15 +-- .../components/channels/composer/composer.tsx | 4 - app/src/lib/channels/start.ts | 10 +- app/src/lib/channels/upload.ts | 32 ++++++- app/src/lib/deployment/queries.ts | 6 +- app/tests/upload-in-parts-browser.test.tsx | 91 +++++++++++++++---- 6 files changed, 107 insertions(+), 51 deletions(-) diff --git a/app/src/components/channels/composer/attachments.ts b/app/src/components/channels/composer/attachments.ts index ca90f31192..602e7738d0 100644 --- a/app/src/components/channels/composer/attachments.ts +++ b/app/src/components/channels/composer/attachments.ts @@ -41,8 +41,9 @@ type UploadedAttachment = { * The SDK's `onUpload`, scoped to one channel. * * The file goes through `uploadAttachment` (`lib/channels/upload.ts`): in parts where this OpenBot - * takes them (`inParts`, the deployment's `attachmentUploadsInParts`) and the file is larger than - * one part, so a slow connection can still send it; in one request otherwise. Each request is tried + * takes them (the deployment's `attachmentUploadsInParts`, read when the file is sent) and the file + * is larger than one part, so a slow connection can still send it; in one request otherwise. Each + * request is tried * again by itself while its failure may pass, so nobody is asked to try again. * * Supplying this is what keeps the bytes out of browser state: with `onUpload` set, the SDK never @@ -54,7 +55,6 @@ type UploadedAttachment = { export function uploadToChannel( channelId: string, uploadGroup: string, - inParts = false, ): (file: File) => Promise { return async (file: File): Promise => { // Named after the file rather than left empty, for every way this can go wrong. It is the only @@ -70,7 +70,6 @@ export function uploadToChannel( channelId, file, uploadGroup, - inParts, // What is said when the server sent no sentence of its own, a proxy's error page included. fallback: couldNotUpload.message, }); @@ -238,10 +237,8 @@ export function attachmentsConfigFor( * gone. See {@link previewUrlOf}. */ onPreview: (previewUrl: string) => void = () => {}, - /** Whether this OpenBot takes a large file in parts (the deployment's `attachmentUploadsInParts`). */ - inParts = false, ): AttachmentsConfig { - const upload = uploadToChannel(channelId, uploadGroup, inParts); + const upload = uploadToChannel(channelId, uploadGroup); return { enabled: true, accept: "*/*", @@ -406,11 +403,9 @@ export function heldFileOf( export async function uploadHeldFiles( channelId: string, attachments: readonly Attachment[], - /** Whether this OpenBot takes a large file in parts (the deployment's `attachmentUploadsInParts`). */ - inParts = false, ): Promise { // One group for one message: the set the server's per-message cap counts. - const upload = uploadToChannel(channelId, newId(), inParts); + const upload = uploadToChannel(channelId, newId()); const created: string[] = []; const settled = await Promise.allSettled( attachments.map(async (attachment): Promise => { diff --git a/app/src/components/channels/composer/composer.tsx b/app/src/components/channels/composer/composer.tsx index 2b99776953..e9a81b628e 100644 --- a/app/src/components/channels/composer/composer.tsx +++ b/app/src/components/channels/composer/composer.tsx @@ -560,8 +560,6 @@ export function Composer({ * would never arrive. Every upload refusal in the app comes through here. */ const limits = attachmentLimits?.limits ?? DEFAULT_ATTACHMENT_LIMITS; - // Whether this OpenBot takes a large file in parts, so a slow connection can still send it. - const inParts = attachmentLimits?.inParts === true; // Whether the Bot can read a large text file to its end: then nothing on the tile warns it is cut. const readsWhole = attachmentLimits?.readsWhole === true; /* @@ -673,7 +671,6 @@ export function Composer({ recordUpload, limits, recordHeld, - inParts, ) : holdsFilesUntilSent ? heldAttachmentsConfig(recordRejection, recordHeld, limits) @@ -686,7 +683,6 @@ export function Composer({ recordUpload, recordHeld, limits, - inParts, ], ); diff --git a/app/src/lib/channels/start.ts b/app/src/lib/channels/start.ts index e7ee1e223c..412b83de03 100644 --- a/app/src/lib/channels/start.ts +++ b/app/src/lib/channels/start.ts @@ -10,7 +10,6 @@ import { forgetSavedDraft } from "@/components/channels/composer/saved-draft"; import { stashFirstMessage } from "@/components/channels/transcript-messages"; import { newConversationBot } from "@/lib/agents/default-agent"; import type { AgentProfile } from "@/lib/agents/queries"; -import { attachmentLimitsQueryOptions } from "@/lib/deployment/queries"; import { createGroupMutationOptions, groupQueryOptions, @@ -208,14 +207,7 @@ export function useStartChannel( ...(files.length > 0 ? { upload: async (channelId: string) => { - attachments = await uploadHeldFiles( - channelId, - files, - // As the screen's composer read it (`useAttachmentLimits`): in parts where offered. - queryClient.getQueryData( - attachmentLimitsQueryOptions().queryKey, - )?.inParts === true, - ); + attachments = await uploadHeldFiles(channelId, files); }, } : {}), diff --git a/app/src/lib/channels/upload.ts b/app/src/lib/channels/upload.ts index 0a4d2fb948..f144091eff 100644 --- a/app/src/lib/channels/upload.ts +++ b/app/src/lib/channels/upload.ts @@ -10,6 +10,8 @@ import { import type { Attachment } from "@/lib/api/generated/model"; import { idempotencyKey, organizationId } from "@/lib/api/request"; import { ClientError } from "@/lib/client"; +import { attachmentLimitsQueryOptions } from "@/lib/deployment/queries"; +import { queryClient } from "@/query-client"; import { trackUpload } from "./upload-progress"; /** @@ -183,12 +185,33 @@ export type UploadInput = { file: File; /** Names the message being written, so the server counts the files of one composer. */ uploadGroup?: string; - /** Whether this OpenBot takes a file in parts (the deployment's `attachmentUploadsInParts`). */ - inParts: boolean; /** What a person reads when OpenBot refused without saying why. */ fallback: string; }; +/** + * WHETHER THIS OPENBOT TAKES A FILE IN PARTS (the deployment's `attachmentUploadsInParts`), ASKED + * WHEN THE FILE IS SENT. + * + * Not a value a screen read while it drew: until the deployment answer arrives that reads as no, + * and a file picked the moment the message box appeared (on a slow connection, the moment that + * answer takes longest) went in one request for good, every try of it cut off. So the upload waits + * for the answer itself: the one already held, or the one on its way. Only when the deployment + * can't be read does a file go in one request, which every OpenBot takes. + */ +async function partsOffered(): Promise { + try { + // Asked once: a file waits on this answer, and one that can't be had means one request. + const reading = await queryClient.ensureQueryData({ + ...attachmentLimitsQueryOptions(), + retry: false, + }); + return reading.inParts === true; + } catch { + return false; + } +} + /** * Send one file to a conversation, held for the next message, and answer what OpenBot stored. * @@ -201,10 +224,9 @@ export async function uploadAttachment({ channelId, file, uploadGroup, - inParts, fallback, }: UploadInput): Promise { - if (!inParts || file.size <= PARTS_ABOVE_BYTES) { + if (file.size <= PARTS_ABOVE_BYTES || !(await partsOffered())) { // One key for every try, so OpenBot recognises a try whose answer was lost as the same upload. const key = idempotencyKey(); return sendRetrying(() => @@ -237,7 +259,7 @@ async function uploadInParts({ uploadGroup, fallback, progress, -}: Omit & { +}: UploadInput & { progress: ReturnType; }): Promise { const { signal } = progress; diff --git a/app/src/lib/deployment/queries.ts b/app/src/lib/deployment/queries.ts index 20da3b0f29..672b258f08 100644 --- a/app/src/lib/deployment/queries.ts +++ b/app/src/lib/deployment/queries.ts @@ -324,8 +324,9 @@ export type AttachmentReading = { readsWhole: boolean; /** * Whether a large file can be sent in parts (`attachmentUploadsInParts`), so a slow connection can - * still attach it. Read with the limits because it too changes when the server is upgraded. - * Absent is no: an older server takes each file in one request. + * still attach it. Read with the limits because it too changes when the server is upgraded, and + * asked when a file is sent (`uploadAttachment` in lib/channels/upload.ts), never from what a + * screen drew before the answer came. Absent is no: an older server takes each file in one request. */ inParts?: boolean; }; @@ -348,7 +349,6 @@ export function useAttachmentLimits(): ComposerAttachmentLimits { () => ({ limits: query.data?.limits ?? DEFAULT_ATTACHMENT_LIMITS, readsWhole: query.data?.readsWhole ?? false, - inParts: query.data?.inParts ?? false, refresh: () => void refetch(), }), [query.data, refetch], diff --git a/app/tests/upload-in-parts-browser.test.tsx b/app/tests/upload-in-parts-browser.test.tsx index f273cc9f35..7a512d4d97 100644 --- a/app/tests/upload-in-parts-browser.test.tsx +++ b/app/tests/upload-in-parts-browser.test.tsx @@ -165,6 +165,10 @@ type Server = { hold?: { part: number; until: Promise }; /** Holds the one-request upload too, for the photographs of the tile before this change. */ holdWhole?: Promise; + /** A one-request upload has arrived and is being held. */ + wholeHeld?: boolean; + /** Holds the deployment answer, as a slow connection does on a page that has just opened. */ + holdDeployment?: Promise; /** How long each part's body took to arrive, in milliseconds. */ bodyTimes: number[]; }; @@ -174,6 +178,15 @@ let server: Server; /** What the test is waiting for the server to have been asked. */ let waiters: { check: () => boolean; resolve: () => void }[] = []; +/** Ask every waiter again: the server's state just changed. */ +function wake() { + waiters = waiters.filter((waiter) => { + if (!waiter.check()) return true; + waiter.resolve(); + return false; + }); +} + /** Once the server's log says `check`: woken by each request it answers, never by a clock. */ function serverSaw(check: () => boolean): Promise { if (check()) return Promise.resolve(); @@ -241,11 +254,7 @@ async function answer(request: Request, path: string): Promise { key, status: response.status, }); - waiters = waiters.filter((waiter) => { - if (!waiter.check()) return true; - waiter.resolve(); - return false; - }); + wake(); return response; }; const json = ( @@ -255,6 +264,7 @@ async function answer(request: Request, path: string): Promise { ) => Response.json(schema.parse(body), { status }); if (path === `${ORGANIZATION}/deployment`) { + await server.holdDeployment; const body = GetDeploymentResponse.parse({ ...getGetDeploymentResponseMock(), edition: "team", @@ -296,7 +306,11 @@ async function answer(request: Request, path: string): Promise { })(); if (!form) return logged("attachments", timedOut()); if (!ok) return logged("attachments", badRequest()); - await server.holdWhole; + if (server.holdWhole) { + server.wholeHeld = true; + wake(); + await server.holdWhole; + } const file = form.get("file") as File; const id = `stored-${server.stored.size + 1}`; server.stored.set(id, { @@ -655,6 +669,8 @@ async function open( viewport?: { width: number; height: number }; /** The page's timers run only when the test runs them (Playwright's clock). */ clock?: boolean; + /** `false`: don't wait for the page to have read the deployment answer. */ + deploymentRead?: boolean; } = {}, ): Promise { const browser = browsers.get(engine); @@ -669,9 +685,11 @@ async function open( const page = await context.newPage(); page.on("pageerror", (error) => console.error(error)); await page.goto(`${origin()}/?theme=${theme}`); - await page - .locator('[data-deployment-read="yes"]') - .waitFor({ timeout: 15_000 }); + if (options.deploymentRead !== false) + await page + .locator('[data-deployment-read="yes"]') + .waitFor({ timeout: 15_000 }); + else await page.locator('input[type="file"]').waitFor({ state: "attached" }); /* * Every percentage a progress bar reaches, kept on the page as it changes, so the test can say a * tile showed how far it had got mid-upload however quickly the upload then finished. @@ -842,6 +860,37 @@ describe.skipIf(!asked)("a large file attaches over a slow connection", () => { } }, 60_000); + /* + * Found on the real stack, on a phone: a file picked the moment the box appeared, before the + * page had read the deployment answer, went in one request for good, and every try of it was + * cut off. How a file goes is decided when it is sent, from the deployment answer itself. + */ + test(`a file picked before the page has read how OpenBot takes files still goes in parts, in ${engine}`, async () => { + server = freshServer(true); + let answerDeployment = () => {}; + server.holdDeployment = new Promise((resolve) => { + answerDeployment = resolve; + }); + const page = await open(engine, { deploymentRead: false }); + try { + await attach(page, [DOCUMENT]); + await page.getByText("Uploading…").waitFor(); + answerDeployment(); + await settled(page); + expect(server.log.map((entry) => entry.what)).toEqual([ + "POST attachment-uploads", + ...Array.from({ length: 9 }, (_, index) => `PUT parts/${index + 1}`), + "POST complete", + ]); + expect(await refusalShown(page)).toBeNull(); + expect(storedBytes(DOCUMENT.name)?.equals(DOCUMENT.buffer)).toBe(true); + expect(server.refused).toEqual([]); + } finally { + answerDeployment(); + await page.context().close(); + } + }, 60_000); + test(`a part the server failed is sent again by itself, and the file arrives, in ${engine}`, async () => { server = freshServer(true); server.failPartOnce = 3; @@ -1027,18 +1076,20 @@ describe.skipIf(!asked)("a large file attaches over a slow connection", () => { * sent in one request (an OpenBot before parts, photographed for comparison) has no bar, * only its "Uploading…", and is held at the server instead. */ - await page.waitForFunction(() => { - const bars = [ - ...document.querySelectorAll('[role="progressbar"]'), - ]; - return bars.length === 0 - ? document.body.innerText.includes("Uploading…") - : bars.some( - (bar) => Number(bar.getAttribute("aria-valuenow")) >= 40, - ); - }); + await serverSaw( + () => + server.wholeHeld === true || + server.log.some((entry) => entry.what === "PUT parts/4"), + ); + const inParts = server.wholeHeld !== true; + if (inParts) + await page.waitForFunction(() => + [...document.querySelectorAll('[role="progressbar"]')].some( + (bar) => Number(bar.getAttribute("aria-valuenow")) >= 40, + ), + ); + else await page.getByText("Uploading…").first().waitFor(); await shoot(page, `mid-${engine}-${theme}-${shape}`); - const inParts = (await page.getByRole("progressbar").count()) > 0; release(); if (inParts) { // Then the picture, part way, with the document done beside it. From 68b1edd132e17e61e6ecd215808d064c728f3912 Mon Sep 17 00:00:00 2001 From: David McKay Date: Fri, 4 Dec 2026 14:51:08 -0800 Subject: [PATCH 5/7] Screen a picked file against the server's limits, not the defaults standing in A 10MB PDF picked right after the page loaded was refused with "is too large for a PDF. The limit is 8MB." on an OpenBot that takes 100MB. The message box screens a pick against the limits it was drawn with, and until the deployment answer arrives those are the smallest any OpenBot takes. It is the same race as choosing parts from a value the screen read too early. Now a pick made while that answer is on its way, holding a file a stand-in limit would refuse on size, waits for the answer (attachmentLimitsNow: the one held or the one on its way, asked once, the defaults only if it can't be read) and is screened against it. A pick within every stand-in limit is screened at once, as before, so its tile shows without waiting. Gestures are screened in turn, each counting its files before the next is screened, so two picks in one tick still can't pass the per-message cap. The SDK's own size backstop reads the same limits when it checks a pick, so it can't refuse what the screen passed before the render that brings the answer. The conversation box, /channel/new and Home all screen through this. upload-in-parts-browser.test.tsx holds the deployment answer and picks a 10MB PDF: before, it was refused at 8MB; now it uploads, in Chromium and WebKit. composer-upload-group.test.tsx stages two batches in one tick while the limits load and still stages exactly the cap. --- .../channels/composer/attachments.ts | 23 +++- .../components/channels/composer/composer.tsx | 109 +++++++++++++----- app/src/lib/channels/upload.ts | 14 +-- .../lib/deployment/attachment-limits-now.ts | 31 +++++ app/src/lib/deployment/queries.ts | 12 +- app/tests/composer-upload-group.test.tsx | 79 ++++++++++++- app/tests/upload-in-parts-browser.test.tsx | 76 +++++++++--- 7 files changed, 277 insertions(+), 67 deletions(-) create mode 100644 app/src/lib/deployment/attachment-limits-now.ts diff --git a/app/src/components/channels/composer/attachments.ts b/app/src/components/channels/composer/attachments.ts index 602e7738d0..b208637111 100644 --- a/app/src/components/channels/composer/attachments.ts +++ b/app/src/components/channels/composer/attachments.ts @@ -230,8 +230,12 @@ export function attachmentsConfigFor( * about. Reporting the row and reconciling afterwards needs no such correlation. */ onUploaded: (attachmentId: string) => void, - /** The limits `screenPickedFiles` screened against, so the two agree. */ - limits: AttachmentLimits, + /** + * The limits `screenPickedFiles` screened against, so the two agree: as they are, or read each + * time a pick reaches the SDK (the composer's, which can change between renders; see + * `screeningLimits` in `composer.tsx`). + */ + limits: AttachmentLimits | (() => AttachmentLimits), /** * Each object URL made for a picture's chip, so the composer can revoke it once the chip has * gone. See {@link previewUrlOf}. @@ -239,10 +243,14 @@ export function attachmentsConfigFor( onPreview: (previewUrl: string) => void = () => {}, ): AttachmentsConfig { const upload = uploadToChannel(channelId, uploadGroup); + const limitsNow = typeof limits === "function" ? limits : () => limits; return { enabled: true, accept: "*/*", - maxSize: largestAttachmentBytes(limits), + // Read when the SDK checks a pick, not when this was made: see `limits`. + get maxSize() { + return largestAttachmentBytes(limitsNow()); + }, onUpload: async (file) => { /* * A file a saved draft is putting back was uploaded before, so it is not uploaded again: the @@ -310,13 +318,16 @@ export function attachmentsConfigFor( export function heldAttachmentsConfig( onUploadFailed: (error: AttachmentUploadError) => void, onHeld: (previewUrl: string) => void, - /** The limits `screenPickedFiles` screened against, so the two agree. */ - limits: AttachmentLimits, + /** The limits `screenPickedFiles` screened against, so the two agree; see `attachmentsConfigFor`. */ + limits: AttachmentLimits | (() => AttachmentLimits), ): AttachmentsConfig { + const limitsNow = typeof limits === "function" ? limits : () => limits; return { enabled: true, accept: "*/*", - maxSize: largestAttachmentBytes(limits), + get maxSize() { + return largestAttachmentBytes(limitsNow()); + }, onUpload: async (file) => { const previewUrl = URL.createObjectURL(file); onHeld(previewUrl); diff --git a/app/src/components/channels/composer/composer.tsx b/app/src/components/channels/composer/composer.tsx index e9a81b628e..f289a8a721 100644 --- a/app/src/components/channels/composer/composer.tsx +++ b/app/src/components/channels/composer/composer.tsx @@ -42,6 +42,7 @@ import { shouldClaimPaste, } from "@/lib/channels/attachments"; import { cancelUpload, wasCancelled } from "@/lib/channels/upload-progress"; +import { attachmentLimitsNow } from "@/lib/deployment/attachment-limits-now"; import type { ComposerAttachmentLimits } from "@/lib/deployment/queries"; import { newId } from "@/lib/new-id"; import { stopIfNeedsCard } from "@/lib/plan/queries"; @@ -560,6 +561,19 @@ export function Composer({ * would never arrive. Every upload refusal in the app comes through here. */ const limits = attachmentLimits?.limits ?? DEFAULT_ATTACHMENT_LIMITS; + /* + * THE LIMITS A PICK IS SCREENED AGAINST, AND THE SDK'S OWN `maxSize` WITH THEM: what this render + * was given, except while the deployment answer is still on its way (`pending`), when those are + * only the defaults standing in. Then a pick waits for the answer (`stageFiles`) and puts it here, + * and the SDK's backstop reads it here too, so a file the screen passed isn't refused by the SDK + * before the render that brings the answer has happened. + */ + const limitsPending = useRef(false); + limitsPending.current = attachmentLimits?.pending === true; + const screeningLimits = useRef(limits); + if (!limitsPending.current) screeningLimits.current = limits; + /** The gesture being screened, which the next one waits for (`stageFiles`). */ + const screening = useRef>(Promise.resolve()); // Whether the Bot can read a large text file to its end: then nothing on the tile warns it is cut. const readsWhole = attachmentLimits?.readsWhole === true; /* @@ -669,11 +683,15 @@ export function Composer({ uploadGroup, recordRejection, recordUpload, - limits, + () => screeningLimits.current, recordHeld, ) : holdsFilesUntilSent - ? heldAttachmentsConfig(recordRejection, recordHeld, limits) + ? heldAttachmentsConfig( + recordRejection, + recordHeld, + () => screeningLimits.current, + ) : undefined, [ channelId, @@ -682,7 +700,6 @@ export function Composer({ recordRejection, recordUpload, recordHeld, - limits, ], ); @@ -970,40 +987,70 @@ export function Composer({ if (disabled) { return; } - const screened = screenPickedFiles(picked, { - // What is on the composer, not what the hook is holding: an attachment riding on a send - // in flight belongs to that message's count, not to the one being built now. - // - // WHICH IS TRUE OF A SEND THAT LANDS AND NOT OF ONE THAT FAILS, and this number cannot - // tell them apart at the moment it is read — the send is still out. A failure hands the - // riding files back onto a strip that has filled up behind them, and the draft is then - // over the cap however carefully this counted. `tooManyStaged` is what catches that, - // because it asks about the strip as it actually is rather than predicting it. - // - // PLUS WHAT IS PARKED, which is on nobody's strip and is still counted by the server — - // see `queuedAttachmentCount`. Without the second half the client accepts a pick the - // server then refuses with a 409 the person was given no chance to avoid. - alreadyStaged: stagedCount.current + queuedAttachmentCount, - limits, - }); - if (screened.rejected.length > 0) { - setRejected((current) => [...current, ...screened.rejected]); - refreshLimits.current?.(); - } - if (screened.accepted.length === 0) { + /* + * EACH GESTURE IS SCREENED IN TURN, AFTER THE ONE BEFORE IT HAS COUNTED ITS FILES. + * + * A pick made while the deployment answer is still on its way, holding a file the defaults + * standing in for it might refuse on size, waits for the answer, so it is screened against + * this OpenBot's limits (a 10MB PDF was refused at 8MB on an OpenBot that takes 100MB). A + * pick within every one of the stand-in limits is screened at once, as it always was, so its + * tile shows without waiting. Waiting would let a second gesture screen against a count that doesn't yet hold + * the first one's files, so the gestures queue: each screens, and bumps the counts, only + * once the one before it has. + */ + const turn = screening.current.then( + async (): Promise => { + const smallest = Math.min(...Object.values(screeningLimits.current)); + if ( + limitsPending.current && + picked.some((file) => file.size > smallest) + ) + screeningLimits.current = (await attachmentLimitsNow()).limits; + const screened = screenPickedFiles(picked, { + // What is on the composer, not what the hook is holding: an attachment riding on a + // send in flight belongs to that message's count, not to the one being built now. + // + // WHICH IS TRUE OF A SEND THAT LANDS AND NOT OF ONE THAT FAILS, and this number cannot + // tell them apart at the moment it is read — the send is still out. A failure hands + // the riding files back onto a strip that has filled up behind them, and the draft is + // then over the cap however carefully this counted. `tooManyStaged` is what catches + // that, because it asks about the strip as it actually is rather than predicting it. + // + // PLUS WHAT IS PARKED, which is on nobody's strip and is still counted by the server — + // see `queuedAttachmentCount`. Without the second half the client accepts a pick the + // server then refuses with a 409 the person was given no chance to avoid. + alreadyStaged: stagedCount.current + queuedAttachmentCount, + limits: screeningLimits.current, + }); + if (screened.rejected.length > 0) { + setRejected((current) => [...current, ...screened.rejected]); + refreshLimits.current?.(); + } + if (screened.accepted.length === 0) { + return undefined; + } + // Both bumps happen before this turn ends, so the next gesture's turn screens against a + // number that already includes these. + stagedCount.current += screened.accepted.length; + staging.current += screened.accepted.length; + return screened.accepted; + }, + ); + screening.current = turn.then( + () => undefined, + () => undefined, + ); + const accepted = await turn; + if (!accepted) { return; } - // Both bumps happen BEFORE the await, so a second gesture in this same tick screens against - // a number that already includes these. - stagedCount.current += screened.accepted.length; - staging.current += screened.accepted.length; try { - await processNoted(screened.accepted.map(withMediaTypeOnly)); + await processNoted(accepted.map(withMediaTypeOnly)); } finally { - staging.current -= screened.accepted.length; + staging.current -= accepted.length; } }, - [disabled, processNoted, queuedAttachmentCount, limits], + [disabled, processNoted, queuedAttachmentCount], ); /** `initialFiles` has been put back once, and is not owed again for the life of this composer. */ diff --git a/app/src/lib/channels/upload.ts b/app/src/lib/channels/upload.ts index f144091eff..d108957b14 100644 --- a/app/src/lib/channels/upload.ts +++ b/app/src/lib/channels/upload.ts @@ -10,8 +10,7 @@ import { import type { Attachment } from "@/lib/api/generated/model"; import { idempotencyKey, organizationId } from "@/lib/api/request"; import { ClientError } from "@/lib/client"; -import { attachmentLimitsQueryOptions } from "@/lib/deployment/queries"; -import { queryClient } from "@/query-client"; +import { attachmentLimitsNow } from "@/lib/deployment/attachment-limits-now"; import { trackUpload } from "./upload-progress"; /** @@ -200,16 +199,7 @@ export type UploadInput = { * can't be read does a file go in one request, which every OpenBot takes. */ async function partsOffered(): Promise { - try { - // Asked once: a file waits on this answer, and one that can't be had means one request. - const reading = await queryClient.ensureQueryData({ - ...attachmentLimitsQueryOptions(), - retry: false, - }); - return reading.inParts === true; - } catch { - return false; - } + return (await attachmentLimitsNow()).inParts === true; } /** diff --git a/app/src/lib/deployment/attachment-limits-now.ts b/app/src/lib/deployment/attachment-limits-now.ts new file mode 100644 index 0000000000..a7283bf9ab --- /dev/null +++ b/app/src/lib/deployment/attachment-limits-now.ts @@ -0,0 +1,31 @@ +import { DEFAULT_ATTACHMENT_LIMITS } from "@/lib/channels/attachments"; +import { queryClient } from "@/query-client"; +import { + type AttachmentReading, + attachmentLimitsQueryOptions, +} from "./queries"; + +/** + * WHAT THIS OPENBOT SAYS ABOUT ATTACHED FILES, ONCE IT HAS SAID IT: for a decision about a file that + * can't be taken back, made the moment the file is picked or sent. + * + * A screen draws with `useAttachmentLimits`, which reads as the smallest limits any OpenBot takes, + * and as no parts, until the deployment answer arrives. On a slow connection that answer takes + * longest exactly when somebody picks a file as soon as the message box appears, and a decision + * made from what was drawn then sticks: a 10MB PDF refused at 8MB on an OpenBot that takes 100MB, a + * large file sent in one request that the edge cuts off. So this waits for the answer itself: the + * one already held, or the one on its way. + * + * Asked once, with none of the query client's retries: a file is waiting on it. When the deployment + * can't be read, the defaults, which every OpenBot takes. + */ +export async function attachmentLimitsNow(): Promise { + try { + return await queryClient.ensureQueryData({ + ...attachmentLimitsQueryOptions(), + retry: false, + }); + } catch { + return { limits: DEFAULT_ATTACHMENT_LIMITS, readsWhole: false }; + } +} diff --git a/app/src/lib/deployment/queries.ts b/app/src/lib/deployment/queries.ts index 672b258f08..549649e2a4 100644 --- a/app/src/lib/deployment/queries.ts +++ b/app/src/lib/deployment/queries.ts @@ -335,12 +335,19 @@ export type AttachmentReading = { export type ComposerAttachmentLimits = AttachmentReading & { /** Read the limits again, as after a refusal: the refusal may be the first sign they changed. */ refresh: () => void; + /** + * True while the deployment answer is still on its way, so `limits` are only the defaults standing + * in for it: a pick is then screened once the answer is in (`attachmentLimitsNow`), never against + * these. Absent is false: limits given outright are the ones to screen with. + */ + pending?: boolean; }; /** * {@link attachmentLimitsQueryOptions} for a screen with a composer: the server's limits, and the * defaults while they load or when they could not be read. The defaults are the safe side, the - * smallest any server takes. + * smallest any server takes, for drawing; a pick made while they load waits for the answer + * (`pending`). */ export function useAttachmentLimits(): ComposerAttachmentLimits { const query = useQuery(attachmentLimitsQueryOptions()); @@ -350,8 +357,9 @@ export function useAttachmentLimits(): ComposerAttachmentLimits { limits: query.data?.limits ?? DEFAULT_ATTACHMENT_LIMITS, readsWhole: query.data?.readsWhole ?? false, refresh: () => void refetch(), + pending: query.isPending, }), - [query.data, refetch], + [query.data, query.isPending, refetch], ); } diff --git a/app/tests/composer-upload-group.test.tsx b/app/tests/composer-upload-group.test.tsx index dad08a2ed1..191faeaea4 100644 --- a/app/tests/composer-upload-group.test.tsx +++ b/app/tests/composer-upload-group.test.tsx @@ -9,7 +9,12 @@ import { import { GlobalRegistrator } from "@happy-dom/global-registrator"; import { cleanup, fireEvent, render, waitFor } from "@testing-library/react"; import { Composer } from "@/components/channels/composer/composer"; -import { MAX_ATTACHMENTS_PER_MESSAGE } from "@/lib/channels/attachments"; +import { + DEFAULT_ATTACHMENT_LIMITS, + MAX_ATTACHMENTS_PER_MESSAGE, +} from "@/lib/channels/attachments"; +import { deploymentKeys } from "@/lib/deployment/queries"; +import { queryClient } from "@/query-client"; import { settleReactWork } from "./settle-react-work"; /** @@ -121,6 +126,78 @@ test("two batches staged in one tick cannot exceed the per-message cap", async ( ).toHaveLength(2); }); +/** + * THE SAME TWO GESTURES WHILE THE DEPLOYMENT ANSWER IS STILL ON ITS WAY. + * + * Files larger than a limit the stand-in defaults hold wait for the answer before they are + * screened, so they are screened against this OpenBot's limits and not refused at the defaults' 1MB. + * The wait must not let the second gesture screen against a count without the first one's files: + * each gesture screens in turn, so five and five still stage eight. + */ +test("two batches staged in one tick while the limits load cannot exceed the cap either", async () => { + const MIB = 1024 * 1024; + global.fetch = (async (path: string, init: RequestInit) => { + if (path.endsWith("/deployment")) + return Response.json({ + attachmentLimits: { + imageBytes: 100 * MIB, + documentBytes: 100 * MIB, + fileBytes: 100 * MIB, + }, + }); + const body = init.body as FormData; + const file = body.get("file") as File; + groups.push(String(body.get("uploadGroup"))); + return Response.json( + { + id: `stored-${groups.length}`, + name: file.name, + mimeType: "text/plain", + }, + { status: 201 }, + ); + }) as unknown as typeof fetch; + /** Text over the defaults' 1MB, which the server here takes. */ + const large = (prefix: string) => + textFiles(prefix, 5).map((file) => { + Object.defineProperty(file, "size", { value: 2 * MIB }); + return file; + }); + const view = render( + {}, + pending: true, + }} + channelId="channel-1" + compact + onSubmit={() => {}} + />, + ); + const form = view.container.querySelector("form") as HTMLFormElement; + try { + drop(form, large("first")); + drop(form, large("second")); + + await waitFor(() => + expect(view.queryAllByLabelText(/^Remove /)).toHaveLength( + MAX_ATTACHMENTS_PER_MESSAGE, + ), + ); + expect(groups).toHaveLength(MAX_ATTACHMENTS_PER_MESSAGE); + expect(view.queryAllByText(/too large/)).toHaveLength(0); + expect( + view.queryAllByText( + new RegExp(`at most ${MAX_ATTACHMENTS_PER_MESSAGE} attachments`), + ), + ).toHaveLength(2); + } finally { + queryClient.removeQueries({ queryKey: deploymentKeys.attachmentLimits() }); + } +}); + /** * One key per composer, on every upload it makes — which is what lets the server count the same set * this composer can see instead of every unsent row in the channel. diff --git a/app/tests/upload-in-parts-browser.test.tsx b/app/tests/upload-in-parts-browser.test.tsx index 7a512d4d97..1cbea96f7d 100644 --- a/app/tests/upload-in-parts-browser.test.tsx +++ b/app/tests/upload-in-parts-browser.test.tsx @@ -734,12 +734,13 @@ async function settled(page: Page) { ); } -async function refusalShown(page: Page): Promise { +/** The line on the page that refuses a file, if one does: by default, an upload that failed. */ +async function refusalShown( + page: Page, + saying = "couldn't be uploaded", +): Promise { const text = await page.evaluate(() => document.body.innerText); - return ( - text.split("\n").find((line) => line.includes("couldn't be uploaded")) ?? - null - ); + return text.split("\n").find((line) => line.includes(saying)) ?? null; } /** The percentages a progress bar showed, from its first to its last. */ @@ -834,20 +835,19 @@ describe.skipIf(!asked)("a large file attaches over a slow connection", () => { const bar = page.getByRole("progressbar", { name: `Uploading ${DOCUMENT.name}`, }); + // Part way, and the line says so in words with the number a person reads, the bar's own. await page.waitForFunction(() => { - const now = Number( - document - .querySelector('[role="progressbar"]') - ?.getAttribute("aria-valuenow") ?? 0, + const shown = document.querySelector('[role="progressbar"]'); + const now = Number(shown?.getAttribute("aria-valuenow") ?? 0); + return ( + now >= 40 && + (shown?.textContent ?? "").includes("Uploading…") && + (shown?.textContent ?? "").includes(`${now}%`) ); - return now >= 40; }); const percent = Number(await bar.getAttribute("aria-valuenow")); expect(percent).toBeGreaterThanOrEqual(40); expect(percent).toBeLessThan(100); - // The line says so in words, with the number a person reads. - await page.getByText("Uploading…").waitFor(); - await page.getByText(`${percent}%`).waitFor(); release(); await settled(page); expect(await refusalShown(page)).toBeNull(); @@ -874,9 +874,16 @@ describe.skipIf(!asked)("a large file attaches over a slow connection", () => { const page = await open(engine, { deploymentRead: false }); try { await attach(page, [DOCUMENT]); - await page.getByText("Uploading…").waitFor(); answerDeployment(); - await settled(page); + // Sent, one way or the other, and its tile done. + await serverSaw(() => + server.log.some( + (entry) => + entry.what === "POST complete" || + entry.what === "POST attachments", + ), + ); + await page.getByText("2.0MB").waitFor(); expect(server.log.map((entry) => entry.what)).toEqual([ "POST attachment-uploads", ...Array.from({ length: 9 }, (_, index) => `PUT parts/${index + 1}`), @@ -891,6 +898,45 @@ describe.skipIf(!asked)("a large file attaches over a slow connection", () => { } }, 60_000); + /* + * The same race at the pick itself: a 10MB PDF picked before the deployment answer arrived was + * refused against the 8MB the box assumes until then, on an OpenBot that takes 100MB. + */ + test(`a file over 8MB picked before the page has read the limits is screened against the server's, in ${engine}`, async () => { + server = freshServer(true); + let answerDeployment = () => {}; + server.holdDeployment = new Promise((resolve) => { + answerDeployment = resolve; + }); + const page = await open(engine, { deploymentRead: false }); + const REPORT = { + name: "quarterly-report.pdf", + mimeType: "application/pdf", + buffer: Buffer.concat([ + Buffer.from("%PDF-1.7\n"), + randomBytes(10 * 1024 * 1024), + ]), + }; + try { + await attach(page, [REPORT]); + answerDeployment(); + // Refused at the pick, or on the strip and sent: whichever the box does. + await page.waitForFunction( + () => + document.body.innerText.includes("too large") || + document.body.innerText.includes("10.0MB"), + undefined, + { timeout: 30_000 }, + ); + expect(await refusalShown(page, "too large")).toBeNull(); + expect(await refusalShown(page)).toBeNull(); + expect(storedBytes(REPORT.name)?.equals(REPORT.buffer)).toBe(true); + } finally { + answerDeployment(); + await page.context().close(); + } + }, 60_000); + test(`a part the server failed is sent again by itself, and the file arrives, in ${engine}`, async () => { server = freshServer(true); server.failPartOnce = 3; From 3e85df7d3b56d41a2f257f3ccd16d6073d90a4ab Mon Sep 17 00:00:00 2001 From: David McKay Date: Fri, 4 Dec 2026 15:35:26 -0800 Subject: [PATCH 6/7] Draw a picked file in the event that picked it, and ask the limits again while they may pass Since the box learned to wait for the server's limits, every pick was screened a microtask later, even one with nothing to wait for. In WebKit its tile was then drawn a task after the pick, and a strip read straight after the pick was empty. The browser test's wait for uploads to settle read exactly that, saw nothing uploading, and checked the server before the file had gone (CI, WebKit: "a part the server failed is sent again by itself" found no part 3 at all). A pick that has nothing to wait for is screened and staged in the event that brought it again, as it was before; only a pick that waits for the limits, and any gesture behind it, takes its turn. The test's wait now waits for each picked file to be on the strip (or refused) before it looks for uploads in flight. The deployment read a pick or an upload waits on is also asked again, up to three more times, while its failure may pass (the uploads' own rule, now in lib/api/may-pass.ts), so one dropped read on a slow connection doesn't send a large file in one request. A refusal still answers at once. upload-in-parts-browser.test.tsx: "a picked file's tile is on the strip as soon as it is picked" fails in WebKit on the previous composer and passes now. --- .../channels/composer/attachments.ts | 3 +- .../components/channels/composer/composer.tsx | 116 ++++++++++-------- app/src/lib/api/may-pass.ts | 20 +++ app/src/lib/channels/upload.ts | 20 +-- .../lib/deployment/attachment-limits-now.ts | 9 +- app/tests/upload-in-parts-browser.test.tsx | 57 +++++++-- 6 files changed, 142 insertions(+), 83 deletions(-) create mode 100644 app/src/lib/api/may-pass.ts diff --git a/app/src/components/channels/composer/attachments.ts b/app/src/components/channels/composer/attachments.ts index b208637111..35942633e5 100644 --- a/app/src/components/channels/composer/attachments.ts +++ b/app/src/components/channels/composer/attachments.ts @@ -8,7 +8,8 @@ import { classifyAttachment, largestAttachmentBytes, } from "@/lib/channels/attachments"; -import { mayPass, uploadAttachment } from "@/lib/channels/upload"; +import { mayPass } from "@/lib/api/may-pass"; +import { uploadAttachment } from "@/lib/channels/upload"; import { wasCancelled } from "@/lib/channels/upload-progress"; import { ClientError } from "@/lib/client"; import { newId } from "@/lib/new-id"; diff --git a/app/src/components/channels/composer/composer.tsx b/app/src/components/channels/composer/composer.tsx index f289a8a721..dd7c888413 100644 --- a/app/src/components/channels/composer/composer.tsx +++ b/app/src/components/channels/composer/composer.tsx @@ -572,8 +572,10 @@ export function Composer({ limitsPending.current = attachmentLimits?.pending === true; const screeningLimits = useRef(limits); if (!limitsPending.current) screeningLimits.current = limits; - /** The gesture being screened, which the next one waits for (`stageFiles`). */ + /** The gesture waiting to be screened, which the next one waits for (`stageFiles`). */ const screening = useRef>(Promise.resolve()); + /** How many gestures are waiting their turn to be screened. */ + const waitingTurns = useRef(0); // Whether the Bot can read a large text file to its end: then nothing on the tile warns it is cut. const readsWhole = attachmentLimits?.readsWhole === true; /* @@ -992,55 +994,73 @@ export function Composer({ * * A pick made while the deployment answer is still on its way, holding a file the defaults * standing in for it might refuse on size, waits for the answer, so it is screened against - * this OpenBot's limits (a 10MB PDF was refused at 8MB on an OpenBot that takes 100MB). A - * pick within every one of the stand-in limits is screened at once, as it always was, so its - * tile shows without waiting. Waiting would let a second gesture screen against a count that doesn't yet hold - * the first one's files, so the gestures queue: each screens, and bumps the counts, only - * once the one before it has. + * this OpenBot's limits (a 10MB PDF was refused at 8MB on an OpenBot that takes 100MB). + * Waiting would let a second gesture screen against a count that doesn't yet hold the first + * one's files, so a gesture that arrives while another waits queues behind it: each + * screens, and bumps the counts, only once the one before it has. + * + * Every other pick is screened here and now, in the event that brought it, as it always + * was, so its tile is drawn in that same event. Screened a moment later, the tile came a + * task after the pick in WebKit, and anything reading the strip straight after the pick + * found nothing on it. */ - const turn = screening.current.then( - async (): Promise => { - const smallest = Math.min(...Object.values(screeningLimits.current)); - if ( - limitsPending.current && - picked.some((file) => file.size > smallest) - ) - screeningLimits.current = (await attachmentLimitsNow()).limits; - const screened = screenPickedFiles(picked, { - // What is on the composer, not what the hook is holding: an attachment riding on a - // send in flight belongs to that message's count, not to the one being built now. - // - // WHICH IS TRUE OF A SEND THAT LANDS AND NOT OF ONE THAT FAILS, and this number cannot - // tell them apart at the moment it is read — the send is still out. A failure hands - // the riding files back onto a strip that has filled up behind them, and the draft is - // then over the cap however carefully this counted. `tooManyStaged` is what catches - // that, because it asks about the strip as it actually is rather than predicting it. - // - // PLUS WHAT IS PARKED, which is on nobody's strip and is still counted by the server — - // see `queuedAttachmentCount`. Without the second half the client accepts a pick the - // server then refuses with a 409 the person was given no chance to avoid. - alreadyStaged: stagedCount.current + queuedAttachmentCount, - limits: screeningLimits.current, - }); - if (screened.rejected.length > 0) { - setRejected((current) => [...current, ...screened.rejected]); - refreshLimits.current?.(); - } - if (screened.accepted.length === 0) { - return undefined; + const mayWait = () => + limitsPending.current && + picked.some( + (file) => + file.size > Math.min(...Object.values(screeningLimits.current)), + ); + /** Screen the pick against `screeningLimits`, and count what it accepts. */ + const screenAndCount = (): File[] | undefined => { + const screened = screenPickedFiles(picked, { + // What is on the composer, not what the hook is holding: an attachment riding on a + // send in flight belongs to that message's count, not to the one being built now. + // + // WHICH IS TRUE OF A SEND THAT LANDS AND NOT OF ONE THAT FAILS, and this number cannot + // tell them apart at the moment it is read — the send is still out. A failure hands + // the riding files back onto a strip that has filled up behind them, and the draft is + // then over the cap however carefully this counted. `tooManyStaged` is what catches + // that, because it asks about the strip as it actually is rather than predicting it. + // + // PLUS WHAT IS PARKED, which is on nobody's strip and is still counted by the server — + // see `queuedAttachmentCount`. Without the second half the client accepts a pick the + // server then refuses with a 409 the person was given no chance to avoid. + alreadyStaged: stagedCount.current + queuedAttachmentCount, + limits: screeningLimits.current, + }); + if (screened.rejected.length > 0) { + setRejected((current) => [...current, ...screened.rejected]); + refreshLimits.current?.(); + } + if (screened.accepted.length === 0) { + return undefined; + } + // Both bumps happen as the pick is screened, so the next gesture screens against a + // number that already includes these. + stagedCount.current += screened.accepted.length; + staging.current += screened.accepted.length; + return screened.accepted; + }; + let accepted: File[] | undefined; + if (waitingTurns.current === 0 && !mayWait()) { + accepted = screenAndCount(); + } else { + waitingTurns.current += 1; + const turn = screening.current.then(async () => { + try { + if (mayWait()) + screeningLimits.current = (await attachmentLimitsNow()).limits; + return screenAndCount(); + } finally { + waitingTurns.current -= 1; } - // Both bumps happen before this turn ends, so the next gesture's turn screens against a - // number that already includes these. - stagedCount.current += screened.accepted.length; - staging.current += screened.accepted.length; - return screened.accepted; - }, - ); - screening.current = turn.then( - () => undefined, - () => undefined, - ); - const accepted = await turn; + }); + screening.current = turn.then( + () => undefined, + () => undefined, + ); + accepted = await turn; + } if (!accepted) { return; } diff --git a/app/src/lib/api/may-pass.ts b/app/src/lib/api/may-pass.ts new file mode 100644 index 0000000000..97cc6e0081 --- /dev/null +++ b/app/src/lib/api/may-pass.ts @@ -0,0 +1,20 @@ +import { ClientError } from "@/lib/client"; + +/** + * Whether a failed request may succeed if it is sent again unchanged, as Google's and AWS's + * guidance for retrying uploads has it: no answer at all, a timeout (408), too many requests (429), + * any server error (5xx, Cloudflare's 520 to 524 among them), or a refusal OpenBot itself marks + * `retryable` (the same request's first try still running, 409 `IDEMPOTENCY_IN_PROGRESS`). Never + * any other refusal. + */ +export function mayPass(error: unknown): boolean { + // No answer at all: the connection dropped, or the browser gave up (`NoAnswerError`). + if (error instanceof TypeError) return true; + if (!(error instanceof ClientError)) return false; + return ( + error.status === 408 || + error.status === 429 || + (error.status >= 500 && error.status <= 599) || + error.body?.retryable === true + ); +} diff --git a/app/src/lib/channels/upload.ts b/app/src/lib/channels/upload.ts index d108957b14..33fcd8c0c7 100644 --- a/app/src/lib/channels/upload.ts +++ b/app/src/lib/channels/upload.ts @@ -8,6 +8,7 @@ import { uploadConversationAttachment, } from "@/lib/api/generated/conversations/conversations"; import type { Attachment } from "@/lib/api/generated/model"; +import { mayPass } from "@/lib/api/may-pass"; import { idempotencyKey, organizationId } from "@/lib/api/request"; import { ClientError } from "@/lib/client"; import { attachmentLimitsNow } from "@/lib/deployment/attachment-limits-now"; @@ -60,25 +61,6 @@ const RETRIES = { /** The longest a server's `Retry-After` is waited out before the next try. */ const LONGEST_RETRY_AFTER_MS = 60_000; -/** - * Whether a failed request may succeed if it is sent again unchanged, as Google's and AWS's - * guidance for retrying uploads has it: no answer at all, a timeout (408), too many requests (429), - * any server error (5xx, Cloudflare's 520 to 524 among them), or a refusal OpenBot itself marks - * `retryable` (the same request's first try still running, 409 `IDEMPOTENCY_IN_PROGRESS`). Never - * any other refusal. - */ -export function mayPass(error: unknown): boolean { - // No answer at all: the connection dropped, or the browser gave up (`NoAnswerError`). - if (error instanceof TypeError) return true; - if (!(error instanceof ClientError)) return false; - return ( - error.status === 408 || - error.status === 429 || - (error.status >= 500 && error.status <= 599) || - error.body?.retryable === true - ); -} - /** * A failure that may pass, as p-retry is handed it. p-retry never tries a TypeError again unless * its words are a browser's own for a lost connection, and the app says a lost connection in diff --git a/app/src/lib/deployment/attachment-limits-now.ts b/app/src/lib/deployment/attachment-limits-now.ts index a7283bf9ab..7e151ed56b 100644 --- a/app/src/lib/deployment/attachment-limits-now.ts +++ b/app/src/lib/deployment/attachment-limits-now.ts @@ -1,3 +1,4 @@ +import { mayPass } from "@/lib/api/may-pass"; import { DEFAULT_ATTACHMENT_LIMITS } from "@/lib/channels/attachments"; import { queryClient } from "@/query-client"; import { @@ -16,14 +17,16 @@ import { * large file sent in one request that the edge cuts off. So this waits for the answer itself: the * one already held, or the one on its way. * - * Asked once, with none of the query client's retries: a file is waiting on it. When the deployment - * can't be read, the defaults, which every OpenBot takes. + * Asked again, up to three more times, only while its failure may pass (no answer, a timeout, a busy + * or broken server: `mayPass`), so one dropped read on a slow connection doesn't send a large file + * the way that connection can't carry. A refusal is the answer at once: a file is waiting on it. + * When the deployment can't be read, the defaults, which every OpenBot takes. */ export async function attachmentLimitsNow(): Promise { try { return await queryClient.ensureQueryData({ ...attachmentLimitsQueryOptions(), - retry: false, + retry: (failures, error) => failures < 3 && mayPass(error), }); } catch { return { limits: DEFAULT_ATTACHMENT_LIMITS, readsWhole: false }; diff --git a/app/tests/upload-in-parts-browser.test.tsx b/app/tests/upload-in-parts-browser.test.tsx index 1cbea96f7d..ba3a87e4c1 100644 --- a/app/tests/upload-in-parts-browser.test.tsx +++ b/app/tests/upload-in-parts-browser.test.tsx @@ -720,16 +720,24 @@ async function attach( await page.locator('input[type="file"]').setInputFiles(files); } -/** Until no tile says it is uploading, or a refusal is shown: whichever happens first. */ -async function settled(page: Page) { +/** + * Until each of these files is on the strip or refused, and then no tile says it is uploading or an + * upload is refused: whichever happens first. Waiting for the files first is what keeps an empty + * strip, read before a pick has been drawn, from passing for one that has finished. + */ +async function settled(page: Page, files: { name: string }[]) { await page.waitForFunction( - () => { + (names) => { const text = document.body.innerText; + const shown = (name: string) => + document.querySelector(`[aria-label="Remove ${name}"]`) !== null || + text.split("\n").some((line) => line.startsWith(`${name}:`)); return ( - text.includes("couldn't be uploaded") || !text.includes("Uploading") + names.every(shown) && + (text.includes("couldn't be uploaded") || !text.includes("Uploading")) ); }, - undefined, + files.map((file) => file.name), { timeout: 110_000 }, ); } @@ -798,7 +806,7 @@ describe.skipIf(!asked)("a large file attaches over a slow connection", () => { uploadThroughput: UPLOAD_BYTES_PER_SECOND, }); await attach(page, [DOCUMENT]); - await settled(page); + await settled(page, [DOCUMENT]); // The edge never had to give up on a request: every one arrived inside its limit. expect(server.log.filter((entry) => entry.status === 524)).toEqual([]); @@ -849,7 +857,7 @@ describe.skipIf(!asked)("a large file attaches over a slow connection", () => { expect(percent).toBeGreaterThanOrEqual(40); expect(percent).toBeLessThan(100); release(); - await settled(page); + await settled(page, [DOCUMENT]); expect(await refusalShown(page)).toBeNull(); expect(await bar.count()).toBe(0); expect(storedBytes(DOCUMENT.name)?.equals(DOCUMENT.buffer)).toBe(true); @@ -937,13 +945,38 @@ describe.skipIf(!asked)("a large file attaches over a slow connection", () => { } }, 60_000); + /* + * Screening a pick waited a microtask once the box learned to wait for the server's limits, so + * in WebKit the tile was drawn a task after the pick, and a strip read straight after the pick + * was empty: CI read it as an upload already finished. A pick that has nothing to wait for is + * drawn in the event that brought it, as before. + */ + test(`a picked file's tile is on the strip as soon as it is picked, in ${engine}`, async () => { + server = freshServer(true); + const page = await open(engine); + try { + await attach(page, [DOCUMENT]); + // Read at once, with no waiting: the pick's own event drew it. + expect( + await page.evaluate( + (name) => + document.querySelector(`[aria-label="Remove ${name}"]`) !== null, + DOCUMENT.name, + ), + ).toBe(true); + await settled(page, [DOCUMENT]); + } finally { + await page.context().close(); + } + }, 60_000); + test(`a part the server failed is sent again by itself, and the file arrives, in ${engine}`, async () => { server = freshServer(true); server.failPartOnce = 3; const page = await open(engine); try { await attach(page, [DOCUMENT]); - await settled(page); + await settled(page, [DOCUMENT]); expect(await refusalShown(page)).toBeNull(); const third = server.log.filter( (entry) => entry.what === "PUT parts/3", @@ -966,7 +999,7 @@ describe.skipIf(!asked)("a large file attaches over a slow connection", () => { const page = await open("chromium"); try { await attach(page, [DOCUMENT]); - await settled(page); + await settled(page, [DOCUMENT]); expect(await refusalShown(page)).toBeNull(); const finishes = server.log.filter( (entry) => entry.what === "POST complete", @@ -989,7 +1022,7 @@ describe.skipIf(!asked)("a large file attaches over a slow connection", () => { const page = await open("chromium"); try { await attach(page, [NOTES]); - await settled(page); + await settled(page, [NOTES]); expect(await refusalShown(page)).toBeNull(); expect(server.log.map((entry) => entry.what)).toEqual([ "POST attachments", @@ -1006,7 +1039,7 @@ describe.skipIf(!asked)("a large file attaches over a slow connection", () => { const page = await open("chromium"); try { await attach(page, [DOCUMENT]); - await settled(page); + await settled(page, [DOCUMENT]); expect(await refusalShown(page)).toBeNull(); expect(server.log.map((entry) => entry.what)).toEqual([ "POST attachments", @@ -1161,7 +1194,7 @@ describe.skipIf(!asked)("a large file attaches over a slow connection", () => { release(); } releaseWhole(); - await settled(page); + await settled(page, [DOCUMENT, PICTURE]); await page .getByRole("button", { name: `Remove ${PICTURE.name}` }) .waitFor(); From fbbe138e754e5a0fef7a7d9521ffed8bb7ce4f44 Mon Sep 17 00:00:00 2001 From: David McKay Date: Fri, 4 Dec 2026 16:11:42 -0800 Subject: [PATCH 7/7] Retry uploads and run parts one at a time with our own few lines, not p-retry and p-limit Both packages are one person's, which is not the bar for something this core, and what the upload needs from them is small. They are gone from the app and the lockfile. lib/api/retrying.ts tries a request again while its failure may pass (mayPass: no answer, 408, 429, any 5xx, or a problem marked retryable), up to 8 tries, the same request and Idempotency-Key each time. Each wait is drawn at random between nothing and a ceiling that doubles from 1s to at most 30s (AWS's "full jitter"), or the server's Retry-After when that is longer, at most a minute. The upload's signal stops a try and any wait at once. The deployment read a pick or an upload waits on uses the same helper, with up to 3 more tries. lib/channels/one-at-a-time.ts is the line a tab's parts wait in: one at a time, in order, and a part that fails doesn't stop the next. A part leaves the line between its tries, as before. upload-retry.test.ts holds the waits to their bounds on a clock and a draw of its own: inside the doubling ceiling, never past 30s, raised by Retry-After up to a minute, no wait and one try for a refusal, 8 tries at most, stopped at once when given up; and the line running one task at a time, in order, past a failure. --- app/package.json | 2 - app/src/lib/api/retrying.ts | 90 +++++++ app/src/lib/channels/one-at-a-time.ts | 16 ++ app/src/lib/channels/upload.ts | 93 +------ .../lib/deployment/attachment-limits-now.ts | 15 +- app/tests/upload-retry.test.ts | 226 ++++++++++++++++++ bun.lock | 12 +- 7 files changed, 348 insertions(+), 106 deletions(-) create mode 100644 app/src/lib/api/retrying.ts create mode 100644 app/src/lib/channels/one-at-a-time.ts create mode 100644 app/tests/upload-retry.test.ts diff --git a/app/package.json b/app/package.json index c125d616dd..26f8b10789 100644 --- a/app/package.json +++ b/app/package.json @@ -48,8 +48,6 @@ "lru-cache": "11.5.3", "mermaid": "12.3.0", "motion": "^13.1.0", - "p-limit": "7.3.3", - "p-retry": "9.0.0", "prompt-area": "^0.6.3", "react": "^19.2.0", "react-dom": "^19.2.0", diff --git a/app/src/lib/api/retrying.ts b/app/src/lib/api/retrying.ts new file mode 100644 index 0000000000..6d0fe24ef3 --- /dev/null +++ b/app/src/lib/api/retrying.ts @@ -0,0 +1,90 @@ +import { ClientError } from "@/lib/client"; +import { mayPass } from "./may-pass"; + +/** + * SENDING A REQUEST AGAIN BY ITSELF WHILE ITS FAILURE MAY PASS, AS THE LEADERS' CLIENTS DO. + * + * Up to {@link MOST_TRIES} tries. Before each try after the first the wait is drawn at random + * between nothing and a ceiling that doubles from 1 second to at most 30 ("full jitter", AWS's + * guidance for backoff: tabs that failed together don't all come back at once). A server that + * said how long to leave it (`Retry-After`) is left at least that long, up to a minute. Only a + * failure that may pass is tried again (`mayPass`): no answer, a timeout, too many requests, a + * server that is busy or broken, or a refusal OpenBot marks retryable. Any other refusal is the + * answer at once. The caller sends the same request each time, its Idempotency-Key included. + */ +export const MOST_TRIES = 8; + +const FIRST_CEILING_MS = 1000; +const LONGEST_CEILING_MS = 30_000; +/** The longest a server's `Retry-After` is waited out before the next try. */ +const LONGEST_RETRY_AFTER_MS = 60_000; + +/** + * How long to wait after the `failed`th try failed, before the next: a random share of a ceiling + * that doubles each time (1s, 2s, 4s … at most 30s), or the server's `Retry-After` if that is + * longer (at most a minute). `random` is `Math.random`'s shape, for a test to pick the share. + */ +export function waitBefore( + failed: number, + failure: unknown, + random: () => number = Math.random, +): number { + const ceiling = Math.min( + LONGEST_CEILING_MS, + FIRST_CEILING_MS * 2 ** (failed - 1), + ); + const backoff = random() * ceiling; + const asked = + failure instanceof ClientError ? failure.retryAfterMs : undefined; + return asked === undefined + ? backoff + : Math.max(backoff, Math.min(asked, LONGEST_RETRY_AFTER_MS)); +} + +export type RetryOptions = { + /** Stops the tries, and any wait between them, with the signal's reason. */ + signal?: AbortSignal; + /** At most this many tries in all; {@link MOST_TRIES} unless said. */ + tries?: number; + /** For a test: the share of each ceiling to wait (`Math.random` unless said). */ + random?: () => number; +}; + +/** A wait that the signal ends early, rejecting with its reason. */ +function pause(ms: number, signal?: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason); + return; + } + const stop = () => { + clearTimeout(timer); + reject(signal?.reason); + }; + const timer = setTimeout(() => { + signal?.removeEventListener("abort", stop); + resolve(); + }, ms); + signal?.addEventListener("abort", stop, { once: true }); + }); +} + +/** Send a request, and again while its failure may pass. Throws the last failure as it came. */ +export async function sendRetrying( + send: () => Promise, + options: RetryOptions = {}, +): Promise { + const { signal, tries = MOST_TRIES, random = Math.random } = options; + for (let failed = 0; ; ) { + signal?.throwIfAborted(); + try { + return await send(); + } catch (error) { + failed += 1; + // Given up on by the caller: that is the answer, whatever the try said. + if (signal?.aborted) throw signal.reason; + if (failed >= tries || !mayPass(error)) throw error; + await pause(waitBefore(failed, error, random), signal); + } + } +} diff --git a/app/src/lib/channels/one-at-a-time.ts b/app/src/lib/channels/one-at-a-time.ts new file mode 100644 index 0000000000..ef870fb585 --- /dev/null +++ b/app/src/lib/channels/one-at-a-time.ts @@ -0,0 +1,16 @@ +/** + * A line where one task runs at a time, in the order they joined it. A task that fails ends only + * itself: the next one runs as if it had finished. A task already in the line can't be taken out; + * one that should no longer run checks for that when its turn comes. + */ +export function oneAtATime(): (task: () => Promise) => Promise { + let last: Promise = Promise.resolve(); + return (task: () => Promise): Promise => { + const run = last.then(task); + last = run.then( + () => undefined, + () => undefined, + ); + return run; + }; +} diff --git a/app/src/lib/channels/upload.ts b/app/src/lib/channels/upload.ts index 33fcd8c0c7..9c438c0fc9 100644 --- a/app/src/lib/channels/upload.ts +++ b/app/src/lib/channels/upload.ts @@ -1,5 +1,3 @@ -import pLimit from "p-limit"; -import pRetry, { AbortError } from "p-retry"; import { cancelAttachmentUpload, completeAttachmentUpload, @@ -8,10 +6,11 @@ import { uploadConversationAttachment, } from "@/lib/api/generated/conversations/conversations"; import type { Attachment } from "@/lib/api/generated/model"; -import { mayPass } from "@/lib/api/may-pass"; import { idempotencyKey, organizationId } from "@/lib/api/request"; +import { sendRetrying } from "@/lib/api/retrying"; import { ClientError } from "@/lib/client"; import { attachmentLimitsNow } from "@/lib/deployment/attachment-limits-now"; +import { oneAtATime } from "./one-at-a-time"; import { trackUpload } from "./upload-progress"; /** @@ -43,91 +42,7 @@ export const PARTS_ABOVE_BYTES = 1024 * 1024; * shared. One at a time, every part takes as long as it would alone, and the files still finish * as soon as the connection allows. Starting and finishing an upload carry no file and don't wait. */ -const partLane = pLimit(1); - -/** - * How each request is tried again: up to 8 tries, waiting about 1, 2, 4 and 8 seconds and then at - * most 30, each wait drawn at random between one and two times its step (jitter), so tabs that - * failed together don't all come back at once. The defaults of Google's and AWS's storage clients. - */ -const RETRIES = { - retries: 7, - minTimeout: 1000, - factor: 2, - maxTimeout: 30_000, - randomize: true, -} as const; - -/** The longest a server's `Retry-After` is waited out before the next try. */ -const LONGEST_RETRY_AFTER_MS = 60_000; - -/** - * A failure that may pass, as p-retry is handed it. p-retry never tries a TypeError again unless - * its words are a browser's own for a lost connection, and the app says a lost connection in - * OpenBot's words (`NoAnswerError`), so each failure worth another try goes in wrapped. - */ -class MayPass extends Error { - constructor(readonly failure: unknown) { - super("This request may pass if it is sent again."); - this.name = "MayPass"; - } -} - -function asError(value: unknown): Error { - return value instanceof Error ? value : new Error(String(value)); -} - -function waitFor(ms: number, signal?: AbortSignal): Promise { - return new Promise((resolve) => { - const timer = setTimeout(resolve, ms); - signal?.addEventListener( - "abort", - () => { - clearTimeout(timer); - resolve(); - }, - { once: true }, - ); - }); -} - -/** Send a request, and again while its failure may pass. Throws the last failure as it came. */ -export async function sendRetrying( - send: () => Promise, - signal?: AbortSignal, -): Promise { - try { - return await pRetry( - async () => { - try { - return await send(); - } catch (error) { - if (signal?.aborted || !mayPass(error)) - throw new AbortError(asError(error)); - throw new MayPass(error); - } - }, - { - ...RETRIES, - signal, - // A server that said how long to leave it is left that long, not only the step's wait. - onFailedAttempt: async ({ error, retriesLeft, retryDelay }) => { - if (retriesLeft === 0 || !(error instanceof MayPass)) return; - const { failure } = error; - const asked = - failure instanceof ClientError ? failure.retryAfterMs : undefined; - if (asked !== undefined && asked > retryDelay) - await waitFor( - Math.min(asked, LONGEST_RETRY_AFTER_MS) - retryDelay, - signal, - ); - }, - }, - ); - } catch (error) { - throw error instanceof MayPass ? error.failure : error; - } -} +const partLane = oneAtATime(); /** The refusal to finish an upload that is missing a part. */ const PARTS_MISSING = "ATTACHMENT_PARTS_MISSING"; @@ -279,7 +194,7 @@ async function uploadInParts({ }, ); }), - signal, + { signal }, ); return part.size; }; diff --git a/app/src/lib/deployment/attachment-limits-now.ts b/app/src/lib/deployment/attachment-limits-now.ts index 7e151ed56b..7b583bc517 100644 --- a/app/src/lib/deployment/attachment-limits-now.ts +++ b/app/src/lib/deployment/attachment-limits-now.ts @@ -1,4 +1,4 @@ -import { mayPass } from "@/lib/api/may-pass"; +import { sendRetrying } from "@/lib/api/retrying"; import { DEFAULT_ATTACHMENT_LIMITS } from "@/lib/channels/attachments"; import { queryClient } from "@/query-client"; import { @@ -24,10 +24,15 @@ import { */ export async function attachmentLimitsNow(): Promise { try { - return await queryClient.ensureQueryData({ - ...attachmentLimitsQueryOptions(), - retry: (failures, error) => failures < 3 && mayPass(error), - }); + // Retried here rather than by the query, on the uploads' own rule and backoff. + return await sendRetrying( + () => + queryClient.ensureQueryData({ + ...attachmentLimitsQueryOptions(), + retry: false, + }), + { tries: 4 }, + ); } catch { return { limits: DEFAULT_ATTACHMENT_LIMITS, readsWhole: false }; } diff --git a/app/tests/upload-retry.test.ts b/app/tests/upload-retry.test.ts new file mode 100644 index 0000000000..80a0b5b725 --- /dev/null +++ b/app/tests/upload-retry.test.ts @@ -0,0 +1,226 @@ +import { afterEach, beforeEach, describe, expect, jest, test } from "bun:test"; +import { MOST_TRIES, sendRetrying, waitBefore } from "@/lib/api/retrying"; +import { oneAtATime } from "@/lib/channels/one-at-a-time"; +import { ClientError, NoAnswerError } from "@/lib/client"; + +/** + * How an upload's requests are tried again, and the line its parts wait in. + * + * Every request of an upload (each part, its start and its finish, the one-request upload and the + * deployment read they wait on) is tried again by itself while its failure may pass: up to 8 + * tries, each wait drawn at random between nothing and a ceiling that doubles from 1s to at most + * 30s ("full jitter"), or longer when the server says so (`Retry-After`, at most a minute). The + * clock and the random draw are the test's, so nothing here really waits. + */ + +const busy = (retryAfterMs?: number) => + new ClientError("OpenBot is busy.", 503, undefined, undefined, retryAfterMs); +const refused = () => new ClientError("That isn't allowed.", 400); + +describe("the wait before each try", () => { + test("is drawn between nothing and a ceiling that doubles from 1s, and never passes 30s", () => { + const ceilings = [1000, 2000, 4000, 8000, 16_000, 30_000, 30_000, 30_000]; + ceilings.forEach((ceiling, index) => { + const failed = index + 1; + expect(waitBefore(failed, busy(), () => 0)).toBe(0); + expect(waitBefore(failed, busy(), () => 0.5)).toBe(ceiling / 2); + // The top of the draw stays under the ceiling, however many tries failed. + expect(waitBefore(failed, busy(), () => 0.999_999)).toBeLessThan(ceiling); + }); + expect(waitBefore(40, busy(), () => 0.999_999)).toBeLessThan(30_000); + }); + + test("is at least what the server asked for (Retry-After), up to a minute", () => { + // The server's ask wins over a shorter draw… + expect(waitBefore(1, busy(5_000), () => 0.5)).toBe(5_000); + // …a longer draw wins over a shorter ask… + expect(waitBefore(6, busy(2_000), () => 0.5)).toBe(15_000); + // …and no ask holds a file back more than a minute. + expect(waitBefore(1, busy(600_000), () => 0)).toBe(60_000); + }); +}); + +describe("sendRetrying", () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + afterEach(() => { + jest.useRealTimers(); + }); + + /** Let the promise run, moving the clock on whenever it waits, and say how long it waited. */ + async function settle( + pending: Promise, + ): Promise<{ value?: T; error?: unknown; waited: number }> { + let done = false; + let value: T | undefined; + let error: unknown; + pending.then( + (result) => { + done = true; + value = result; + }, + (failure) => { + done = true; + error = failure; + }, + ); + let waited = 0; + while (!done) { + await new Promise((resolve) => setImmediate(resolve)); + if (done) break; + jest.advanceTimersByTime(100); + waited += 100; + } + return { value, error, waited }; + } + + test("a failure that passes is sent again, and the answer is the one that came", async () => { + let tries = 0; + const result = await settle( + sendRetrying( + async () => { + tries += 1; + if (tries < 3) throw tries === 1 ? busy() : new NoAnswerError(null); + return "stored"; + }, + { random: () => 1 }, + ), + ); + expect(result.value).toBe("stored"); + expect(tries).toBe(3); + // Waited the whole of the first two ceilings (1s, then 2s), as the draw said. + expect(result.waited).toBeGreaterThanOrEqual(3_000); + expect(result.waited).toBeLessThan(3_300); + }); + + test("a refusal is the answer at once: one try, no wait", async () => { + let tries = 0; + const result = await settle( + sendRetrying(async () => { + tries += 1; + throw refused(); + }), + ); + expect(tries).toBe(1); + expect((result.error as ClientError).status).toBe(400); + expect(result.waited).toBe(0); + }); + + test("at most 8 tries, then the last failure as it came", async () => { + let tries = 0; + const last = busy(); + const result = await settle( + sendRetrying( + async () => { + tries += 1; + throw tries === MOST_TRIES ? last : busy(); + }, + { random: () => 0 }, + ), + ); + expect(MOST_TRIES).toBe(8); + expect(tries).toBe(8); + expect(result.error).toBe(last); + }); + + test("Retry-After holds the next try back that long", async () => { + let tries = 0; + const result = await settle( + sendRetrying( + async () => { + tries += 1; + if (tries === 1) throw busy(7_000); + return "stored"; + }, + { random: () => 0 }, + ), + ); + expect(result.value).toBe("stored"); + expect(result.waited).toBeGreaterThanOrEqual(7_000); + expect(result.waited).toBeLessThan(7_300); + }); + + test("giving up stops the wait at once, with the reason it was given up", async () => { + const controller = new AbortController(); + const reason = new Error("Removed."); + let tries = 0; + const pending = sendRetrying( + async () => { + tries += 1; + throw busy(); + }, + { signal: controller.signal, random: () => 1 }, + ); + pending.catch(() => undefined); + // The first try has failed and the wait before the second has begun. + await new Promise((resolve) => setImmediate(resolve)); + controller.abort(reason); + const result = await settle(pending); + expect(result.error).toBe(reason); + expect(result.waited).toBe(0); + expect(tries).toBe(1); + }); + + test("the tries can be fewer, for a read a file is waiting on", async () => { + let tries = 0; + const result = await settle( + sendRetrying( + async () => { + tries += 1; + throw busy(); + }, + { tries: 4, random: () => 0 }, + ), + ); + expect(tries).toBe(4); + expect((result.error as ClientError).status).toBe(503); + }); +}); + +describe("oneAtATime", () => { + test("runs one task at a time, in the order they joined, and goes on after a failure", async () => { + const line = oneAtATime(); + const log: string[] = []; + let running = 0; + let most = 0; + const releases: (() => void)[] = []; + const task = (name: string, fails = false) => + line(async () => { + running += 1; + most = Math.max(most, running); + log.push(`start ${name}`); + await new Promise((resolve) => releases.push(resolve)); + running -= 1; + log.push(`end ${name}`); + if (fails) throw new Error(`${name} failed`); + return name; + }); + + const first = task("first"); + const second = task("second", true); + const third = task("third"); + second.catch(() => undefined); + + // Each is let go in turn; only the one running has a release waiting. + for (let index = 0; index < 3; index++) { + while (releases.length === 0) + await new Promise((resolve) => setImmediate(resolve)); + expect(releases).toHaveLength(1); + releases.shift()?.(); + } + + expect(await first).toBe("first"); + await expect(second).rejects.toThrow("second failed"); + expect(await third).toBe("third"); + expect(most).toBe(1); + expect(log).toEqual([ + "start first", + "end first", + "start second", + "end second", + "start third", + "end third", + ]); + }); +}); diff --git a/bun.lock b/bun.lock index df6c91d347..a4a8f845dc 100644 --- a/bun.lock +++ b/bun.lock @@ -58,8 +58,6 @@ "lru-cache": "11.5.3", "mermaid": "12.3.0", "motion": "^13.1.0", - "p-limit": "7.3.3", - "p-retry": "9.0.0", "prompt-area": "^0.6.3", "react": "^19.2.0", "react-dom": "^19.2.0", @@ -2050,13 +2048,13 @@ "p-finally": ["p-finally@1.0.0", "", {}, "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow=="], - "p-limit": ["p-limit@7.3.3", "", { "dependencies": { "yocto-queue": "^1.2.1" } }, "sha512-SKgVvDU5TNIxQ4r30U75BNLC6a+6GOEjngrk/ysM5+Zu3oJuk1SC5ApzIzY/7PjCEjoVPMWJ0zho/4QUiEB7TQ=="], + "p-limit": ["p-limit@2.3.0", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="], "p-locate": ["p-locate@3.0.0", "", { "dependencies": { "p-limit": "^2.0.0" } }, "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ=="], "p-queue": ["p-queue@6.6.2", "", { "dependencies": { "eventemitter3": "^4.0.4", "p-timeout": "^3.2.0" } }, "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ=="], - "p-retry": ["p-retry@9.0.0", "", { "dependencies": { "is-network-error": "^1.3.2" } }, "sha512-HuEats8gYn/UUYa5uyveyQGv75mQmwdFtuMgnZlS12dj/7bdnJSO6keaTjgcZUhvkANTj5EO3lACUmV3xmgj0Q=="], + "p-retry": ["p-retry@7.1.1", "", { "dependencies": { "is-network-error": "^1.1.0" } }, "sha512-J5ApzjyRkkf601HpEeykoiCvzHQjWxPAHhyjFcEUP2SWq0+35NKh8TLhpLw+Dkq5TZBFvUM6UigdE9hIVYTl5w=="], "p-timeout": ["p-timeout@3.2.0", "", { "dependencies": { "p-finally": "^1.0.0" } }, "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg=="], @@ -2554,8 +2552,6 @@ "yauzl": ["yauzl@2.10.0", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="], - "yocto-queue": ["yocto-queue@1.2.2", "", {}, "sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ=="], - "yocto-spinner": ["yocto-spinner@1.2.2", "", { "dependencies": { "yoctocolors": "^2.1.1" } }, "sha512-DODGl1wJjA/s5pnJFKau9lIYHT81lnhob1i3e1TjxZRxEhWRKl74nTbWE6H5KlkViQQTo/Z29YFdxzTZAMY3ng=="], "yoctocolors": ["yoctocolors@2.2.0", "", {}, "sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg=="], @@ -2658,8 +2654,6 @@ "@langchain/langgraph-sdk/p-queue": ["p-queue@9.3.3", "", { "dependencies": { "eventemitter3": "^5.0.4", "p-timeout": "^7.0.0" } }, "sha512-NXAOdnEe5FsZJfT4oK84lE1Y5cFFdWlRuOo5tww8DyNMxyRXwn39fIkUtNLKppcPC+UYU/bXujNCUGDv01y7CA=="], - "@langchain/langgraph-sdk/p-retry": ["p-retry@7.1.1", "", { "dependencies": { "is-network-error": "^1.1.0" } }, "sha512-J5ApzjyRkkf601HpEeykoiCvzHQjWxPAHhyjFcEUP2SWq0+35NKh8TLhpLw+Dkq5TZBFvUM6UigdE9hIVYTl5w=="], - "@modelcontextprotocol/sdk/zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="], "@mswjs/interceptors/@open-draft/deferred-promise": ["@open-draft/deferred-promise@2.2.0", "", {}, "sha512-CecwLWx3rhxVQF6V4bAgPS5t+So2sTbPgAzafKkVizyi7tlwpcFpdFqq+wqF2OwNBmqFuu6tOyouTuxgpMfzmA=="], @@ -2948,8 +2942,6 @@ "openid-client/jose": ["jose@6.2.19", "", {}, "sha512-NnThKzdK4dJTUQOBoMB0bF3Xmw4EtbFTo4xzeLaoBwcuOdBVDQcKB3/86DUTWjVMXkZOdaqZVo2OU6DllhS+9Q=="], - "p-locate/p-limit": ["p-limit@2.3.0", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="], - "p-queue/eventemitter3": ["eventemitter3@4.0.7", "", {}, "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw=="], "parse5/entities": ["entities@6.0.1", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="],