Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(documents): raise document name limit to 200, surface name-too-long toast (#4400)

gbirman4e4e4aa21301
diff --git a/js/app/packages/core/util/upload.ts b/js/app/packages/core/util/upload.ts
index da5e8635c2..17cd71f54f 100644
--- a/js/app/packages/core/util/upload.ts
+++ b/js/app/packages/core/util/upload.ts
@@ -31,6 +31,7 @@ import {
filenameWithoutExtension,
} from '@service-storage/util/filename';
import {
+ DocumentNameTooLongError,
type UploadFileOptions as DssUploadFileOptions,
type UploadSuccess as DssUploadSuccessResult,
upload as dssUpload,
@@ -282,6 +283,8 @@ class UnsupportedFileTypeError extends Error {
}
class UploadError extends Error {
+ public readonly originalError?: Error | string;
+
constructor(
file: { name: string },
destination?: UploadDestination,
@@ -291,6 +294,8 @@ class UploadError extends Error {
const message = `Upload failed: ${fileName}`;
super(message);
+ this.originalError = originalError;
+
console.error(
`upload${destination ? ` to ${destination}` : ''} failed:`,
originalError
@@ -517,8 +522,30 @@ export async function uploadFiles(
return uploadResults;
}
+function asNameTooLongError(error: Error): DocumentNameTooLongError | null {
+ if (error instanceof DocumentNameTooLongError) return error;
+ // The typed error can be wrapped by UploadError, which preserves the original.
+ if (
+ error instanceof UploadError &&
+ error.originalError instanceof DocumentNameTooLongError
+ ) {
+ return error.originalError;
+ }
+ return null;
+}
+
function handleUploadError(error: Error): void {
console.error('Upload error:', error);
+ const nameTooLong = asNameTooLongError(error);
+ if (nameTooLong != null) {
+ const { maxLength } = nameTooLong;
+ toast.failure(
+ maxLength != null
+ ? `Name too long (max ${maxLength} characters)`
+ : 'Name too long'
+ );
+ return;
+ }
if (
error instanceof UploadError ||
error instanceof FileSizeExceededError ||
diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.ts
index 78c5a474ec..2ff29fc2bb 100644
--- a/js/app/packages/service-clients/service-storage/client.ts
+++ b/js/app/packages/service-clients/service-storage/client.ts
@@ -352,6 +352,9 @@ const enhancements = {
const { showPaywall } = usePaywallState();
+/** Machine-readable code the backend returns when a document name is too long. */
+export const DOCUMENT_NAME_TOO_LONG_CODE = 'DOCUMENT_NAME_TOO_LONG' as const;
+
export const storageServiceClient = {
async ping() {
return (await dssFetch<SuccessResponse>(`/ping`)).map(
@@ -1008,18 +1011,49 @@ export const storageServiceClient = {
},
async createDocument(request: CreateDocumentRequest) {
- const result = await dssFetch<CreateDocumentResponse>(`/documents`, {
+ const result = await fetchWithToken<
+ CreateDocumentResponse,
+ typeof DOCUMENT_NAME_TOO_LONG_CODE
+ >(`${dssHost}/documents`, {
method: 'POST',
body: JSON.stringify(request),
+ // A custom handler replaces safeFetch's default status mapping. For an
+ // over-length name the backend returns a machine-readable code plus the
+ // limit; forward both (limit carried as JSON in message, since ResultError
+ // is only { code, message }) so the UI can render its own copy without
+ // hardcoding the number. 403 is preserved explicitly; other statuses keep
+ // the HTTP_ERROR shape callers branch on.
+ errorResponseHandler: async (response) => {
+ const body = (await response.json().catch(() => null)) as {
+ code?: string;
+ maxLength?: number;
+ } | null;
+ if (body?.code === DOCUMENT_NAME_TOO_LONG_CODE) {
+ return {
+ code: DOCUMENT_NAME_TOO_LONG_CODE,
+ message: JSON.stringify({ maxLength: body.maxLength }),
+ };
+ }
+ if (response.status === 403) {
+ return { code: 'FORBIDDEN', message: 'Forbidden' };
+ }
+ return {
+ code: 'HTTP_ERROR',
+ message: `HTTP error! status: ${response.status}`,
+ };
+ },
});
if (!result.isOk()) {
- const errors = result.error;
+ // The DOCUMENT_NAME_TOO_LONG code is carried at runtime for callers to
+ // branch on, but it is not part of the generated client's error union, so
+ // narrow back to it to satisfy StorageServiceClient.
+ const errors = result.error as ResultError<FetchWithTokenErrorCode>[];
if (errors[0].message.includes('403')) {
showPaywall(PaywallKey.FILE_LIMIT);
}
- return err(result.error);
+ return err(errors);
}
const { data } = result.value;
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index f5f5e583ea..1fd9819188 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -4640,6 +4640,16 @@
}
}
},
+ "422": {
+ "description": "Document name exceeds the maximum length",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
diff --git a/js/app/packages/service-clients/service-storage/util/upload.ts b/js/app/packages/service-clients/service-storage/util/upload.ts
index 2f8623b92c..e138b0e720 100644
--- a/js/app/packages/service-clients/service-storage/util/upload.ts
+++ b/js/app/packages/service-clients/service-storage/util/upload.ts
@@ -7,7 +7,10 @@ import type { ResultError } from '@core/util/result';
import { toaster } from '@kobalte/core/toast';
import { waitForDocumentContentReady } from '@queries/storage/document-location';
import { waitBulkUploadStatus } from '@service-connection/bulkUpload';
-import { storageServiceClient } from '@service-storage/client';
+import {
+ DOCUMENT_NAME_TOO_LONG_CODE,
+ storageServiceClient,
+} from '@service-storage/client';
import { filenameWithoutExtension } from '@service-storage/util/filename';
import { uploadToPresignedUrl } from '@service-storage/util/uploadToPresignedUrl';
import { storageWS } from '@service-storage/websocket';
@@ -19,6 +22,17 @@ const dismissToast = (toastId: number | null) => {
if (toastId !== null) toaster.dismiss(toastId);
};
+/**
+ * Thrown when the backend rejects a document name as too long. Carries the
+ * limit so the UI can render its own copy without hardcoding the number.
+ */
+export class DocumentNameTooLongError extends Error {
+ constructor(public readonly maxLength?: number) {
+ super('Document name too long');
+ this.name = 'DocumentNameTooLongError';
+ }
+}
+
const uploadWithPresignedUrl = async (params: {
presignedUrl: string;
buffer: ArrayBuffer;
@@ -74,6 +88,17 @@ export async function upload(
) => {
dismissToast(toastId);
+ if (Array.isArray(err) && err[0]?.code === DOCUMENT_NAME_TOO_LONG_CODE) {
+ let maxLength: number | undefined;
+ try {
+ maxLength = (JSON.parse(err[0].message) as { maxLength?: number })
+ .maxLength;
+ } catch {
+ maxLength = undefined;
+ }
+ throw new DocumentNameTooLongError(maxLength);
+ }
+
const isPaywallError = Array.isArray(err) && err[0].message.includes('403');
if (isPaywallError) {
diff --git a/rust/cloud-storage/documents/src/domain/models.rs b/rust/cloud-storage/documents/src/domain/models.rs
index e9d790286e..dfdc58ed86 100644
--- a/rust/cloud-storage/documents/src/domain/models.rs
+++ b/rust/cloud-storage/documents/src/domain/models.rs
@@ -41,6 +41,12 @@ pub enum DocumentError {
/// A bad request was made.
#[error("bad request: {0}")]
BadRequest(String),
+ /// The provided document name exceeds the maximum allowed length.
+ #[error("name too long")]
+ NameTooLong {
+ /// Maximum allowed name length, in grapheme clusters.
+ max: usize,
+ },
/// An internal error occurred.
#[error("{0}")]
Internal(#[from] anyhow::Error),
diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rs
index d0686b117a..08850de119 100644
--- a/rust/cloud-storage/documents/src/domain/service.rs
+++ b/rust/cloud-storage/documents/src/domain/service.rs
@@ -120,6 +120,8 @@ fn pending_content_for_file_type(file_type: Option<FileType>) -> DocumentContent
const GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE: &str = "github_pull_request";
+const MAX_DOCUMENT_NAME_GRAPHEMES: usize = 200;
+
fn short_id_for_entity_id(entity_id: &str) -> Result<String, DocumentError> {
let uuid = macro_uuid::string_to_uuid(entity_id)
.map_err(|e| DocumentError::BadRequest(format!("invalid entity_id: {e}")))?;
@@ -877,8 +879,10 @@ impl<
args: CreateDocumentRepoArgs,
job_id: Option<String>,
) -> Result<CreateDocumentResponseData, DocumentError> {
- if args.document_name.graphemes(true).count() > 100 {
- return Err(DocumentError::BadRequest("name too long".to_string()));
+ if args.document_name.graphemes(true).count() > MAX_DOCUMENT_NAME_GRAPHEMES {
+ return Err(DocumentError::NameTooLong {
+ max: MAX_DOCUMENT_NAME_GRAPHEMES,
+ });
}
let file_type = args.file_type;
@@ -1013,9 +1017,11 @@ impl<
args: EditDocumentServiceArgs,
) -> Result<(), DocumentError> {
if let Some(name) = args.document_name.as_ref()
- && name.graphemes(true).count() > 100
+ && name.graphemes(true).count() > MAX_DOCUMENT_NAME_GRAPHEMES
{
- return Err(DocumentError::BadRequest("name too long".to_string()));
+ return Err(DocumentError::NameTooLong {
+ max: MAX_DOCUMENT_NAME_GRAPHEMES,
+ });
}
// Check owner-only restrictions for authenticated users
@@ -1142,8 +1148,10 @@ impl<
) -> Result<DocumentResponse, DocumentError> {
use model::document::response::DocumentResponseMetadata;
- if document_name.graphemes(true).count() > 100 {
- return Err(DocumentError::BadRequest("name too long".to_string()));
+ if document_name.graphemes(true).count() > MAX_DOCUMENT_NAME_GRAPHEMES {
+ return Err(DocumentError::NameTooLong {
+ max: MAX_DOCUMENT_NAME_GRAPHEMES,
+ });
}
if document_context.deleted_at.is_some() {
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router.rs b/rust/cloud-storage/documents/src/inbound/axum_router.rs
index 39417cfc60..6bc9198a36 100644
--- a/rust/cloud-storage/documents/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/documents/src/inbound/axum_router.rs
@@ -80,14 +80,41 @@ use crate::domain::ports::DocumentService;
#[cfg(feature = "document_create")]
use crate::domain::ports::create::DocumentCreationService;
+/// Stable machine-readable error code for an over-length document name. Clients
+/// branch on this instead of the human message and render their own copy.
+pub const DOCUMENT_NAME_TOO_LONG_CODE: &str = "DOCUMENT_NAME_TOO_LONG";
+
+/// Structured 422 body for [`DocumentError::NameTooLong`]. Carries the limit so
+/// clients can show it without hardcoding a value that could drift from the API.
+#[derive(serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+struct NameTooLongErrorResponse {
+ code: &'static str,
+ max_length: usize,
+ message: &'static str,
+}
+
impl IntoResponse for DocumentError {
fn into_response(self) -> axum::response::Response {
+ if let DocumentError::NameTooLong { max } = &self {
+ return (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ Json(NameTooLongErrorResponse {
+ code: DOCUMENT_NAME_TOO_LONG_CODE,
+ max_length: *max,
+ message: "name too long",
+ }),
+ )
+ .into_response();
+ }
+
let status_code = match &self {
DocumentError::NotFound(_) => StatusCode::NOT_FOUND,
DocumentError::Unauthorized => StatusCode::UNAUTHORIZED,
DocumentError::Gone => StatusCode::GONE,
DocumentError::Conflict(_) => StatusCode::CONFLICT,
DocumentError::BadRequest(_) => StatusCode::BAD_REQUEST,
+ DocumentError::NameTooLong { .. } => StatusCode::UNPROCESSABLE_ENTITY,
DocumentError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
DocumentError::JwtEncoding(_) => StatusCode::INTERNAL_SERVER_ERROR,
};
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/create_document.rs b/rust/cloud-storage/documents/src/inbound/axum_router/create_document.rs
index 2a360656a1..b32d5d5cdf 100644
--- a/rust/cloud-storage/documents/src/inbound/axum_router/create_document.rs
+++ b/rust/cloud-storage/documents/src/inbound/axum_router/create_document.rs
@@ -30,6 +30,7 @@ use crate::domain::response::CreateDocumentResponse;
(status = 400, body = model_error_response::ErrorResponse),
(status = 401, body = model_error_response::ErrorResponse),
(status = 409, body = model_error_response::ErrorResponse),
+ (status = 422, description = "Document name exceeds the maximum length", body = model_error_response::ErrorResponse),
(status = 500, body = model_error_response::ErrorResponse),
)
)]
diff --git a/rust/cloud-storage/documents/src/inbound/toolset/create_document.rs b/rust/cloud-storage/documents/src/inbound/toolset/create_document.rs
index 5be57c28af..f971e0d961 100644
--- a/rust/cloud-storage/documents/src/inbound/toolset/create_document.rs
+++ b/rust/cloud-storage/documents/src/inbound/toolset/create_document.rs
@@ -20,6 +20,9 @@ use super::DocumentToolContext;
fn failed_to_create_document(error: DocumentError) -> ToolCallError {
let description = match &error {
DocumentError::BadRequest(message) => message.clone(),
+ DocumentError::NameTooLong { max } => {
+ format!("name too long (max {max} characters)")
+ }
_ => "failed to create document".to_string(),
};