Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Retry failed Space posts and add downloadable logs

Anand Baburajan9f83b0696859
diff --git a/rust/crates/space/src/client/assets.rs b/rust/crates/space/src/client/assets.rs
index 410c2b65bb..33af4148ab 100644
--- a/rust/crates/space/src/client/assets.rs
+++ b/rust/crates/space/src/client/assets.rs
@@ -13,6 +13,7 @@ use crate::transport::{
use crate::{
MAX_SPACE_AVATAR_UPLOAD_BYTES, MAX_SPACE_COVER_UPLOAD_BYTES, MAX_SPACE_POST_UPLOAD_BYTES,
};
+use ente_core::http;
impl AccountSpaceCtx {
pub async fn upload_post_video_asset(
@@ -69,7 +70,8 @@ impl AccountSpaceCtx {
.json(&request)
.send()
.await?
- .error_for_status()?
+ .error_for_code()
+ .await?
.json()
.await?)
}
@@ -125,15 +127,19 @@ impl AccountSpaceCtx {
}
pub async fn upload_bytes(&self, presign: &PresignUploadResponse, body: &[u8]) -> Result<()> {
- let request = presign.headers.iter().fold(
- self.api().http().put(&presign.url),
- |request, (name, value)| request.header(name, value),
- );
- request
- .body(body.to_vec())
- .send()
- .await?
- .error_for_status()?;
+ http::retry(|| async {
+ let request = presign.headers.iter().fold(
+ self.api().http().put(&presign.url),
+ |request, (name, value)| request.header(name, value),
+ );
+ request
+ .body(body.to_vec())
+ .send()
+ .await?
+ .error_for_status()?;
+ Ok(())
+ })
+ .await?;
Ok(())
}
diff --git a/rust/crates/space/src/client/posts.rs b/rust/crates/space/src/client/posts.rs
index 4bff40b36e..baa05c3a83 100644
--- a/rust/crates/space/src/client/posts.rs
+++ b/rust/crates/space/src/client/posts.rs
@@ -94,20 +94,31 @@ impl AccountSpaceCtx {
objects: objects.to_vec(),
};
let path = format!("/spaces/{space_id}/posts");
- let response = self
- .api()
- .post(&path)
- .json(&request)
- .send()
- .await?
- .error_for_code()
- .await
- .map_err(|error| match &error {
- http::Error::Api { code, .. } if code == "CONFLICT" => Error::PostLimitReached,
- _ => error.into(),
- })?
- .json::<CreatePostResponse>()
- .await?;
+ let response = http::retry_if(
+ || async {
+ self.api()
+ .post(&path)
+ .json(&request)
+ .send()
+ .await?
+ .error_for_code()
+ .await?
+ .json::<CreatePostResponse>()
+ .await
+ },
+ |error| {
+ request
+ .client_request_id
+ .as_ref()
+ .is_some_and(|id| !id.is_empty())
+ && error.is_retryable()
+ },
+ )
+ .await
+ .map_err(|error| match &error {
+ http::Error::Api { code, .. } if code == "CONFLICT" => Error::PostLimitReached,
+ _ => error.into(),
+ })?;
Ok((response.post_id, post_key_bytes))
}
diff --git a/web/apps/space/package.json b/web/apps/space/package.json
index 0451bd4ae5..3c3035f122 100644
--- a/web/apps/space/package.json
+++ b/web/apps/space/package.json
@@ -10,7 +10,7 @@
"@ffmpeg/ffmpeg": "0.12.15",
"@fontsource-variable/inter": "5.2.8",
"@fontsource/nunito": "5.2.7",
- "@hugeicons/core-free-icons": "1.2.1",
+ "@hugeicons/core-free-icons": "4.3.5",
"@hugeicons/react": "1.1.4",
"ente-accounts": "*",
"ente-base": "*",
diff --git a/web/apps/space/src/components/FileViewer.tsx b/web/apps/space/src/components/FileViewer.tsx
index 6349f969cd..be99923cae 100644
--- a/web/apps/space/src/components/FileViewer.tsx
+++ b/web/apps/space/src/components/FileViewer.tsx
@@ -1639,7 +1639,6 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
title="Edit item"
disabled={
isDraftPostActionRunning ||
- isDraftPostPreviewPending ||
Boolean(draftPostPreparationError)
}
onClick={() => {
diff --git a/web/apps/space/src/components/FriendQuickActionsDialog.tsx b/web/apps/space/src/components/FriendQuickActionsDialog.tsx
index 5315299552..6e072450a8 100644
--- a/web/apps/space/src/components/FriendQuickActionsDialog.tsx
+++ b/web/apps/space/src/components/FriendQuickActionsDialog.tsx
@@ -320,7 +320,7 @@ export const FriendQuickActionsDialog: React.FC<
animation: "none",
},
...(action.icon == BubbleChatIcon && {
- "& svg path:first-of-type": {
+ "& svg path:last-of-type": {
display: "none",
},
}),
diff --git a/web/apps/space/src/components/HomeHeader.tsx b/web/apps/space/src/components/HomeHeader.tsx
index ace078ebf3..d264d022a0 100644
--- a/web/apps/space/src/components/HomeHeader.tsx
+++ b/web/apps/space/src/components/HomeHeader.tsx
@@ -212,7 +212,7 @@ export const SpaceHomeHeader: React.FC<SpaceHomeHeaderProps> = ({
justifyContent: "center",
position: "relative",
width: headerChatCircleSize,
- "& svg path:first-of-type": { display: "none" },
+ "& svg path:last-of-type": { display: "none" },
}}
>
<HugeiconsIcon
diff --git a/web/apps/space/src/components/PostComposer.tsx b/web/apps/space/src/components/PostComposer.tsx
index 325ec3091f..25a44a600f 100644
--- a/web/apps/space/src/components/PostComposer.tsx
+++ b/web/apps/space/src/components/PostComposer.tsx
@@ -255,7 +255,11 @@ export const SpacePostComposer: React.FC<{
if (!snapshot.drafts.some(({ id }) => id == draft.id))
releasePreview(draft);
}
- setDrafts(snapshot.drafts);
+ setDrafts(
+ drafts.filter((draft) =>
+ snapshot.drafts.some(({ id }) => id == draft.id),
+ ),
+ );
setActiveIndex(snapshot.activeIndex);
setEditorSnapshot(undefined);
};
diff --git a/web/apps/space/src/pages/_app.tsx b/web/apps/space/src/pages/_app.tsx
index 01be0a86b1..b1350b3c88 100644
--- a/web/apps/space/src/pages/_app.tsx
+++ b/web/apps/space/src/pages/_app.tsx
@@ -8,6 +8,7 @@ import "configure-zod";
import { CustomHead } from "ente-base/components/Head";
import { useSetupLogs } from "ente-base/components/utils/hooks-app";
import { shareTheme } from "ente-base/components/utils/theme";
+import { setLogSanitizer } from "ente-base/log";
import { captureSpacePWAInstallPrompt } from "hooks/use-pwa-install-prompt";
import type { AppProps } from "next/app";
import { useRouter } from "next/router";
@@ -26,8 +27,11 @@ import {
spaceTextMuted,
} from "styles/colors";
import "styles/globals.css";
+import { sanitizeSpaceLog } from "utils/logs";
import { spacePageTitle } from "utils/page-titles";
+setLogSanitizer(sanitizeSpaceLog);
+
const interFontURL = new URL(
"@fontsource-variable/inter/files/inter-latin-wght-normal.woff2",
import.meta.url,
@@ -99,7 +103,7 @@ const spaceTheme = createTheme(
);
const App: React.FC<AppProps> = ({ Component, pageProps }) => {
- useSetupLogs({ disableDiskLogs: true });
+ useSetupLogs();
const router = useRouter();
const publicProfileManifest = router.pathname == "/profile-link";
diff --git a/web/apps/space/src/pages/app/index.tsx b/web/apps/space/src/pages/app/index.tsx
index ea95ce5d14..2ed948a4cb 100644
--- a/web/apps/space/src/pages/app/index.tsx
+++ b/web/apps/space/src/pages/app/index.tsx
@@ -41,6 +41,7 @@ const Page: React.FC = () => {
profile,
profileLoadError,
profileLoadStatus,
+ retryPost,
setFriends,
setLocalFeedPosts,
setPendingPostPhotoFiles,
@@ -326,6 +327,7 @@ const Page: React.FC = () => {
onInviteFriendsToastClose={closeInviteFriendsToast}
onAddFriend={() => setIsAddFriendOpen(true)}
onPostPhotoSelect={setPendingPostPhotoFiles}
+ onRetryPost={retryPost}
onDeletePost={async (postId) => {
const spaceId = profile?.spaceId;
if (!spaceId) throw new Error("Missing space.");
diff --git a/web/apps/space/src/screens/HomeScreen.tsx b/web/apps/space/src/screens/HomeScreen.tsx
index 51a64c3020..53d2cb725e 100644
--- a/web/apps/space/src/screens/HomeScreen.tsx
+++ b/web/apps/space/src/screens/HomeScreen.tsx
@@ -111,6 +111,7 @@ interface HomeScreenProps {
showInviteFriendsToast?: boolean;
onAddFriend: () => void;
onPostPhotoSelect: (files: File[]) => void;
+ onRetryPost?: (localPostId: string) => Promise<void>;
onDeletePost?: (postId: number) => Promise<void> | void;
onLoadMoreFeedItems?: () => Promise<void> | void;
onLoadPostAvatar?: SpacePostAvatarURLLoader;
@@ -363,7 +364,7 @@ class FeedMotionList extends React.Component<FeedMotionListProps> {
}
}
-type FeedTimestampStatus = "failed" | "post-limit" | "posted" | "posting";
+type FeedTimestampStatus = "failed" | "posted" | "posting";
interface FeedPostPhoto extends SpacePostPhoto {
isUnavailable?: boolean;
@@ -372,6 +373,7 @@ interface FeedPostPhoto extends SpacePostPhoto {
type FeedPhotoSource = SpacePostPhoto & Pick<SpacePost, "postId" | "spaceId">;
interface FeedItemProps {
+ onRetry?: () => void;
photoCount?: number;
photoIndex?: number;
photos?: FeedPostPhoto[];
@@ -868,6 +870,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
onOpenPhoto,
onOpenProfile,
onSetPostLiked,
+ onRetry,
postId,
spaceId,
thumbHash,
@@ -1207,7 +1210,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
minHeight: spaceTouchTargetSize,
position: "absolute",
right: photoCount > 1 ? 16 : 8,
- top: 12,
+ top: photoCount > 1 ? 4 : 12,
zIndex: 3,
pointerEvents: "none",
}}
@@ -1564,17 +1567,14 @@ const FeedItem: React.FC<FeedItemProps> = ({
aria-label={
timestampStatus == "posting"
? "Posting"
- : timestampStatus == "post-limit"
- ? "Post limit reached. Please contact support."
- : timestampStatus == "failed"
- ? "Failed"
- : "Posted"
+ : timestampStatus == "failed"
+ ? "Failed"
+ : "Posted"
}
sx={{
alignItems: "center",
color:
- timestampStatus == "failed" ||
- timestampStatus == "post-limit"
+ timestampStatus == "failed"
? dangerColor
: feedTimestampForeground,
display: "flex",
@@ -1582,21 +1582,64 @@ const FeedItem: React.FC<FeedItemProps> = ({
fontWeight: 500,
lineHeight: "16px",
minHeight: 16,
- whiteSpace:
- timestampStatus == "post-limit"
- ? "normal"
- : "nowrap",
+ whiteSpace: "nowrap",
}}
>
{timestampStatus == "posted" ? (
<Box component="span">Posted</Box>
- ) : timestampStatus == "post-limit" ? (
- <Box component="span">
- Post limit reached. Please contact
- support.
- </Box>
) : timestampStatus == "failed" ? (
- <Box component="span">Failed</Box>
+ <>
+ <Box component="span">Failed</Box>
+ {onRetry && (
+ <>
+ <Box
+ component="span"
+ aria-hidden
+ sx={{
+ color: feedTimestampForeground,
+ mx: 0.75,
+ }}
+ >
+ Β·
+ </Box>
+ <Box
+ component="button"
+ type="button"
+ aria-label="Retry post"
+ onClick={onRetry}
+ sx={{
+ appearance: "none",
+ bgcolor: "transparent",
+ border: 0,
+ borderRadius: "2px",
+ color: "#FFFFFF",
+ cursor: "pointer",
+ font: "inherit",
+ minHeight: 24,
+ my: -0.5,
+ p: 0,
+ pointerEvents: "auto",
+ textDecoration:
+ "underline",
+ textDecorationColor:
+ "rgba(255, 255, 255, 0.6)",
+ textUnderlineOffset:
+ "2px",
+ "&:hover": {
+ textDecorationColor:
+ "#FFFFFF",
+ },
+ "&:focus-visible": {
+ outline: `2px solid ${green}`,
+ outlineOffset: 2,
+ },
+ }}
+ >
+ Retry
+ </Box>
+ </>
+ )}
+ </>
) : (
<>
<Box component="span">Posting</Box>
@@ -1848,6 +1891,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
showInviteFriendsToast = false,
onAddFriend,
onPostPhotoSelect,
+ onRetryPost,
onDeletePost,
onLoadMoreFeedItems,
onLoadPostAvatar,
@@ -2174,11 +2218,12 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
onOpenProfile={onOpenProfile}
photoCount={item.photoCount}
postId={0}
+ onRetry={
+ onRetryPost ? () => void onRetryPost(item.id) : undefined
+ }
timestampStatus={
item.status == "failed"
- ? item.reason == "post-limit"
- ? "post-limit"
- : "failed"
+ ? "failed"
: item.postId
? "posted"
: "posting"
diff --git a/web/apps/space/src/screens/ProfileScreen.tsx b/web/apps/space/src/screens/ProfileScreen.tsx
index a654a89185..48a9bcdad6 100644
--- a/web/apps/space/src/screens/ProfileScreen.tsx
+++ b/web/apps/space/src/screens/ProfileScreen.tsx
@@ -1019,7 +1019,7 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
justifyContent: "flex-end",
p: 0,
width: spaceTouchTargetSize,
- "& svg path:first-of-type": {
+ "& svg path:last-of-type": {
display: "none",
},
"&:focus-visible": {
diff --git a/web/apps/space/src/screens/SettingsScreen.tsx b/web/apps/space/src/screens/SettingsScreen.tsx
index 662ba17af4..80ca67eb30 100644
--- a/web/apps/space/src/screens/SettingsScreen.tsx
+++ b/web/apps/space/src/screens/SettingsScreen.tsx
@@ -5,6 +5,7 @@ import {
CustomerSupportIcon,
Image01Icon,
Logout05Icon,
+ LogsIcon,
Notification02Icon,
ScreenAddToHomeIcon,
UserEdit01Icon,
@@ -18,6 +19,8 @@ import { SpaceNotificationPermissionInstructions } from "components/Notification
import { SpacePWAInstallInstructions } from "components/PWAInstallPrompt";
import { SpaceSkipLink } from "components/SkipLink";
import log from "ente-base/log";
+import { savedLogs } from "ente-base/log-web";
+import { saveStringAsFile } from "ente-base/utils/web";
import {
isSpaceIOS,
isSpaceStandalone,
@@ -34,6 +37,7 @@ import {
spaceTextMuted,
} from "styles/colors";
import { spaceTouchTargetSize } from "styles/touch-targets";
+import { sanitizeSpaceLog } from "utils/logs";
const green = "#08C225";
const textBase = spaceText;
@@ -554,6 +558,16 @@ export const SettingsScreen: React.FC<SettingsScreenProps> = ({
icon={CustomerSupportIcon}
label="Support"
/>
+ <SettingsRow
+ icon={LogsIcon}
+ label="Download logs"
+ onClick={() =>
+ saveStringAsFile(
+ savedLogs(sanitizeSpaceLog),
+ `ente-space-logs-${Date.now()}.txt`,
+ )
+ }
+ />
<SettingsRow
danger
icon={Logout05Icon}
diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.ts
index 3c9657af2f..de3b924053 100644
--- a/web/apps/space/src/services/space.ts
+++ b/web/apps/space/src/services/space.ts
@@ -1165,17 +1165,23 @@ export const createCurrentMediaPost = async ({
signal?: AbortSignal;
}) => {
const ctx = await ensureCurrentSpaceContext();
+ let stage = "prepare";
+ let itemIndex: number | undefined;
+ let bytes: number | undefined;
try {
if (!session.postId) {
session.key ??= ctx.generatePostKey();
session.requestId ??= crypto.randomUUID();
for (const [index, image] of images.entries()) {
+ itemIndex = index + 1;
signal?.throwIfAborted();
let upload = session.uploads[index];
if (!upload || upload.expiresAt < Date.now()) {
upload = { expiresAt: Date.now() + 25 * 60 * 1000 };
session.uploads[index] = upload;
}
+ stage = "upload-preview";
+ bytes = image.file.size;
upload.preview ??= await ctx.uploadPostPhotoAsset(
spaceId,
session.key,
@@ -1189,7 +1195,9 @@ export const createCurrentMediaPost = async ({
signal,
);
signal?.throwIfAborted();
- if (image.video)
+ if (image.video) {
+ stage = "upload-video";
+ bytes = image.video.file.size;
upload.video ??= await ctx.uploadPostVideoAsset(
spaceId,
session.key,
@@ -1201,8 +1209,12 @@ export const createCurrentMediaPost = async ({
},
signal,
);
+ }
}
signal?.throwIfAborted();
+ stage = "create-post";
+ itemIndex = undefined;
+ bytes = undefined;
session.postId = Number(
await ctx.createMediaPost(
spaceId,
@@ -1217,6 +1229,12 @@ export const createCurrentMediaPost = async ({
);
}
return session.postId;
+ } catch (error) {
+ log.error(
+ `Space post upload failed ${JSON.stringify({ requestId: session.requestId, stage, itemIndex, itemCount: images.length, bytes })}`,
+ error,
+ );
+ throw error;
} finally {
releaseCurrentSpaceContext(ctx);
}
diff --git a/web/apps/space/src/state/AppStateProvider.tsx b/web/apps/space/src/state/AppStateProvider.tsx
index f52612da7e..4bc7fe7e46 100644
--- a/web/apps/space/src/state/AppStateProvider.tsx
+++ b/web/apps/space/src/state/AppStateProvider.tsx
@@ -1,4 +1,3 @@
-import { isNamedError } from "ente-base/error";
import { retryAsyncOperation } from "ente-base/http";
import log from "ente-base/log";
import React, {
@@ -89,9 +88,13 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
const profileLoadGenerationRef = useRef(0);
const postPublishGenerationRef = useRef(0);
const postReadbacksRef = useRef(new Map<string, () => Promise<void>>());
+ const postUploadsRef = useRef(
+ new Map<string, () => ReturnType<SpaceAppState["publishPost"]>>(),
+ );
useEffect(() => {
const readbacks = postReadbacksRef.current;
+ const uploads = postUploadsRef.current;
const retryReadbacks = () => {
readbacks.forEach((readback) => void readback());
};
@@ -101,6 +104,7 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
window.removeEventListener("online", retryReadbacks);
window.removeEventListener("focus", retryReadbacks);
readbacks.clear();
+ uploads.clear();
};
}, []);
@@ -126,17 +130,6 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
[],
);
- useEffect(() => {
- if (postPublication?.phase != "failed") return;
-
- const timeoutID = window.setTimeout(() => {
- setPostPublication((current) =>
- current == postPublication ? null : current,
- );
- }, 2500);
- return () => window.clearTimeout(timeoutID);
- }, [postPublication]);
-
const publishPost = useCallback(
async (
images: Parameters<SpaceAppState["publishPost"]>[0],
@@ -148,7 +141,6 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
const cover = images[0]!;
const previewUrl = cover.previewUrl;
- const generation = ++postPublishGenerationRef.current;
const localPostId = createLocalFeedPostID();
const timestampMs = Date.now();
setLocalFeedPosts((current) => [
@@ -184,112 +176,175 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
width: cover.width,
},
};
- setPostPublication(publication);
- try {
- const prepared: PreparedSpacePostMedia[] = [];
- for (const image of images) {
- prepared.push(
- image.video
- ? await prepareSpaceVideo(image.file, image.video)
- : await prepareSpacePostImageFromEdit(
- image.file,
- image.cropArea,
- image.rotationDegrees,
- ),
- );
- }
- const session: SpacePostUploadSession = { uploads: [] };
- const postId = await createCurrentMediaPost({
- caption,
- images: prepared,
- spaceId,
- session,
- });
- const posted = { ...publication.post, postId };
- if (profileRef.current?.spaceId != spaceId) return posted;
+ const prepared: PreparedSpacePostMedia[] = [];
+ const session: SpacePostUploadSession = {
+ requestId: crypto.randomUUID(),
+ uploads: [],
+ };
+ let pending: ReturnType<SpaceAppState["publishPost"]> | undefined;
+ let attempt = 0;
+ const upload = () => {
+ if (pending) return pending;
+ const generation = ++postPublishGenerationRef.current;
+ const startedAt = Date.now();
+ attempt += 1;
+ setPostPublication(publication);
setLocalFeedPosts((current) =>
current.map((item) =>
- item.id == localPostId && item.status == "pending"
- ? { ...item, postId }
+ item.id == localPostId && item.status == "failed"
+ ? { ...item, status: "pending" }
: item,
),
);
- if (postPublishGenerationRef.current == generation) {
- setPostPublication({
- ...publication,
- phase: "posted",
- post: posted,
- statusExpiresAtMs: Date.now() + postStatusDurationMs,
- });
- }
- const previews = prepared.map((image) => image.file);
- let reading = false;
- const readback = async () => {
- if (reading) return;
- reading = true;
+ pending = (async () => {
try {
- const post = await retryAsyncOperation(
- () => {
- if (!postReadbacksRef.current.has(localPostId))
- throw new DOMException(
- "Canceled",
- "AbortError",
- );
- return loadCurrentCreatedPost(
- spaceId,
- session.postId!,
- previews,
+ for (const [index, image] of images.entries()) {
+ if (prepared[index]) continue;
+ try {
+ prepared[index] = image.video
+ ? await prepareSpaceVideo(
+ image.file,
+ image.video,
+ )
+ : await prepareSpacePostImageFromEdit(
+ image.file,
+ image.cropArea,
+ image.rotationDegrees,
+ );
+ } catch (error) {
+ log.error(
+ `Space post preparation failed request=${session.requestId} item=${index + 1}/${images.length} type=${image.file.type} bytes=${image.file.size}`,
+ error,
);
- },
- {
- abortIfNeeded: (error) => {
- if (
- !postReadbacksRef.current.has(
- localPostId,
- )
- )
- throw error;
- },
- },
+ throw error;
+ }
+ }
+ if (!postUploadsRef.current.has(localPostId))
+ throw new DOMException("Canceled", "AbortError");
+ const postId = await createCurrentMediaPost({
+ caption,
+ images: prepared,
+ spaceId,
+ session,
+ });
+ const posted = { ...publication.post, postId };
+ postUploadsRef.current.delete(localPostId);
+ log.info(
+ `Space post published request=${session.requestId} attempt=${attempt} elapsedMs=${Date.now() - startedAt}`,
);
- if (!postReadbacksRef.current.has(localPostId)) return;
- post.avatarUrl = profile.avatarUrl;
- postReadbacksRef.current.delete(localPostId);
- confirmLocalFeedPost(
- setLocalFeedPosts,
- localPostId,
- post,
+ if (profileRef.current?.spaceId != spaceId)
+ return posted;
+ setLocalFeedPosts((current) =>
+ current.map((item) =>
+ item.id == localPostId &&
+ item.status == "pending"
+ ? { ...item, postId }
+ : item,
+ ),
);
- if (postPublishGenerationRef.current == generation)
- setPostPublication(
- (current) => current && { ...current, post },
- );
+ if (postPublishGenerationRef.current == generation) {
+ setPostPublication({
+ ...publication,
+ phase: "posted",
+ post: posted,
+ statusExpiresAtMs:
+ Date.now() + postStatusDurationMs,
+ });
+ }
+ const previews = prepared.map((image) => image.file);
+ let reading = false;
+ const readback = async () => {
+ if (reading) return;
+ reading = true;
+ try {
+ const post = await retryAsyncOperation(
+ () => {
+ if (
+ !postReadbacksRef.current.has(
+ localPostId,
+ )
+ )
+ throw new DOMException(
+ "Canceled",
+ "AbortError",
+ );
+ return loadCurrentCreatedPost(
+ spaceId,
+ session.postId!,
+ previews,
+ );
+ },
+ {
+ abortIfNeeded: (error) => {
+ if (
+ !postReadbacksRef.current.has(
+ localPostId,
+ )
+ )
+ throw error;
+ },
+ },
+ );
+ if (!postReadbacksRef.current.has(localPostId))
+ return;
+ post.avatarUrl = profile.avatarUrl;
+ postReadbacksRef.current.delete(localPostId);
+ confirmLocalFeedPost(
+ setLocalFeedPosts,
+ localPostId,
+ post,
+ );
+ if (
+ postPublishGenerationRef.current ==
+ generation
+ )
+ setPostPublication(
+ (current) =>
+ current && { ...current, post },
+ );
+ } catch (error) {
+ log.warn(
+ "Failed to refresh a published post",
+ error,
+ );
+ } finally {
+ reading = false;
+ }
+ };
+ postReadbacksRef.current.set(localPostId, readback);
+ void readback();
+ return posted;
} catch (error) {
- log.warn("Failed to refresh a published post", error);
- } finally {
- reading = false;
+ log.error(
+ `Space post failed request=${session.requestId} attempt=${attempt} elapsedMs=${Date.now() - startedAt}`,
+ error,
+ );
+ failLocalFeedPost(setLocalFeedPosts, localPostId);
+ if (postPublishGenerationRef.current == generation) {
+ setPostPublication({
+ ...publication,
+ phase: "failed",
+ });
+ }
+ throw error;
}
- };
- postReadbacksRef.current.set(localPostId, readback);
- void readback();
- return posted;
- } catch (error) {
- failLocalFeedPost(
- setLocalFeedPosts,
- localPostId,
- isNamedError(error, "post_limit_reached")
- ? "post-limit"
- : undefined,
- );
- if (postPublishGenerationRef.current == generation) {
- setPostPublication({ ...publication, phase: "failed" });
- }
- throw error;
- }
+ })().finally(() => {
+ pending = undefined;
+ });
+ return pending;
+ };
+ postUploadsRef.current.set(localPostId, upload);
+ return upload();
},
[],
);
+ const retryPost = useCallback(async (localPostId: string) => {
+ await postUploadsRef.current
+ .get(localPostId)?.()
+ .catch(() => undefined);
+ }, []);
+
const applyProfile = useCallback<SpaceAppState["setProfile"]>((update) => {
const nextProfile =
typeof update == "function" ? update(profileRef.current) : update;
@@ -459,6 +514,7 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
setProfileLoadStatus("ready");
postPublishGenerationRef.current += 1;
postReadbacksRef.current.clear();
+ postUploadsRef.current.clear();
setPostPublication(null);
setPendingLoginCredentials(null);
setPendingPasskeyVerification(null);
@@ -495,6 +551,7 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
resetAfterLogout,
setPostPublication,
publishPost,
+ retryPost,
setFriends,
setLocalFeedPosts,
setIsLiveSignupVerification,
@@ -528,6 +585,7 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
refreshProfile,
resetAfterLogout,
publishPost,
+ retryPost,
signupEmail,
applyProfile,
],
diff --git a/web/apps/space/src/state/app-state.tsx b/web/apps/space/src/state/app-state.tsx
index 1bceff0f3c..1e8a86693f 100644
--- a/web/apps/space/src/state/app-state.tsx
+++ b/web/apps/space/src/state/app-state.tsx
@@ -44,7 +44,6 @@ interface PendingSpaceFeedPost {
}
export type FailedSpaceFeedPost = Omit<PendingSpaceFeedPost, "status"> & {
- reason?: "post-limit";
status: "failed";
};
@@ -93,6 +92,7 @@ export interface SpaceAppState {
images: SpaceDraftPostImage[],
caption: string,
) => Promise<SpacePost>;
+ retryPost: (localPostId: string) => Promise<void>;
refreshProfile: (
options?: RefreshSpaceProfileOptions,
) => Promise<SetupProfile | null>;
diff --git a/web/apps/space/src/utils/local-feed-post.ts b/web/apps/space/src/utils/local-feed-post.ts
index aedb9bd04d..9cd0167c39 100644
--- a/web/apps/space/src/utils/local-feed-post.ts
+++ b/web/apps/space/src/utils/local-feed-post.ts
@@ -1,11 +1,10 @@
import type React from "react";
import type { SpacePost } from "services/space";
-import type { FailedSpaceFeedPost, LocalSpaceFeedPost } from "state/app-state";
+import type { LocalSpaceFeedPost } from "state/app-state";
let nextLocalFeedPostID = 0;
const postedConfirmationDurationMs = 1500;
-const failedPostDurationMs = 2500;
export const createLocalFeedPostID = () =>
`space-local-post-${Date.now()}-${nextLocalFeedPostID++}`;
@@ -41,19 +40,12 @@ export const failLocalFeedPost = (
React.SetStateAction<LocalSpaceFeedPost[]>
>,
localPostId: string,
- reason?: FailedSpaceFeedPost["reason"],
) => {
setLocalFeedPosts((currentPosts) =>
currentPosts.map((item) =>
item.id == localPostId && item.status == "pending"
- ? { ...item, reason, status: "failed" }
+ ? { ...item, status: "failed" }
: item,
),
);
-
- window.setTimeout(() => {
- setLocalFeedPosts((currentPosts) =>
- currentPosts.filter((item) => item.id != localPostId),
- );
- }, failedPostDurationMs);
};
diff --git a/web/apps/space/src/utils/logs.ts b/web/apps/space/src/utils/logs.ts
new file mode 100644
index 0000000000..606c77b406
--- /dev/null
+++ b/web/apps/space/src/utils/logs.ts
@@ -0,0 +1,133 @@
+const events = [
+ "Space post upload failed",
+ "Space post preparation failed",
+ "Space post failed",
+ "Space post published",
+ "Failed to publish space post",
+ "Failed to refresh a published post",
+ "Failed to prepare post preview",
+ "Failed to prepare edited post photos",
+ "WebCodecs export failed, using FFmpeg",
+ "[wasm] ffmpeg command failed",
+ "[wasm] ffprobe command failed",
+ "[rust] ente_core::http: retrying",
+ "Failed to load space feed",
+ "Failed to load space profile",
+ "Failed to decrypt Space browser session",
+ "Space login email verification failed",
+ "Space signup verification failed",
+ "Space 2FA verification failed",
+ "Space passkey verification failed",
+ "Unhandled error",
+ "Unhandled promise rejection",
+ "Application error",
+ "Application warning",
+ "Application event",
+];
+
+const errorCodes = [
+ "SPACE_UPLOAD_LIMIT_REACHED",
+ "post_limit_reached",
+ "UNAUTHORIZED",
+ "PERMISSION_DENIED",
+ "BAD_REQUEST",
+ "NOT_FOUND",
+ "CONFLICT",
+ "RATE_LIMIT_EXCEEDED",
+];
+
+const errorReasons = [
+ "error sending request",
+ "Failed to fetch",
+ "Load failed",
+ "NetworkError",
+ "TimeoutError",
+ "AbortError",
+ "QuotaExceededError",
+ "NotSupportedError",
+ "EncodingError",
+ "SecurityError",
+ "SpaceImageTypeError",
+ "SpaceImageSizeError",
+ "Only photos can be uploaded.",
+ "This photo is too large. Try a smaller one.",
+ "Could not decode image",
+ "Could not encode image",
+ "Could not create image canvas",
+ "Invalid image dimensions",
+ "This browser can't preview this video.",
+ "The video took too long to load.",
+ "This video has no readable duration.",
+ "Couldn't prepare the video cover.",
+ "Choose a video segment of up to 10 seconds.",
+ "This video is too large. Try a shorter trim.",
+ "Couldn't export a video within 10 seconds.",
+ "Couldn't read video packets",
+ "Couldn't prepare the video frames",
+ "Video export is missing frames",
+ "space post limit reached",
+ "missing secret key material",
+ "TypeError",
+ "RangeError",
+ "SyntaxError",
+];
+
+const uploadFields: [string, RegExp][] = [
+ [
+ "request",
+ /(?:request=|"requestId":")([a-f\d]{8}-[a-f\d]{4}-4[a-f\d]{3}-[89ab][a-f\d]{3}-[a-f\d]{12})\b/i,
+ ],
+ [
+ "stage",
+ /(?:stage=|"stage":")(prepare|upload-preview|upload-video|create-post)\b/,
+ ],
+ ["attempt", /\battempt=(\d{1,6})\b/],
+ ["elapsedMs", /\belapsedMs=(\d{1,12})\b/],
+ ["item", /\bitem=(\d{1,2}\/\d{1,2})\b/],
+ ["itemIndex", /(?:itemIndex=|"itemIndex":)(\d{1,2})\b/],
+ ["itemCount", /(?:itemCount=|"itemCount":)(\d{1,2})\b/],
+ ["bytes", /(?:bytes=|"bytes":)(\d{1,12})\b/],
+ [
+ "type",
+ /\btype=((?:image\/(?:jpeg|jpg|png|webp|heic|heif)|video\/(?:mp4|quicktime|webm)))(?=\s|$)/,
+ ],
+];
+
+export const sanitizeSpaceLog = (message: string) => {
+ const level = /^\[(error|warn|info)\] /.exec(message)?.[1] ?? "info";
+ const body = message.replace(/^\[(error|warn|info)\] /, "");
+ const event =
+ events.find((event) => body.startsWith(event)) ??
+ (level == "error"
+ ? "Application error"
+ : level == "warn"
+ ? "Application warning"
+ : "Application event");
+ const details = [`[${level}] ${event}`];
+ if (event.startsWith("Space post ")) {
+ const metadata = body.split(": ")[0]!;
+ for (const [field, pattern] of uploadFields) {
+ const value = pattern.exec(metadata)?.[1];
+ if (value) details.push(`${field}=${value}`);
+ }
+ }
+ if (event == "[rust] ente_core::http: retrying") {
+ const delay =
+ /(?:retrying in |delaySeconds=)(2|5|10|30|120)(?:s|\b)/.exec(
+ body,
+ )?.[1];
+ if (delay) details.push(`delaySeconds=${delay}`);
+ }
+ const exitCode =
+ /(?:ffmpeg command failed with exit code |ffprobe command failed with exit code |exitCode=)(-?\d{1,3})\b/.exec(
+ body,
+ )?.[1];
+ if (exitCode) details.push(`exitCode=${exitCode}`);
+ const status = /(?:HTTP |status=)([45]\d{2})\b/.exec(body)?.[1];
+ if (status) details.push(`status=${status}`);
+ const code = errorCodes.find((code) => body.includes(code));
+ if (code) details.push(`code=${code}`);
+ const reason = errorReasons.find((reason) => body.includes(reason));
+ if (reason) details.push(`reason=${reason}`);
+ return details.join(" ");
+};
diff --git a/web/apps/space/tests/logs.test.ts b/web/apps/space/tests/logs.test.ts
new file mode 100644
index 0000000000..cfeb7e47f2
--- /dev/null
+++ b/web/apps/space/tests/logs.test.ts
@@ -0,0 +1,120 @@
+import log, { logToDisk, setLogSanitizer } from "ente-base/log";
+import { savedLogs } from "ente-base/log-web";
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import { sanitizeSpaceLog } from "../src/utils/logs";
+
+const requestID = "ed2d1157-f958-489c-aa59-25b49f560b8a";
+
+beforeEach(() => {
+ const items = new Map<string, string>();
+ vi.stubGlobal("localStorage", {
+ getItem: (key: string) => items.get(key) ?? null,
+ setItem: (key: string, value: string) => items.set(key, value),
+ removeItem: (key: string) => items.delete(key),
+ });
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ setLogSanitizer(sanitizeSpaceLog);
+});
+
+afterEach(() => {
+ setLogSanitizer((message) => message);
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+test("saves upload diagnostics without URLs, credentials, or error payloads", () => {
+ const error = new Error(
+ "HTTP 429 SPACE_UPLOAD_LIMIT_REACHED at https://api.test/spaces/private-space?token=secret-token [email protected] caption=Family birthday",
+ );
+ error.stack = `Error: ${error.message}\n at /Users/Alice/holiday.jpg:4:8`;
+ log.error(
+ `Space post upload failed ${JSON.stringify({ requestId: requestID, stage: "upload-video", itemIndex: 2, itemCount: 3, bytes: 4096 })}`,
+ error,
+ );
+ const expected = `[error] Space post upload failed request=${requestID} stage=upload-video itemIndex=2 itemCount=3 bytes=4096 status=429 code=SPACE_UPLOAD_LIMIT_REACHED`;
+ const entries = JSON.parse(localStorage.getItem("logs")!) as {
+ logs: { logLine: string }[];
+ };
+ expect(entries.logs.map((entry) => entry.logLine)).toEqual([expected]);
+ expect(savedLogs(sanitizeSpaceLog).split("] ").slice(1).join("] ")).toBe(
+ expected,
+ );
+});
+
+test.each([
+ "[info] Profile Alice Example [email protected] +1-202-555-0100 uid 12345",
+ "[warn] [rust] ente_space::client::profiles: Space profile private-space fell back to public fields: private payload",
+ "[info] Starting ente-space-web uid 12345",
+ "[error] Unhandled error: private message with a caption and auth token\n at https://space.test/alice?token=secret",
+ "[info] [wasm] ffmpeg command failed: /Users/Alice/private-video.mp4",
+])("does not retain arbitrary personal data in %s", (message) => {
+ logToDisk(message);
+ expect(savedLogs()).not.toMatch(
+ /Alice|alice|example\.test|202-555|12345|private|secret|https:/,
+ );
+});
+
+test("filters legacy entries and unexpected records again on download", () => {
+ localStorage.setItem(
+ "logs",
+ JSON.stringify({
+ logs: [
+ {
+ timestamp: 0,
+ logLine:
+ "[error] Failed to publish space post: Error: HTTP 503 at https://api.test/spaces/private-space/posts?token=secret",
+ },
+ { caption: "Family birthday" },
+ ],
+ }),
+ );
+ expect(savedLogs(sanitizeSpaceLog)).toBe(
+ "[1970-01-01T00:00:00.000Z] [error] Failed to publish space post status=503\n[info] Application event\n[info] Application event",
+ );
+});
+
+test.each([
+ [
+ `[error] Space post failed request=${requestID} attempt=2 elapsedMs=450: TypeError: Failed to fetch`,
+ "attempt=2 elapsedMs=450 reason=Failed to fetch",
+ ],
+ [
+ `[error] Space post preparation failed request=${requestID} item=2/3 type=image/jpeg bytes=500: Error: Could not decode image at /Users/Alice/photo.jpg`,
+ "item=2/3 bytes=500 type=image/jpeg reason=Could not decode image",
+ ],
+ [
+ "[warn] [rust] ente_core::http: retrying in 5s: HTTP 503 at https://bucket.test/object?signature=secret",
+ "delaySeconds=5 status=503",
+ ],
+ [
+ "[error] Space post failed: post_limit_reached: space post limit reached",
+ "code=post_limit_reached reason=space post limit reached",
+ ],
+ [
+ "[info] [wasm] ffmpeg command failed with exit code 1: -i /Users/Alice/private.mp4",
+ "exitCode=1",
+ ],
+])(
+ "keeps useful diagnostics and remains safe on repeated filtering",
+ (message, expected) => {
+ const sanitized = sanitizeSpaceLog(message);
+ expect(sanitized).toContain(expected);
+ expect(sanitizeSpaceLog(sanitized)).toBe(sanitized);
+ expect(sanitized).not.toMatch(/Alice|photo\.jpg|https:|secret/);
+ },
+);
+
+test("does not extract upload metadata from exception text", () => {
+ expect(
+ sanitizeSpaceLog(
+ `[error] Space post failed: TypeError: request=${requestID} bytes=2025550100`,
+ ),
+ ).toBe("[error] Space post failed reason=TypeError");
+});
+
+test("leaves shared logging unchanged when no Space filter is configured", () => {
+ setLogSanitizer((message) => message);
+ logToDisk("[info] A Photos diagnostic");
+ expect(savedLogs()).toContain("[info] A Photos diagnostic");
+});
diff --git a/web/apps/space/tests/post-publication.test.ts b/web/apps/space/tests/post-publication.test.ts
index 6dcba1f9b6..0733dc128f 100644
--- a/web/apps/space/tests/post-publication.test.ts
+++ b/web/apps/space/tests/post-publication.test.ts
@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({
ctx: {
generatePostKey: vi.fn(),
uploadPostPhotoAsset: vi.fn(),
+ uploadPostVideoAsset: vi.fn(),
createMediaPost: vi.fn(),
getPost: vi.fn(),
downloadPostAsset: vi.fn(),
@@ -16,6 +17,7 @@ const mocks = vi.hoisted(() => ({
release: vi.fn(),
cacheMedia: vi.fn(),
cachePost: vi.fn(),
+ logError: vi.fn(),
}));
vi.mock("services/profile", () => ({
@@ -31,7 +33,9 @@ vi.mock("services/media-cache", () => ({
`${spaceId}:${key}`,
clearSpaceMediaURLCache: vi.fn(),
}));
-vi.mock("ente-base/log", () => ({ default: { warn: vi.fn() } }));
+vi.mock("ente-base/log", () => ({
+ default: { warn: vi.fn(), error: mocks.logError },
+}));
const file = new File(["photo"], "photo.webp", { type: "image/webp" });
const images = [{ file, width: 1200, height: 800, thumbHash: "hash" }];
@@ -142,3 +146,68 @@ test("a rejected creation is still reported as a failure", async () => {
expect(session.postId).toBeUndefined();
expect(mocks.ctx.getPost).not.toHaveBeenCalled();
});
+
+test("retry keeps completed photos and the post request ID", async () => {
+ mocks.ctx.uploadPostPhotoAsset
+ .mockResolvedValueOnce({ objectKey: "first" })
+ .mockRejectedValueOnce(new Error("HTTP 503"))
+ .mockResolvedValueOnce({ objectKey: "second" });
+ const session: SpacePostUploadSession = { uploads: [] };
+ const request = {
+ images: [images[0]!, images[0]!],
+ caption: "Caption",
+ spaceId: "self",
+ session,
+ };
+ await expect(createCurrentMediaPost(request)).rejects.toThrow("HTTP 503");
+ const requestId = session.requestId;
+ expect(mocks.ctx.createMediaPost).not.toHaveBeenCalled();
+ expect(mocks.logError).toHaveBeenCalledWith(
+ expect.stringContaining('"stage":"upload-preview","itemIndex":2'),
+ expect.any(Error),
+ );
+ expect(await createCurrentMediaPost(request)).toBe(501);
+ expect(mocks.ctx.uploadPostPhotoAsset).toHaveBeenCalledTimes(3);
+ expect(mocks.ctx.generatePostKey).toHaveBeenCalledTimes(1);
+ expect(mocks.ctx.createMediaPost).toHaveBeenCalledWith(
+ "self",
+ session.key,
+ [
+ { preview: { objectKey: "first" }, video: undefined },
+ { preview: { objectKey: "second" }, video: undefined },
+ ],
+ requestId,
+ "Caption",
+ );
+});
+
+test("retry after a failed video upload reuses its cover", async () => {
+ mocks.ctx.uploadPostVideoAsset
+ .mockRejectedValueOnce(new Error("Offline"))
+ .mockResolvedValueOnce({ objectKey: "video" });
+ const session: SpacePostUploadSession = { uploads: [] };
+ const request = {
+ images: [{ ...images[0]!, video: { file, durationMs: 1000 } }],
+ caption: "",
+ spaceId: "self",
+ session,
+ };
+ await expect(createCurrentMediaPost(request)).rejects.toThrow("Offline");
+ expect(await createCurrentMediaPost(request)).toBe(501);
+ expect(mocks.ctx.uploadPostPhotoAsset).toHaveBeenCalledTimes(1);
+ expect(mocks.ctx.uploadPostVideoAsset).toHaveBeenCalledTimes(2);
+});
+
+test("retry after a lost creation response keeps the request ID and uploaded assets", async () => {
+ mocks.ctx.createMediaPost.mockRejectedValueOnce(new Error("Lost response"));
+ const session: SpacePostUploadSession = { uploads: [] };
+ const request = { images, caption: "Caption", spaceId: "self", session };
+ await expect(createCurrentMediaPost(request)).rejects.toThrow(
+ "Lost response",
+ );
+ expect(await createCurrentMediaPost(request)).toBe(501);
+ expect(mocks.ctx.uploadPostPhotoAsset).toHaveBeenCalledTimes(1);
+ expect(mocks.ctx.createMediaPost.mock.calls[1]).toEqual(
+ mocks.ctx.createMediaPost.mock.calls[0],
+ );
+});
diff --git a/web/apps/space/tests/post-upload.test.ts b/web/apps/space/tests/post-upload.test.ts
index 0b0bbc26da..987ab0c9f2 100644
--- a/web/apps/space/tests/post-upload.test.ts
+++ b/web/apps/space/tests/post-upload.test.ts
@@ -2,7 +2,10 @@ import { encryptBox, openSpaceAccountContext } from "ente-space-wasm";
import { afterEach, expect, test, vi } from "vitest";
import { CachedSpacePost } from "../src/services/post-cache";
-afterEach(() => vi.unstubAllGlobals());
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+});
const photo = (index: number) => ({
bytes: new TextEncoder().encode("RIFF\x04\x00\x00\x00WEBP"),
@@ -232,21 +235,121 @@ test("copies typed-array photo bytes without JavaScript iteration", async () =>
});
test("a failed photo upload does not publish a partial post", async () => {
+ vi.useFakeTimers();
const { ctx, calls, createPhotoPost } = await uploadFixture(true);
try {
- await expect(
+ const failure = expect(
createPhotoPost(
"test-space",
[photo(0), photo(1), photo(2)],
"Caption",
),
).rejects.toThrow();
+ await vi.runAllTimersAsync();
+ await failure;
expect(calls).not.toContain("POST /spaces/test-space/posts");
} finally {
ctx.free();
}
});
+test.each([429, 503, "network"] as const)(
+ "retries a %s transfer failure using the same bytes and upload URL",
+ async (failure) => {
+ vi.useFakeTimers();
+ const bodies: ArrayBuffer[] = [];
+ const urls: string[] = [];
+ const { ctx, calls, createPhotoPost } = await uploadFixture(
+ false,
+ (request) => {
+ if (request.method != "PUT") return undefined;
+ return (async () => {
+ urls.push(request.url);
+ bodies.push(await request.arrayBuffer());
+ if (bodies.length == 1) {
+ if (failure == "network")
+ throw new TypeError("Failed to fetch");
+ return new Response("", { status: failure });
+ }
+ return new Response("", { status: 200 });
+ })();
+ },
+ );
+ try {
+ const publication = createPhotoPost(
+ "test-space",
+ [photo(0)],
+ "Caption",
+ );
+ await vi.runAllTimersAsync();
+ await expect(publication).resolves.toMatchObject({ postId: 501 });
+ expect(urls).toHaveLength(2);
+ expect(urls[1]).toBe(urls[0]);
+ expect(bodies[1]).toEqual(bodies[0]);
+ expect(
+ calls.filter((call) => call.endsWith("/uploads/presign")),
+ ).toHaveLength(1);
+ } finally {
+ ctx.free();
+ }
+ },
+);
+
+test("retries a lost creation response with an identical request", async () => {
+ vi.useFakeTimers();
+ let lostRequest: UploadedPost | undefined;
+ let attempts = 0;
+ const { ctx, created, createPhotoPost } = await uploadFixture(
+ false,
+ (request) => {
+ if (request.method != "POST" || !request.url.endsWith("/posts"))
+ return undefined;
+ attempts += 1;
+ if (attempts > 1) return undefined;
+ return (async () => {
+ lostRequest = (await request.json()) as UploadedPost;
+ throw new TypeError("Response lost");
+ })();
+ },
+ );
+ try {
+ const publication = createPhotoPost(
+ "test-space",
+ [photo(0)],
+ "Caption",
+ );
+ await vi.runAllTimersAsync();
+ await expect(publication).resolves.toMatchObject({ postId: 501 });
+ expect(attempts).toBe(2);
+ expect(created()).toEqual(lostRequest);
+ expect(lostRequest!.clientRequestId).toBeTruthy();
+ } finally {
+ ctx.free();
+ }
+});
+
+test("preserves the unfinished upload limit code without retrying it", async () => {
+ let attempts = 0;
+ const { ctx, createPhotoPost } = await uploadFixture(false, (request) => {
+ if (!request.url.endsWith("/uploads/presign")) return undefined;
+ attempts += 1;
+ return Promise.resolve(
+ Response.json(
+ { code: "SPACE_UPLOAD_LIMIT_REACHED" },
+ { status: 429 },
+ ),
+ );
+ });
+ try {
+ await expect(
+ createPhotoPost("test-space", [photo(0)], "Caption"),
+ ).rejects.toThrow("SPACE_UPLOAD_LIMIT_REACHED");
+ expect(attempts).toBe(1);
+ } finally {
+ ctx.free();
+ }
+});
+
test.each([0, 11])("rejects %i items before publishing", async (count) => {
const { ctx, calls } = await uploadFixture();
try {
diff --git a/web/package-lock.json b/web/package-lock.json
index 0586d52138..8e519046fe 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -343,7 +343,7 @@
"@ffmpeg/ffmpeg": "0.12.15",
"@fontsource-variable/inter": "5.2.8",
"@fontsource/nunito": "5.2.7",
- "@hugeicons/core-free-icons": "1.2.1",
+ "@hugeicons/core-free-icons": "4.3.5",
"@hugeicons/react": "1.1.4",
"ente-accounts": "*",
"ente-base": "*",
@@ -360,6 +360,12 @@
"vitest": "4.1.11"
}
},
+ "apps/space/node_modules/@hugeicons/core-free-icons": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@hugeicons/core-free-icons/-/core-free-icons-4.3.5.tgz",
+ "integrity": "sha512-Sv+NjHRPnQk+yZsGCMcGznCHdTfJR9PMMOEKcJYAQU4gy90dmlc9PwdtvYOImBZIjiheMsTLL5eMn2DmHxUiUg==",
+ "license": "MIT"
+ },
"apps/space/node_modules/@hugeicons/react": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/@hugeicons/react/-/react-1.1.4.tgz",
diff --git a/web/packages/base/log-web.ts b/web/packages/base/log-web.ts
index 4858e86070..2fccc6a9f8 100644
--- a/web/packages/base/log-web.ts
+++ b/web/packages/base/log-web.ts
@@ -97,15 +97,18 @@ const logEntries = (): unknown[] => {
return o.logs;
};
-export const savedLogs = () => logEntries().map(formatEntry).join("\n");
+export const savedLogs = (sanitize?: (message: string) => string) =>
+ logEntries()
+ .map((entry) => formatEntry(entry, sanitize))
+ .join("\n");
-const formatEntry = (e: unknown) => {
+const formatEntry = (e: unknown, sanitize?: (message: string) => string) => {
if (e && typeof e == "object" && "timestamp" in e && "logLine" in e) {
const timestamp = e.timestamp;
const logLine = e.logLine;
if (typeof timestamp == "number" && typeof logLine == "string") {
- return `[${new Date(timestamp).toISOString()}] ${logLine}`;
+ return `[${new Date(timestamp).toISOString()}] ${sanitize?.(logLine) ?? logLine}`;
}
}
- return String(e);
+ return sanitize?.(String(e)) ?? String(e);
};
diff --git a/web/packages/base/log.ts b/web/packages/base/log.ts
index 6c7f4cb08c..0ad7ee3807 100644
--- a/web/packages/base/log.ts
+++ b/web/packages/base/log.ts
@@ -4,10 +4,16 @@ import { logToDisk as webLogToDisk } from "./log-web";
import { workerBridge } from "./worker/worker-bridge";
let shouldLogToDisk = true;
+let logSanitizer: ((message: string) => string) | undefined;
export const disableDiskLogs = () => (shouldLogToDisk = false);
+export const setLogSanitizer = (sanitize: (message: string) => string) => {
+ logSanitizer = sanitize;
+};
+
export const logToDisk = (message: string) => {
+ message = logSanitizer?.(message) ?? message;
const electron = globalThis.electron;
if (electron) electron.logToDisk(message);
else if (inWorker()) workerLogToDisk(message);