Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 49 additions & 21 deletions apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native"
import { TextInputWrapper } from "expo-paste-input";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { T, useGT } from "gt-react-native";
import { useMemo, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { ScrollView, View, useWindowDimensions } from "react-native";
import * as Dialog from "../../components/ui/Dialog";
import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal";
Expand All @@ -16,6 +16,7 @@ import { cn } from "../../lib/cn";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
import { useNativePaste } from "../../lib/useNativePaste";
import { scheduleUnusedComposerAttachmentCleanup } from "../../state/use-composer-drafts";
import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
import { appendReviewCommentToDraft } from "../../state/use-thread-composer-state";
import {
Expand Down Expand Up @@ -49,6 +50,31 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
const { environmentId, threadId } = props.route.params;
const [commentText, setCommentText] = useState("");
const [attachments, setAttachments] = useState<ReadonlyArray<DraftComposerImageAttachment>>([]);
const attachmentsRef = useRef(attachments);
const isMountedRef = useRef(true);
// Store file references before React commits, so closing the sheet can release them.
const replaceAttachments = (next: ReadonlyArray<DraftComposerImageAttachment>) => {
attachmentsRef.current = next;
setAttachments(next);
};
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- releases owned image files when the sheet unmounts
useEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
scheduleUnusedComposerAttachmentCleanup(attachmentsRef.current);
};
}, []);

function appendImages(images: ReadonlyArray<DraftComposerImageAttachment>): void {
if (!isMountedRef.current) {
scheduleUnusedComposerAttachmentCleanup(images);
return;
}
if (images.length > 0) {
replaceAttachments([...attachmentsRef.current, ...images]);
}
}
const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);

const { selectedLines, highlightedLinesById } = useMemo(() => {
Expand Down Expand Up @@ -90,27 +116,25 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
};
const handleNativePaste = useNativePaste((uris) => {
void (async () => {
try {
const result = await convertPastedImagesToAttachments({
uris,
existingCount: attachments.length,
});
if (result.attachments.length > 0) {
setAttachments((current) => [...current, ...result.attachments]);
}
if (result.error) Dialog.alert(gt("Could not paste image"), result.error);
} catch (error) {
const result = await convertPastedImagesToAttachments({
uris,
existingCount: attachmentsRef.current.length,
}).catch((error: unknown) => {
console.error("[review comment] error converting pasted images", error);
return null;
});
if (result === null) return;
appendImages(result.attachments);
if (result.error && isMountedRef.current) {
Dialog.alert(gt("Could not paste image"), result.error);
}
})();
});

async function handlePickImages(): Promise<void> {
const result = await pickComposerImages({ existingCount: attachments.length });
if (result.images.length > 0) {
setAttachments((current) => [...current, ...result.images]);
}
if (result.error) {
const result = await pickComposerImages({ existingCount: attachmentsRef.current.length });
appendImages(result.images);
if (result.error && isMountedRef.current) {
setPendingConnectionError(result.error);
}
}
Expand All @@ -124,9 +148,10 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
environmentId,
threadId,
text: formatReviewCommentContext(target, commentText),
attachments,
attachments: attachmentsRef.current,
});
setAttachments([]);
scheduleUnusedComposerAttachmentCleanup(attachmentsRef.current);
replaceAttachments([]);
dismissComposer();
};

Expand Down Expand Up @@ -255,9 +280,12 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
onPressPreview={setPreviewFile}
removeButtonPlacement="gutter"
onRemove={(imageId) => {
setAttachments((current) =>
current.filter((image) => image.id !== imageId),
);
const current = attachmentsRef.current;
const removed = current.find((image) => image.id === imageId);
replaceAttachments(current.filter((image) => image.id !== imageId));
if (removed) {
scheduleUnusedComposerAttachmentCleanup([removed]);
}
}}
/>
</View>
Expand Down
118 changes: 114 additions & 4 deletions apps/mobile/src/features/sharing/incoming-share-model.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "@effect/vitest";
import { describe, expect, it, vi } from "vite-plus/test";
import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
Expand All @@ -13,6 +13,32 @@ import {
selectIncomingShareAttachmentsForServer,
} from "./incoming-share-model";

