π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Support photo-specific replies in Space
Anand Baburajan77b4d1ddb58c
diff --git a/rust/bindings/wasm/space/src/space.rs b/rust/bindings/wasm/space/src/space.rsindex 92c531c10b..7a042aed6b 100644--- a/rust/bindings/wasm/space/src/space.rs+++ b/rust/bindings/wasm/space/src/space.rs@@ -18,6 +18,14 @@ pub enum Error {impl Error {fn name(&self) -> Option<&'static str> {match self {+ Self::Space(ente_space::Error::Http(ente_core::http::Error::Http {+ status: 404 | 410,+ ..+ })) => Some("content_unavailable"),+ Self::Space(ente_space::Error::Http(ente_core::http::Error::Http {+ status: 403,+ ..+ })) => Some("permission_denied"),Self::Space(error) if error.is_content_error() => Some("content_unavailable"),Self::Space(ente_space::Error::SpaceLimitReached) => Some("space_limit_reached"),Self::Space(ente_space::Error::SpaceSlugAlreadyExists) => {@@ -258,6 +266,7 @@ pub struct MessageResponse {recipient_space_id: String,text: String,reply_post_id: Option<i64>,+ reply_object_key: Option<String>,reply_message_id: Option<String>,liked: bool,viewer_liked: bool,@@ -286,6 +295,7 @@ struct MessageConversationActivity {message_id: Option<String>,text: Option<String>,post_id: Option<i64>,+ reply_object_key: Option<String>,post_space_id: Option<String>,is_unavailable: bool,}@@ -662,7 +672,9 @@ fn account_message_to_js(decrypted: DecryptedMessage,) -> Result<MessageResponse, Error> {message.kind = decrypted.payload.kind;- Ok(message_to_js(message, decrypted.payload.text))+ let mut response = message_to_js(message, decrypted.payload.text);+ response.reply_object_key = decrypted.payload.reply_object_key;+ Ok(response)}fn message_to_js(message: ente_space::MessageResponse, text: String) -> MessageResponse {@@ -673,6 +685,7 @@ fn message_to_js(message: ente_space::MessageResponse, text: String) -> MessageRrecipient_space_id: message.recipient_space_id,text,reply_post_id: message.reply_post_id,+ reply_object_key: None,reply_message_id: message.reply_message_id,liked: message.liked,viewer_liked: message.viewer_liked,@@ -691,6 +704,7 @@ fn unavailable_message_to_js(message: ente_space::MessageResponse) -> MessageResrecipient_space_id: message.recipient_space_id,text: String::new(),reply_post_id: message.reply_post_id,+ reply_object_key: None,reply_message_id: message.reply_message_id,liked: message.liked,viewer_liked: message.viewer_liked,@@ -784,6 +798,9 @@ async fn message_conversation_activity_to_js(.as_ref().map(|payload| payload.kind.clone()).unwrap_or_else(|| activity.kind.clone());+ let reply_object_key = payload+ .as_ref()+ .and_then(|payload| payload.reply_object_key.clone());let text = payload.map(|payload| payload.text);Ok(MessageConversationActivity {id: activity.id,@@ -794,6 +811,7 @@ async fn message_conversation_activity_to_js(message_id: activity.message_id,text,post_id: activity.post_id,+ reply_object_key,post_space_id: activity.post_space_id,is_unavailable: false,})@@ -811,6 +829,7 @@ fn unavailable_message_conversation_activity_to_js(message_id: activity.message_id,text: None,post_id: activity.post_id,+ reply_object_key: None,post_space_id: activity.post_space_id,is_unavailable: true,}@@ -1427,10 +1446,17 @@ impl SpaceAccountCtxHandle {post_space_id: String,post_id: i64,text: String,+ object_key: Option<String>,) -> Result<<MessageResponse as Tsify>::JsType, Error> {let message = self.inner- .reply_to_post(&sender_space_id, &post_space_id, post_id, &text)+ .reply_to_post(+ &sender_space_id,+ &post_space_id,+ post_id,+ &text,+ object_key.as_deref(),+ ).await?;let decrypted = self.inner@@ -1812,69 +1838,84 @@ mod tests {async fn encrypted_message_kinds_preserve_server_events_and_allow_pokes() {let (ctx, message_key, encrypted_message_key) = message_context();- for (server_kind, payload_kind, expected_kind) in [- ("regular", "regular", "regular"),- ("regular", "poke", "poke"),- ("regular", "post_like", "regular"),- ("regular", "post_reply", "regular"),- ("regular", "friend_added", "regular"),- ("regular", "unknown", "regular"),- ("post_reply", "post_reply", "post_reply"),- ("post_reply", "regular", "post_reply"),- ("post_reply", "poke", "post_reply"),- ("post_reply", "post_like", "post_reply"),- ("post_reply", "friend_added", "post_reply"),- ] {- let plaintext = format!(r#"{{"version":1,"kind":"{payload_kind}","text":"hello"}}"#);- let cipher = b64::encode(&secretbox::encrypt_combined(- plaintext.as_bytes(),- &message_key,- ));- let mut response = message("message-1", &encrypted_message_key, &cipher);- response.kind = server_kind.into();- response.reply_post_id = (server_kind == "post_reply").then_some(42);- let activity = ente_space::MessageConversationActivity {- id: "activity-1".into(),- activity_type: if server_kind == "post_reply" {- "post_reply".into()- } else {- "message".into()- },- kind: response.kind.clone(),- created_at: response.created_at.clone(),- outgoing: false,- message_id: Some(response.message_id.clone()),- sender_space_id: response.sender_space_id.clone(),- recipient_space_id: response.recipient_space_id.clone(),- message_cipher: response.message_cipher.clone(),- encrypted_message_key: response.encrypted_message_key.clone(),- reply_message_id: None,- post_id: response.reply_post_id,- post_space_id: response.reply_post_id.map(|_| "space-1".into()),- };- let converted = resilient_account_message_response_to_js(&ctx, "space-1", response)- .await- .unwrap_or_else(|error| panic!("{error}"));- let converted_activity =- resilient_message_conversation_activity_to_js(&ctx, "space-1", activity.clone())+ for reply_object_key in [None, Some("first"), Some("second")] {+ for (server_kind, payload_kind, expected_kind) in [+ ("regular", "regular", "regular"),+ ("regular", "poke", "poke"),+ ("regular", "post_like", "regular"),+ ("regular", "post_reply", "regular"),+ ("regular", "friend_added", "regular"),+ ("regular", "unknown", "regular"),+ ("post_reply", "post_reply", "post_reply"),+ ("post_reply", "regular", "post_reply"),+ ("post_reply", "poke", "post_reply"),+ ("post_reply", "post_like", "post_reply"),+ ("post_reply", "friend_added", "post_reply"),+ ] {+ let photo_field = reply_object_key+ .map(|key| format!(r#","replyObjectKey":"{key}""#))+ .unwrap_or_default();+ let plaintext = format!(+ r#"{{"version":1,"kind":"{payload_kind}","text":"hello"{photo_field}}}"#+ );+ let cipher = b64::encode(&secretbox::encrypt_combined(+ plaintext.as_bytes(),+ &message_key,+ ));+ let mut response = message("message-1", &encrypted_message_key, &cipher);+ response.kind = server_kind.into();+ response.reply_post_id = (server_kind == "post_reply").then_some(42);+ let activity = ente_space::MessageConversationActivity {+ id: "activity-1".into(),+ activity_type: if server_kind == "post_reply" {+ "post_reply".into()+ } else {+ "message".into()+ },+ kind: response.kind.clone(),+ created_at: response.created_at.clone(),+ outgoing: false,+ message_id: Some(response.message_id.clone()),+ sender_space_id: response.sender_space_id.clone(),+ recipient_space_id: response.recipient_space_id.clone(),+ message_cipher: response.message_cipher.clone(),+ encrypted_message_key: response.encrypted_message_key.clone(),+ reply_message_id: None,+ post_id: response.reply_post_id,+ post_space_id: response.reply_post_id.map(|_| "space-1".into()),+ };+ let converted = resilient_account_message_response_to_js(&ctx, "space-1", response).await.unwrap_or_else(|error| panic!("{error}"));+ let converted_activity = resilient_message_conversation_activity_to_js(+ &ctx,+ "space-1",+ activity.clone(),+ )+ .await+ .unwrap_or_else(|error| panic!("{error}"));- assert_eq!(- converted.kind, expected_kind,- "message: server={server_kind}, payload={payload_kind}"- );- assert_eq!(- converted_activity.kind, expected_kind,- "activity: server={server_kind}, payload={payload_kind}"- );- assert_eq!(converted.text, "hello");- assert_eq!(converted.reply_post_id, activity.post_id);- assert!(!converted.is_unavailable);- assert_eq!(converted_activity.text.as_deref(), Some("hello"));- assert_eq!(converted_activity.activity_type, activity.activity_type);- assert_eq!(converted_activity.post_id, activity.post_id);- assert!(!converted_activity.is_unavailable);+ assert_eq!(+ converted.kind, expected_kind,+ "message: server={server_kind}, payload={payload_kind}"+ );+ assert_eq!(+ converted_activity.kind, expected_kind,+ "activity: server={server_kind}, payload={payload_kind}"+ );+ assert_eq!(converted.reply_object_key.as_deref(), reply_object_key);+ assert_eq!(+ converted_activity.reply_object_key.as_deref(),+ reply_object_key+ );+ assert_eq!(converted.text, "hello");+ assert_eq!(converted.reply_post_id, activity.post_id);+ assert!(!converted.is_unavailable);+ assert_eq!(converted_activity.text.as_deref(), Some("hello"));+ assert_eq!(converted_activity.activity_type, activity.activity_type);+ assert_eq!(converted_activity.post_id, activity.post_id);+ assert!(!converted_activity.is_unavailable);+ }}}diff --git a/rust/crates/space/src/client/messages.rs b/rust/crates/space/src/client/messages.rsindex c2d2ee0216..159d4bdbc9 100644--- a/rust/crates/space/src/client/messages.rs+++ b/rust/crates/space/src/client/messages.rs@@ -69,6 +69,7 @@ impl AccountSpaceCtx {version: 1,kind: MESSAGE_KIND_REGULAR.to_owned(),text: text.to_owned(),+ reply_object_key: None,},None,)@@ -87,6 +88,7 @@ impl AccountSpaceCtx {version: 1,kind: MESSAGE_KIND_POKE.to_owned(),text: POKE_MESSAGE_TEXT.to_owned(),+ reply_object_key: None,},Some(MESSAGE_NOTIFICATION_KIND_POKE),)@@ -142,6 +144,7 @@ impl AccountSpaceCtx {version: 1,kind: MESSAGE_KIND_REGULAR.to_owned(),text: text.to_owned(),+ reply_object_key: None,};let request = self.message_request_for_payload(@@ -170,6 +173,7 @@ impl AccountSpaceCtx {post_space_id: &str,post_id: i64,text: &str,+ object_key: Option<&str>,) -> Result<MessageResponse> {let post = self.get_post(post_space_id, post_id, Some(sender_space_id))@@ -186,10 +190,19 @@ impl AccountSpaceCtx {"post author public key is missing".into(),));}+ if let Some(object_key) = object_key+ && !post+ .objects+ .iter()+ .any(|object| object.object_key == object_key)+ {+ return Err(Error::InvalidInput("photo does not belong to post".into()));+ }let payload = MessagePayload {version: 1,kind: MESSAGE_KIND_POST_REPLY.to_owned(),text: text.to_owned(),+ reply_object_key: object_key.map(str::to_owned),};let request = self.message_request_for_payload(diff --git a/rust/crates/space/src/client/tests.rs b/rust/crates/space/src/client/tests.rsindex 6d656061f2..d68066ef9e 100644--- a/rust/crates/space/src/client/tests.rs+++ b/rust/crates/space/src/client/tests.rs@@ -1560,6 +1560,7 @@ fn message_payload_limits_reject_oversized_text_and_payload() {version: 1,kind: MESSAGE_KIND_REGULAR.to_owned(),text: "hello".to_owned(),+ reply_object_key: None,};let valid_plaintext = serde_json::to_vec(&valid).expect("valid payload json");validate_message_payload(&valid, valid_plaintext.len())@@ -1579,6 +1580,83 @@ fn message_payload_limits_reject_oversized_text_and_payload() {assert!(err.to_string().contains("payload must be"));}+#[tokio::test]+async fn post_replies_encrypt_photo_references_and_reject_other_photos() {+ let mut server = Server::new_async().await;+ let ctx = test_account_ctx(&server.url());+ let (public_key, _) = generate_keypair().unwrap();+ let owned = server+ .mock("GET", "/account/space")+ .with_body("[]")+ .create_async()+ .await;+ let post = server.mock("GET", "/spaces/space_friend/posts/42")+ .match_query(Matcher::UrlEncoded("viewerSpaceId".into(), "space_owner_main".into()))+ .with_body(json!({+ "postId": 42,+ "spaceId": "space_friend",+ "spaceSlug": "friend",+ "author": { "spaceId": "space_friend", "spaceSlug": "friend", "publicKey": b64::encode(&public_key) },+ "encryptedPostKey": "unused",+ "keyVersion": 1,+ "viewerLiked": false,+ "createdAt": "2026-09-19T00:00:00Z",+ "objects": [+ { "objectKey": "first", "metadataCipher": "unused" },+ { "objectKey": "second", "metadataCipher": "unused" }+ ]+ }).to_string())+ .expect(4).create_async().await;+ let reply = server+ .mock("POST", "/spaces/space_owner_main/posts/42/reply")+ .with_body_from_request(|request| {+ let body: serde_json::Value = serde_json::from_slice(request.body().unwrap()).unwrap();+ assert!(body.get("replyObjectKey").is_none());+ json!({+ "messageId": "reply",+ "kind": "post_reply",+ "senderSpaceId": "space_owner_main",+ "recipientSpaceId": "space_friend",+ "replyPostId": 42,+ "messageCipher": body["messageCipher"],+ "encryptedMessageKey": body["senderEncryptedMessageKey"],+ "createdAt": "2026-09-19T00:00:00Z",+ "updatedAt": "2026-09-19T00:00:00Z"+ })+ .to_string()+ .into_bytes()+ })+ .expect(3)+ .create_async()+ .await;+ for object_key in [None, Some("first"), Some("second")] {+ let response = ctx+ .reply_to_post("space_owner_main", "space_friend", 42, "Coo", object_key)+ .await+ .unwrap();+ let decrypted = ctx+ .decrypt_message("space_owner_main", &response)+ .await+ .unwrap();+ assert_eq!(decrypted.payload.text, "Coo");+ assert_eq!(decrypted.payload.reply_object_key.as_deref(), object_key);+ }+ let error = ctx+ .reply_to_post(+ "space_owner_main",+ "space_friend",+ 42,+ "Coo",+ Some("unrelated"),+ )+ .await+ .unwrap_err();+ assert!(matches!(error, Error::InvalidInput(_)));+ owned.assert_async().await;+ post.assert_async().await;+ reply.assert_async().await;+}+#[tokio::test]async fn list_space_friends_uses_space_friends_endpoint() {let mut server = Server::new_async().await;diff --git a/rust/crates/space/src/models.rs b/rust/crates/space/src/models.rsindex b2fd8a7744..6bf2c34653 100644--- a/rust/crates/space/src/models.rs+++ b/rust/crates/space/src/models.rs@@ -82,6 +82,8 @@ pub struct MessagePayload {pub version: i32,pub kind: String,pub text: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reply_object_key: Option<String>,}#[derive(Clone)]diff --git a/rust/crates/space/tests/space.rs b/rust/crates/space/tests/space.rsindex d1b45b2a6e..d5e0c5ae4f 100644--- a/rust/crates/space/tests/space.rs+++ b/rust/crates/space/tests/space.rs@@ -520,6 +520,7 @@ async fn space_unfriend_revokes_reciprocal_account_access_suite(endpoint: &str)&owner_space.space_id,post_id,"should fail",+ None,).await,403,diff --git a/web/apps/space/src/components/AuthenticatedFriendProfile.tsx b/web/apps/space/src/components/AuthenticatedFriendProfile.tsxindex 088de7c0b2..c8ab8c7fba 100644--- a/web/apps/space/src/components/AuthenticatedFriendProfile.tsx+++ b/web/apps/space/src/components/AuthenticatedFriendProfile.tsx@@ -172,8 +172,14 @@ export const AuthenticatedFriendProfile: React.FC<}onOpenProfileCover={() => setOpenProfileImage("cover")}onOpenProfilePhoto={() => setOpenProfileImage("avatar")}- onReplyToPost={(postSpaceId, postId, text) =>- replyToCurrentPost(actorSpaceId, postSpaceId, postId, text)+ onReplyToPost={(postSpaceId, postId, text, objectKey) =>+ replyToCurrentPost(+ actorSpaceId,+ postSpaceId,+ postId,+ text,+ objectKey,+ )}onSetPostLiked={async (postId, liked) => {const previousLiked =diff --git a/web/apps/space/src/components/FileViewer.tsx b/web/apps/space/src/components/FileViewer.tsxindex 72f112dc30..40b5c49cdd 100644--- a/web/apps/space/src/components/FileViewer.tsx+++ b/web/apps/space/src/components/FileViewer.tsx@@ -151,12 +151,14 @@ interface SpaceFileViewerProps {spaceId: string,postId: number,text: string,+ objectKey: string,) => Promise<void>;onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;onUpdatePostCaption?: (postId: number, caption: string) => Promise<void>;onPhotoIndexChange?: (index: number) => void;photo: SpaceViewerPhoto;photoIndex?: number;+ initialPhotoIndex?: number;photos?: SpaceViewerPhoto[];focusReplyOnOpen?: boolean;postActionMode?: SpaceViewerPostActionMode;@@ -351,10 +353,12 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({onPhotoIndexChange,photo,photoIndex,+ initialPhotoIndex = 0,photos,postActionMode = "like-only",}) => {- const [localPhotoIndex, setLocalPhotoIndex] = React.useState(0);+ const [localPhotoIndex, setLocalPhotoIndex] =+ React.useState(initialPhotoIndex);const [loadedPhotoURLs, setLoadedPhotoURLs] = React.useState<Record<string, string>>({});@@ -403,6 +407,9 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({const postPhotoCount = activePhoto.postPhotoCount ?? 1;const postPhotoIndex = activePhoto.postPhotoIndex ?? 0;const activePhotoKey = photoKey(activePhoto);+ const activeReplyKey = `${activePhoto.spaceId}:${activePhoto.postId}:${activePhoto.imageAsset?.objectKey}`;+ const activeReplyKeyRef = React.useRef(activeReplyKey);+ activeReplyKeyRef.current = activeReplyKey;const activePostKey = `${activePhoto.spaceId ?? ""}:${activePhoto.postId ?? ""}`;const hasPhotoLoadError = Boolean(photoLoadErrors[activePhotoKey]);const canUpdatePostCaption =@@ -446,8 +453,19 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({const replyDraftsRef = React.useRef(new Map<string, string>());const [isReplyFocused, setIsReplyFocused] =React.useState(focusReplyOnOpen);- const [replyActionPhase, setReplyActionPhase] =- React.useState<SpaceActionPhase | null>(null);+ const [replyPhases, setReplyPhases] = React.useState<+ Record<string, SpaceActionPhase | null>+ >({});+ const replyActionPhase = replyPhases[activeReplyKey] ?? null;+ const setReplyActionPhase = React.useCallback(+ (phase: SpaceActionPhase | null) => {+ setReplyPhases((phases) => ({+ ...phases,+ [activeReplyKey]: phase,+ }));+ },+ [activeReplyKey],+ );const [addFriendSheetOpen, setAddFriendSheetOpen] = React.useState(false);const [addFriendIntent, setAddFriendIntent] =React.useState<SpaceInviteIntent>("like");@@ -501,7 +519,10 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({const canReplyToPost = Boolean(!isDraftPost &&(canAddFriendForPostAction ||- (activePhoto.spaceId && activePhoto.postId && onReplyToPost)),+ (activePhoto.spaceId &&+ activePhoto.postId &&+ activePhoto.imageAsset &&+ onReplyToPost)),);const isReplyMode =canReplyToPost &&@@ -764,11 +785,13 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({!canSendReply ||!activePhoto.spaceId ||!activePhoto.postId ||+ !activePhoto.imageAsset ||!onReplyToPost) {return;}+ const objectKey = activePhoto.imageAsset.objectKey;setReplyActionPhase("busy");void (async () => {try {@@ -776,9 +799,11 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({activePhoto.spaceId!,activePhoto.postId!,text,+ objectKey,);- replyDraftsRef.current.delete(activePostKey);- setReplyText("");+ replyDraftsRef.current.delete(activeReplyKey);+ if (activeReplyKeyRef.current == activeReplyKey)+ setReplyText("");setReplyActionPhase("done");} catch (error) {log.error("Failed to send post reply", error);@@ -869,7 +894,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({}, viewerActionDoneDurationMs);return () => window.clearTimeout(timeoutID);- }, [replyActionPhase]);+ }, [replyActionPhase, setReplyActionPhase]);React.useEffect(() => {if (isDraftPost || isCaptionEditingRef.current) return;@@ -886,10 +911,12 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({setCaptionUpdateActionPhase(null);setHasCaptionUpdateError(false);setIsCaptionEditing(false);- setReplyText(replyDraftsRef.current.get(activePostKey) ?? "");+ }, [activePostKey]);++ React.useLayoutEffect(() => {+ setReplyText(replyDraftsRef.current.get(activeReplyKey) ?? "");setIsReplyFocused(focusReplyOnOpen && canReplyToPost);- setReplyActionPhase(null);- }, [activePostKey, canReplyToPost, focusReplyOnOpen]);+ }, [activeReplyKey, canReplyToPost, focusReplyOnOpen]);React.useEffect(() => {setPhotoLikePopID(0);@@ -2151,7 +2178,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({nextText;setReplyText(nextText);replyDraftsRef.current.set(- activePostKey,+ activeReplyKey,nextText,);},diff --git a/web/apps/space/src/components/MessagesPage.tsx b/web/apps/space/src/components/MessagesPage.tsxindex 82efb26d9b..1578116d46 100644--- a/web/apps/space/src/components/MessagesPage.tsx+++ b/web/apps/space/src/components/MessagesPage.tsx@@ -692,7 +692,11 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({}}onOpenQuotePost={(quote) =>void router.push(- spaceRoutes.post(quote.spaceId, quote.postId),+ spaceRoutes.post(+ quote.spaceId,+ quote.postId,+ quote.objectKey,+ ),)}onOpenThread={openConversation}diff --git a/web/apps/space/src/components/PostReplyControls.tsx b/web/apps/space/src/components/PostReplyControls.tsxindex 480e377075..4f6d404e73 100644--- a/web/apps/space/src/components/PostReplyControls.tsx+++ b/web/apps/space/src/components/PostReplyControls.tsx@@ -101,7 +101,7 @@ export const SpacePostReplyControls: React.FC<SpacePostReplyControlsProps> = ({<Boxref={replyInputRef}component="textarea"- aria-label="Reply to post"+ aria-label="Reply to photo"disabled={disabled || replyActionPhase != null}placeholder="Reply..."rows={1}diff --git a/web/apps/space/src/pages/app/index.tsx b/web/apps/space/src/pages/app/index.tsxindex bbda5dcf02..2d1c9b4b22 100644--- a/web/apps/space/src/pages/app/index.tsx+++ b/web/apps/space/src/pages/app/index.tsx@@ -409,12 +409,14 @@ const Page: React.FC = () => {postSpaceId: string,postId: number,text: string,+ objectKey: string,) =>replyToCurrentPost(actorSpaceId,postSpaceId,postId,text,+ objectKey,))(profile.spaceId): undefineddiff --git a/web/apps/space/src/pages/app/posts/[spaceId]/[postId].tsx b/web/apps/space/src/pages/app/posts/[spaceId]/[postId].tsxindex 0699860b17..c5db3d7874 100644--- a/web/apps/space/src/pages/app/posts/[spaceId]/[postId].tsx+++ b/web/apps/space/src/pages/app/posts/[spaceId]/[postId].tsx@@ -14,7 +14,7 @@ import { useSpaceAppState } from "state/app-state";import { spaceAppBackgroundColor } from "styles/colors";import { viewerPhotosFromPost } from "utils/post-photos";import { hasPreviousSpaceRoute, useSpaceRouter } from "utils/route-transitions";-import { spaceRoutes } from "utils/routes";+import { postPhotoIdFromObjectKey, spaceRoutes } from "utils/routes";const postBackground = "#000000";@@ -70,6 +70,12 @@ const Page: React.FC = () => {const spaceId =valueFromQuery(router.query.spaceId) ?? pathParams.spaceId ?? "";const postId = postIdFromQuery(router.query.postId) ?? pathParams.postId;+ const photoId =+ valueFromQuery(router.query.photo) ??+ (typeof window == "undefined"+ ? undefined+ : (new URLSearchParams(window.location.search).get("photo") ??+ undefined));const [post, setPost] = React.useState<SpacePost | null>(null);const [postLoadError, setPostLoadError] = React.useState<string>();const [isPostLoading, setIsPostLoading] = React.useState(false);@@ -168,13 +174,33 @@ const Page: React.FC = () => {);}+ const photos = viewerPhotosFromPost(viewerPhotoFromPost(post));+ const photoIndex =+ photoId === undefined+ ? 0+ : photos.findIndex(+ (photo) =>+ photo.imageAsset &&+ postPhotoIdFromObjectKey(photo.imageAsset.objectKey) ==+ photoId,+ );+ if (photoIndex < 0) {+ return (+ <SpaceRouteFallback+ background={spaceAppBackgroundColor}+ message="Photo unavailable."+ />+ );+ }+return (<><SpacePageMeta themeColor={postBackground} /><SpaceFileViewer- key={post.postId}+ key={`${post.postId}:${photoId ?? ""}`}photo={viewerPhotoFromPost(post)}- photos={viewerPhotosFromPost(viewerPhotoFromPost(post))}+ photos={photos}+ initialPhotoIndex={photoIndex}onLoadPhoto={loadCurrentSpacePostAssetURL}postActionMode={isOwnPost ? "hidden" : "like-only"}onClose={closePost}@@ -182,12 +208,13 @@ const Page: React.FC = () => {onReplyToPost={isOwnPost? undefined- : (postSpaceId, nextPostId, text) =>+ : (postSpaceId, nextPostId, text, objectKey) =>replyToCurrentPost(actorSpaceId,postSpaceId,nextPostId,text,+ objectKey,)}onSetPostLiked={async (nextPostId, liked) => {diff --git a/web/apps/space/src/screens/HomeScreen.tsx b/web/apps/space/src/screens/HomeScreen.tsxindex 03c282bd3a..c43c0a5437 100644--- a/web/apps/space/src/screens/HomeScreen.tsx+++ b/web/apps/space/src/screens/HomeScreen.tsx@@ -116,6 +116,7 @@ interface HomeScreenProps {postSpaceId: string,postId: number,text: string,+ objectKey: string,) => Promise<void>;onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;onUpdatePostCaption?: (postId: number, caption: string) => Promise<void>;@@ -727,7 +728,7 @@ const FeedPhoto: React.FC<{}}/>)}- {!isPostUnavailable && !isPhotoReady && thumbHashDataURL ? (+ {!isPostUnavailable && thumbHashDataURL ? (<Boxcomponent="img"alt=""diff --git a/web/apps/space/src/screens/MessagesScreen.tsx b/web/apps/space/src/screens/MessagesScreen.tsxindex a501421dc2..33b16321cc 100644--- a/web/apps/space/src/screens/MessagesScreen.tsx+++ b/web/apps/space/src/screens/MessagesScreen.tsx@@ -44,6 +44,8 @@ import {import { spaceTouchTargetSize } from "styles/touch-targets";import { firstNameFrom } from "utils/display";import { clampSpaceMessageText } from "utils/message-limits";+import { spacePostDeletedEvent } from "utils/post-events";+import { postQuoteErrorState, postQuoteKey } from "utils/post-quote";const green = "#08C225";const textBase = spaceText;@@ -300,9 +302,6 @@ const conversationId = (conversation: SpaceMessageConversation) =>? conversation.latestActivity.id: (conversation.friend.spaceId ?? conversation.friend.id);-const activityPostKey = (post: SpaceMessageActivityPost) =>- `${post.spaceId}:${post.postId}`;-const conversationTimeSections = (conversations: SpaceMessageConversation[],newConversationIds: string[],@@ -426,7 +425,7 @@ const MessageTimeSeparator: React.FC<{ timestampMs: number }> = ({fontWeight: 500,lineHeight: "16px",listStyle: "none",- py: "14px",+ py: "32px",textAlign: "center",}}>@@ -471,16 +470,17 @@ const ConversationListItem: React.FC<{const post = conversation.latestActivity.post;const postThumbnailUrl = (activityPost ?? post)?.imageUrl;const showPostThumbnailSlot = Boolean(post);- const isPostThumbnailUnavailable =- Boolean(post?.isDeleted) ||- Boolean(activityPost && !activityPost.imageUrl);+ const isPostThumbnailUnavailable = Boolean(+ (activityPost ?? post)?.isUnavailable,+ );+ const hasPostThumbnailLoadError = Boolean(activityPost?.hasLoadError);const unreadCount = conversation.unreadCount;const showPostSomething = shouldShowPostSomething(conversation,latestPostCreatedAtMs,);React.useEffect(() => {- if (!post || post.isDeleted || post.imageUrl || activityPost) {+ if (!post || post.isUnavailable || post.imageUrl || activityPost) {return;}onLoadActivityPost?.(post);@@ -489,7 +489,7 @@ const ConversationListItem: React.FC<{onLoadActivityPost,post,post?.imageUrl,- post?.isDeleted,+ post?.isUnavailable,]);const confirmFriendRequest = () => {void onConfirmFriendRequest(conversation).catch((error: unknown) =>@@ -731,7 +731,9 @@ const ConversationListItem: React.FC<{aria-label={isPostThumbnailUnavailable? "Post image unavailable"- : "Loading post image"+ : hasPostThumbnailLoadError+ ? "Couldn't load post image"+ : "Loading post image"}role="img"sx={{@@ -895,7 +897,7 @@ const ConversationSection: React.FC<{activityPost={conversation.latestActivity.post? activityPostsByKey[- activityPostKey(+ postQuoteKey(conversation.latestActivity.post,)]@@ -1268,35 +1270,53 @@ const PostQuotePreview: React.FC<{onOpenQuotePost,}) => {const quote = message.quote;- const imageUrl = quote?.imageUrl ?? activityPost?.imageUrl;- const photoCount = quote?.photoCount ?? activityPost?.photoCount ?? 1;- const isUnavailable =- !quote ||- quote.isUnavailable == true ||- (!imageUrl &&- (activityPost != undefined || onLoadActivityPost == undefined));+ const preview = activityPost ?? quote;+ const isUnavailable = !quote || Boolean(preview?.isUnavailable);+ const hasLoadError = Boolean(preview?.hasLoadError);+ const imageUrl =+ isUnavailable || hasLoadError ? undefined : preview?.imageUrl;+ const photoCount = preview?.photoCount ?? 1;const loadedQuote =- quote && imageUrl && !isUnavailable- ? { ...quote, imageUrl, photoCount }- : undefined;- const isLoading = quote != undefined && !imageUrl && !isUnavailable;+ quote && imageUrl ? { ...quote, ...preview, imageUrl } : undefined;+ const isLoading = Boolean(+ quote && !imageUrl && !isUnavailable && !hasLoadError,+ );const canOpen = Boolean(loadedQuote);+ const canRetry = hasLoadError && Boolean(onLoadActivityPost);+ const unavailableLabel =+ quote?.objectKey !== undefined && preview?.photoCount !== undefined+ ? "Photo unavailable"+ : "Post unavailable";React.useEffect(() => {- if (!quote || imageUrl || isUnavailable) return;+ if (!quote || activityPost || imageUrl || isUnavailable || hasLoadError)+ return;onLoadActivityPost?.(quote);- }, [imageUrl, isUnavailable, onLoadActivityPost, quote]);+ }, [+ activityPost,+ hasLoadError,+ imageUrl,+ isUnavailable,+ onLoadActivityPost,+ quote,+ ]);return (<QuoteFrame isOwn={isOwn} mb={mb}><Box- component={canOpen ? "button" : "div"}- type={canOpen ? "button" : undefined}- aria-label={canOpen ? "Open quoted post" : undefined}+ component={canOpen || canRetry ? "button" : "div"}+ type={canOpen || canRetry ? "button" : undefined}+ aria-label={+ canOpen+ ? "Open quoted photo"+ : canRetry+ ? "Retry loading photo"+ : undefined+ }onClick={(event: React.MouseEvent) => {- if (!loadedQuote) return;event.stopPropagation();- onOpenQuotePost(loadedQuote);+ if (canRetry && quote) onLoadActivityPost?.(quote);+ else if (loadedQuote) onOpenQuotePost(loadedQuote);}}sx={{appearance: "none",@@ -1304,7 +1324,7 @@ const PostQuotePreview: React.FC<{border: 0,borderRadius: "28px",color: "inherit",- cursor: canOpen ? "pointer" : "default",+ cursor: canOpen || canRetry ? "pointer" : "default",display: "inline-flex",font: "inherit",overflow: "hidden",@@ -1334,14 +1354,18 @@ const PostQuotePreview: React.FC<{role="img"aria-label={isLoading- ? "Loading post image"- : "Post unavailable"+ ? "Loading photo"+ : hasLoadError+ ? "Couldn't load photo"+ : unavailableLabel}sx={{alignItems: "center",bgcolor: incomingQuoteBubble,color: incomingQuoteText,display: "flex",+ flexDirection: "column",+ gap: "8px",fontFamily: '"Inter Variable", Inter, sans-serif',fontSize: 12,fontWeight: 700,@@ -1360,6 +1384,13 @@ const PostQuotePreview: React.FC<{strokeWidth={1.5}/>)}+ {isUnavailable ? (+ unavailableLabel+ ) : hasLoadError ? (+ "Couldn't load photo. Tap to retry."+ ) : (+ <SpaceLoadingSpinner />+ )}</Box>)}{canOpen && <SpacePostPhotosBadge count={photoCount} />}@@ -1754,44 +1785,76 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({() => conversationTimeSections(conversations, newConversationIds),[conversations, newConversationIds],);+ const previewGenerationRef = React.useRef(0);+ React.useEffect(() => {+ const cancelPreviewLoads = () => {+ previewGenerationRef.current++;+ activityPostLoadsInFlightRef.current.clear();+ };+ const invalidatePreviews = () => {+ cancelPreviewLoads();+ setActivityPostsByKey({});+ };+ const onVisibilityChange = () => {+ if (document.visibilityState == "visible") invalidatePreviews();+ };+ invalidatePreviews();+ window.addEventListener("focus", invalidatePreviews);+ window.addEventListener("online", invalidatePreviews);+ window.addEventListener(spacePostDeletedEvent, invalidatePreviews);+ document.addEventListener("visibilitychange", onVisibilityChange);+ return () => {+ cancelPreviewLoads();+ window.removeEventListener("focus", invalidatePreviews);+ window.removeEventListener("online", invalidatePreviews);+ window.removeEventListener(+ spacePostDeletedEvent,+ invalidatePreviews,+ );+ document.removeEventListener(+ "visibilitychange",+ onVisibilityChange,+ );+ };+ }, [selectedFriend?.id]);const loadActivityPost = React.useCallback((post: SpaceMessageActivityPost) => {if (!onLoadActivityPost) return;- const key = activityPostKey(post);+ const key = postQuoteKey(post);+ const cached = activityPostsByKey[key];if (- activityPostsByKey[key] ||+ (cached && !cached.hasLoadError) ||activityPostLoadsInFlightRef.current.has(key)- ) {+ )return;- }+ const generation = previewGenerationRef.current;activityPostLoadsInFlightRef.current.add(key);- void onLoadActivityPost(post)- .then((loadedPost) => {- setActivityPostsByKey((currentPosts) =>- currentPosts[key]- ? currentPosts- : {- ...currentPosts,- [key]: loadedPost ?? {- ...post,- isDeleted: true,- },- },- );- })+ const target = {+ spaceId: post.spaceId,+ postId: post.postId,+ objectKey: post.objectKey,+ };+ setActivityPostsByKey((posts) => ({ ...posts, [key]: target }));+ const storePreview = (preview: SpaceMessageActivityPost) => {+ if (generation != previewGenerationRef.current) return;+ setActivityPostsByKey((posts) => ({+ ...posts,+ [key]: preview,+ }));+ };+ void onLoadActivityPost(target)+ .then((loadedPost) =>+ storePreview(+ loadedPost ?? { ...target, isUnavailable: true },+ ),+ ).catch((error: unknown) => {log.warn("Failed to load message activity post", error);- setActivityPostsByKey((currentPosts) =>- currentPosts[key]- ? currentPosts- : {- ...currentPosts,- [key]: { ...post, isDeleted: true },- },- );+ storePreview({ ...target, ...postQuoteErrorState(error) });}).finally(() => {- activityPostLoadsInFlightRef.current.delete(key);+ if (generation == previewGenerationRef.current)+ activityPostLoadsInFlightRef.current.delete(key);});},[activityPostsByKey, onLoadActivityPost],@@ -2459,7 +2522,7 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({activityPost={message.quote? activityPostsByKey[- activityPostKey(+ postQuoteKey(message.quote,)]diff --git a/web/apps/space/src/screens/ProfileScreen.tsx b/web/apps/space/src/screens/ProfileScreen.tsxindex 2425880adf..47fde48e47 100644--- a/web/apps/space/src/screens/ProfileScreen.tsx+++ b/web/apps/space/src/screens/ProfileScreen.tsx@@ -512,6 +512,7 @@ interface ProfileScreenProps {postSpaceId: string,postId: number,text: string,+ objectKey: string,) => Promise<void>;onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;onUnfriend?: () => Promise<void> | void;diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.tsindex ea97e51e58..431a41ea82 100644--- a/web/apps/space/src/services/space.ts+++ b/web/apps/space/src/services/space.ts@@ -43,6 +43,8 @@ import {spaceProfileTextField,} from "services/profile-payload";import { normalizeSpaceMessageText } from "utils/message-limits";+import { spacePostDeletedEvent } from "utils/post-events";+import { postQuoteErrorState, postQuotePhotoIndex } from "utils/post-quote";export { clearSpaceMediaURLCache } from "services/media-cache";@@ -144,6 +146,8 @@ export type SpaceMessageKind = MessageResponse["kind"];export interface SpaceMessageQuote {imageUrl?: string;isUnavailable?: boolean;+ hasLoadError?: boolean;+ objectKey?: string;photoCount?: number;postId: number;spaceId: string;@@ -159,6 +163,7 @@ export interface SpaceMessage {recipient: FriendProfile;replyMessageId?: string;replyPostId?: number;+ replyObjectKey?: string;sender: FriendProfile;text: string;updatedAtMs: number;@@ -168,13 +173,7 @@ export interface SpaceMessage {export type SpaceMessageActivityType = MessageConversationActivity["type"];-export interface SpaceMessageActivityPost {- imageUrl?: string;- isDeleted?: boolean;- photoCount?: number;- postId: number;- spaceId: string;-}+export type SpaceMessageActivityPost = SpaceMessageQuote;export interface SpaceMessageActivity {createdAtMs: number;@@ -634,14 +633,18 @@ const messageQuoteFromPostResponse = async (post: PostResponse,includeImage: boolean,viewerSpaceId?: string,+ objectKey?: string,): Promise<SpaceMessageQuote> => {- const object = firstObject(post);+ const photoIndex = postQuotePhotoIndex(post.objects, objectKey);+ const object = post.objects[photoIndex];const quote: SpaceMessageQuote = {+ objectKey,photoCount: post.objects.length,postId: post.postId,spaceId: post.spaceId,};- if (!includeImage || !object) return quote;+ if (!object || post.isUnavailable) return { ...quote, isUnavailable: true };+ if (!includeImage) return quote;try {const imageUrl = await accountPostAssetURL(@@ -657,7 +660,7 @@ const messageQuoteFromPostResponse = async (quote.imageUrl = imageUrl;} catch (error) {log.warn("Failed to load quoted post image", error);- quote.isUnavailable = true;+ Object.assign(quote, postQuoteErrorState(error));}return quote;};@@ -673,6 +676,7 @@ const messageQuoteFromReplyPost = async (}const fallbackQuote: SpaceMessageQuote = {+ objectKey: message.replyObjectKey,postId: message.replyPostId,spaceId: message.recipientSpaceId,};@@ -689,10 +693,11 @@ const messageQuoteFromReplyPost = async (post,includeImage,viewerSpaceId,+ message.replyObjectKey,);} catch (error) {log.warn("Failed to load quoted post", error);- return { ...fallbackQuote, isUnavailable: true };+ return { ...fallbackQuote, ...postQuoteErrorState(error) };}};@@ -736,6 +741,7 @@ const messageFromSpaceMessage = async (recipient,replyMessageId: message.replyMessageId,replyPostId: message.replyPostId,+ replyObjectKey: message.replyObjectKey,sender,text: message.text,updatedAtMs: timestampMsFromSpaceDate(message.updatedAt),@@ -749,14 +755,17 @@ const messageActivityPostFromActivity = (if (typeof activity.postId != "number" || !activity.postSpaceId) {return undefined;}- return { postId: activity.postId, spaceId: activity.postSpaceId };+ return {+ postId: activity.postId,+ spaceId: activity.postSpaceId,+ objectKey: activity.replyObjectKey,+ };};export const loadCurrentMessageActivityPostPreview = async (post: SpaceMessageActivityPost,viewerSpaceId?: string,): Promise<SpaceMessageActivityPost | undefined> => {- if (post.isDeleted) return post;const ctx = await ensureCurrentSpaceContext();try {const response = await ctx.getPost(@@ -764,18 +773,13 @@ export const loadCurrentMessageActivityPostPreview = async (BigInt(post.postId),viewerSpaceId ?? null,);- const quote = await messageQuoteFromPostResponse(+ return await messageQuoteFromPostResponse(ctx,response,true,viewerSpaceId,+ post.objectKey,);- return {- ...post,- imageUrl: quote.imageUrl,- isDeleted: quote.isUnavailable,- photoCount: quote.photoCount,- };} finally {releaseCurrentSpaceContext(ctx);}@@ -1212,6 +1216,7 @@ export const replyToCurrentPost = async (postSpaceId: string,postId: number,text: string,+ objectKey: string,) => {const messageText = normalizeSpaceMessageText(text);const ctx = await ensureCurrentSpaceContext();@@ -1221,6 +1226,7 @@ export const replyToCurrentPost = async (postSpaceId,BigInt(postId),messageText,+ objectKey,);} finally {releaseCurrentSpaceContext(ctx);@@ -1500,6 +1506,7 @@ export const deleteCurrentPost = async (spaceId: string, postId: number) => {const ctx = await ensureCurrentSpaceContext();try {await ctx.deletePost(spaceId, BigInt(postId));+ window.dispatchEvent(new Event(spacePostDeletedEvent));await removeCachedSpaceFeedPost(spaceId, postId);} finally {releaseCurrentSpaceContext(ctx);diff --git a/web/apps/space/src/utils/post-events.ts b/web/apps/space/src/utils/post-events.tsnew file mode 100644index 0000000000..ec05bc1369--- /dev/null+++ b/web/apps/space/src/utils/post-events.ts@@ -0,0 +1 @@+export const spacePostDeletedEvent = "space-post-deleted";diff --git a/web/apps/space/src/utils/post-quote.ts b/web/apps/space/src/utils/post-quote.tsnew file mode 100644index 0000000000..fef0733fd8--- /dev/null+++ b/web/apps/space/src/utils/post-quote.ts@@ -0,0 +1,23 @@+import { isNamedError } from "ente-base/error";++export const postQuotePhotoIndex = (+ photos: { objectKey: string }[],+ objectKey?: string,+) =>+ objectKey === undefined+ ? photos.length+ ? 0+ : -1+ : photos.findIndex((photo) => photo.objectKey == objectKey);++export const postQuoteKey = (post: {+ spaceId: string;+ postId: number;+ objectKey?: string;+}) => JSON.stringify([post.spaceId, post.postId, post.objectKey ?? null]);++export const postQuoteErrorState = (error: unknown) =>+ isNamedError(error, "content_unavailable") ||+ isNamedError(error, "permission_denied")+ ? { isUnavailable: true }+ : { hasLoadError: true };diff --git a/web/apps/space/src/utils/routes.ts b/web/apps/space/src/utils/routes.tsindex 0fbe90c90b..96a430f7f3 100644--- a/web/apps/space/src/utils/routes.ts+++ b/web/apps/space/src/utils/routes.ts@@ -10,6 +10,9 @@ const routeWithProfileImageFlowSource = (source?: ProfileImageFlowSource,) => (source == "settings" ? `${route}?from=settings` : route);+export const postPhotoIdFromObjectKey = (objectKey: string) =>+ objectKey.slice(objectKey.lastIndexOf("/") + 1);+export const spaceRoutes = {friend: (username: string) => `/${encodeURIComponent(username)}`,friendPage: "/profile-link",@@ -22,8 +25,8 @@ export const spaceRoutes = {onboarding: "/",passkeysFinish: "/passkeys/finish",passkeysVerify: "/passkeys/verify",- post: (spaceId: string, postId: number) =>- `/app/posts/${encodeURIComponent(spaceId)}/${encodeURIComponent(String(postId))}`,+ post: (spaceId: string, postId: number, objectKey?: string) =>+ `/app/posts/${encodeURIComponent(spaceId)}/${encodeURIComponent(String(postId))}${objectKey === undefined ? "" : `?photo=${encodeURIComponent(postPhotoIdFromObjectKey(objectKey))}`}`,editProfileCover: "/app/profile/cover-edit",editProfileCoverFrom: (source?: ProfileImageFlowSource) =>routeWithProfileImageFlowSource("/app/profile/cover-edit", source),diff --git a/web/apps/space/tests/post-quote.test.ts b/web/apps/space/tests/post-quote.test.tsnew file mode 100644index 0000000000..306af6c728--- /dev/null+++ b/web/apps/space/tests/post-quote.test.ts@@ -0,0 +1,66 @@+import { expect, test } from "vitest";+import {+ postQuoteErrorState,+ postQuoteKey,+ postQuotePhotoIndex,+} from "../src/utils/post-quote";+import { spaceRoutes } from "../src/utils/routes";++const photos = [+ { objectKey: "first" },+ { objectKey: "second" },+ { objectKey: "third" },+];++test("replies follow the selected photo across reordering", () => {+ expect(postQuotePhotoIndex(photos, "third")).toBe(2);+ expect(postQuotePhotoIndex([...photos].reverse(), "third")).toBe(0);+});++test("legacy replies show the sole photo or the post cover", () => {+ expect(postQuotePhotoIndex(photos.slice(0, 1))).toBe(0);+ expect(postQuotePhotoIndex(photos)).toBe(0);+});++test("missing references never fall back to the cover", () => {+ expect(postQuotePhotoIndex(photos, "missing")).toBe(-1);+ expect(postQuotePhotoIndex(photos, "")).toBe(-1);+ expect(postQuotePhotoIndex([], "third")).toBe(-1);+ expect(postQuotePhotoIndex([])).toBe(-1);+});++test("likes and replies to different photos have separate preview caches", () => {+ const post = { spaceId: "alice", postId: 42 };+ const keys = [+ post,+ { ...post, objectKey: "first" },+ { ...post, objectKey: "second" },+ { ...post, postId: 43, objectKey: "first" },+ ].map(postQuoteKey);+ expect(new Set(keys).size).toBe(keys.length);+});++test("photo URLs omit the storage path and preserve encoded photo IDs", () => {+ const objectKey = "space/alice/posts/photo #3?&+=.webp";+ const url = new URL(+ spaceRoutes.post("alice", 42, objectKey),+ "https://space.ente.io",+ );+ expect(url.pathname).toBe("/app/posts/alice/42");+ expect(url.searchParams.get("photo")).toBe("photo #3?&+=.webp");+ expect(spaceRoutes.post("alice", 42, "space/alice/posts/wo_second")).toBe(+ "/app/posts/alice/42?photo=wo_second",+ );+ expect(spaceRoutes.post("alice", 42)).toBe("/app/posts/alice/42");+});++test("unavailable posts and temporary failures have different states", () => {+ expect(postQuoteErrorState(new Error("Offline"))).toEqual({+ hasLoadError: true,+ });+ for (const name of ["content_unavailable", "permission_denied"]) {+ const error = new Error("Cannot access photo");+ error.name = name;+ expect(postQuoteErrorState(error)).toEqual({ isUnavailable: true });+ }+});