const nativeImage = vi.hoisted(() => ({
resize: vi.fn(),
}));

vi.mock("expo-image-manipulator", () => ({
SaveFormat: { PNG: "png", JPEG: "jpeg" },
ImageManipulator: {
manipulate: (source: string | { width: number; height: number }) => {
let size = typeof source === "string" ? { width: 3000, height: 1500 } : source;
const context = {
resize: (next: { width: number; height: number }) => {
nativeImage.resize(next);
size = next;
return context;
},
renderAsync: async () => ({
...size,
release: () => {},
saveAsync: async () => ({ uri: "file:///cache/resized.png", base64: "YWJj" }),
}),
};
return context;
},
},
}));

describe("incoming native shares", () => {
it("converts shared text, URLs, and images into a durable composer draft", async () => {
const image: SharePayload = {
Expand All @@ -35,14 +61,19 @@ describe("incoming native shares", () => {
originalName: "Screenshot.png",
};
const removeOwnedFile = vi.fn(() => Promise.resolve());
const readBase64 = vi.fn(async () => "YWJj");
const persistedUri = "file:///documents/t3-composer-attachments/Screenshot.png";
const persistFile = vi.fn(async () => persistedUri);

const result = await buildIncomingShareDraft({
id: "share-1",
createdAt: "2026-07-15T10:00:00.000Z",
payloads,
resolvedPayloads: [resolvedImage],
fileReader: {
readBase64: async () => "YWJj",
readBase64,
persistFile,
readSize: async (uri) => (uri === persistedUri ? 3 : null),
removeOwnedFile,
},
});
Expand All @@ -59,16 +90,95 @@ describe("incoming native shares", () => {
name: "Screenshot.png",
mimeType: "image/png",
sizeBytes: 3,
dataUrl: "data:image/png;base64,YWJj",
previewUri: "data:image/png;base64,YWJj",
fileUri: persistedUri,
previewUri: persistedUri,
},
],
warnings: [],
});
expect(removeOwnedFile).toHaveBeenCalledWith(image.value);
expect(removeOwnedFile).not.toHaveBeenCalledWith(persistedUri);
expect(hasIncomingShareContent(result)).toBe(true);
});

it("persists the resized PNG for a shared image over 2000px", async () => {
const header = Buffer.alloc(24);
header.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
header.set([0x49, 0x48, 0x44, 0x52], 12);
header.writeUInt32BE(3000, 16);
header.writeUInt32BE(1500, 20);
const persistedUri = "file:///documents/t3-composer-attachments/screenshot.png";
const persistFile = vi.fn(async () => persistedUri);
const removeOwnedFile = vi.fn(async (_uri: string) => undefined);

const draft = await buildIncomingShareDraft({
id: "share-resize",
createdAt: "2026-07-15T10:00:00.000Z",
payloads: [
{ shareType: "image", value: "content://shared/screenshot", mimeType: "image/png" },
],
resolvedPayloads: [],
fileReader: {
readBase64: async () => header.toString("base64"),
persistFile,
readSize: async () => 3,
removeOwnedFile,
},
});

expect(nativeImage.resize).toHaveBeenCalledWith({ width: 2000, height: 1000 });
expect(persistFile).toHaveBeenCalledWith("file:///cache/resized.png", "screenshot");
expect(draft.attachments).toEqual([
{
id: "share-resize-image-0",
type: "image",
name: "screenshot",
mimeType: "image/png",
sizeBytes: 3,
fileUri: persistedUri,
previewUri: persistedUri,
},
]);
expect(draft.warnings).toEqual([]);
expect(removeOwnedFile).not.toHaveBeenCalledWith(persistedUri);
});

it("releases a shared image when its stored size cannot be measured", async () => {
const image: SharePayload = {
shareType: "image",
value: "file:///shared/photo.png",
mimeType: "image/png",
};
const persistedUri = "file:///documents/t3-composer-attachments/photo.png";
const removeOwnedFile = vi.fn(async (_uri: string) => undefined);
const result = await buildIncomingShareDraft({
id: "share-unmeasured",
createdAt: "2026-07-15T10:00:00.000Z",
payloads: [image],
resolvedPayloads: [
{
...image,
contentUri: image.value,
contentType: "image",
contentMimeType: "image/png",
contentSize: 3,
originalName: "photo.png",
},
],
fileReader: {
readBase64: async () => "unused",
persistFile: async () => persistedUri,
readSize: async () => null,
removeOwnedFile,
},
});

expect(result.attachments).toEqual([]);
expect(result.warnings).toEqual(["'photo.png' is empty or could not be read."]);
expect(removeOwnedFile).toHaveBeenCalledWith(persistedUri);
expect(removeOwnedFile).toHaveBeenCalledWith(image.value);
});

it("skips oversized images and releases the temporary native file", async () => {
const image: SharePayload = {
shareType: "image",
Expand Down
55 changes: 38 additions & 17 deletions apps/mobile/src/features/sharing/incoming-share-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,9 @@ export async function buildIncomingShareDraft(input: {
continue;
}

const name = resolved?.originalName ?? fallbackName(uri, index, mimeType);
let persistedImageUri: string | undefined;
let retainedImageUri: string | undefined;
try {
const sharedBase64 = await input.fileReader.readBase64(uri);
// Use already-read bytes because native image loaders may not read the provider's file.
Expand All @@ -421,36 +424,54 @@ export async function buildIncomingShareDraft(input: {
base64: sharedBase64,
});
const base64 = fitted?.base64 ?? sharedBase64;
const sizeBytes = fitted
? estimateBase64ByteSize(base64)
: (resolved?.contentSize ?? estimateBase64ByteSize(base64));
if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
warnings.push(
m(
msg("''{name}'' exceeds the 10 MB attachment limit.", {
name: resolved?.originalName ?? fallbackName(uri, index, mimeType),
}),
),
);
const decodedSize = estimateBase64ByteSize(base64);
if (decodedSize <= 0 || decodedSize > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
warnings.push(m(msg("''{name}'' exceeds the 10 MB attachment limit.", { name })));
continue;
}
if (input.fileReader.persistFile) {
persistedImageUri = await input.fileReader.persistFile(fitted?.uri ?? uri, name);
const sizeBytes = (await input.fileReader.readSize?.(persistedImageUri)) ?? null;
if (sizeBytes === null || sizeBytes <= 0) {
warnings.push(m(msg("''{name}'' is empty or could not be read.", { name })));
continue;
}
if (sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
warnings.push(fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, m));
continue;
}
attachments.push({
id: `${input.id}-image-${index}`,
type: "image",
name,
mimeType,
sizeBytes,
fileUri: persistedImageUri,
previewUri: persistedImageUri,
});
retainedImageUri = persistedImageUri;
continue;
}
const dataUrl = `data:${mimeType};base64,${base64}`;
attachments.push({
id: `${input.id}-image-${index}`,
type: "image",
name: resolved?.originalName ?? fallbackName(uri, index, mimeType),
name,
mimeType,
sizeBytes,
sizeBytes: decodedSize,
dataUrl,
// Data-backed previews outlive temporary share files and App Group entries.
previewUri: dataUrl,
});
} catch {
warnings.push(
m(msg("Could not read ''{name}''.", { name: fallbackName(uri, index, mimeType) })),
);
warnings.push(m(msg("Could not read ''{name}''.", { name })));
} finally {
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
await releaseOwnedFiles(
input.fileReader,
[uri, payload.value, persistedImageUri].filter(
(candidate) => candidate !== retainedImageUri,
),
);
}
}

Expand Down
Loading
Loading