Skip to content
Open
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
4 changes: 2 additions & 2 deletions apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ import {
} from "@t3tools/contracts";

import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
import { composerContextImportsAtom } from "../../state/use-composer-drafts";
import { composerContextImportsAtom, composerDraftBusy } from "../../state/use-composer-drafts";
import { abortComposerDraftOperations } from "../../state/composerDraftOperations";
import { composerContextSendBlockReason } from "../../lib/composerContext";
import { ComposerInlineControl } from "../../components/ComposerToolbar";
Expand Down Expand Up @@ -601,7 +601,7 @@ export function NewTaskDraftScreen(props: {
return null;
}
const draft = getComposerDraftSnapshot(draftKey);
if (appAtomRegistry.get(composerContextImportsAtom)[draftKey]) return null;
if (composerDraftBusy(draftKey)) return null;
const modelSelection =
resolveSelectableModelSelection(
selectedEnvironmentServerConfig,
Expand Down
20 changes: 15 additions & 5 deletions apps/mobile/src/features/threads/ThreadComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import {
getComposerDraftSnapshot,
setComposerDraftText,
composerContextImportsAtom,
composerPendingMediaAtom,
countComposerDraftAttachmentsAfterSelection,
useComposerDraft,
useComposerDraftResetGeneration,
Expand Down Expand Up @@ -305,9 +306,11 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
context: draftContext,
} = useComposerDraft(composerDraftKey);
const queuedEdit = props.queuedEdit ?? null;
const pendingMedia = useAtomValue(composerPendingMediaAtom)[composerDraftKey];
const hasContent =
draftMessage.trim().length > 0 ||
draftAttachments.length > 0 ||
pendingMedia !== undefined ||
(queuedEdit?.existingAttachments.length ?? 0) > 0;
const showStopAction = !hasContent && props.canStopThread && queuedEdit === null;
const onResumeQueue = props.onResumeQueue;
Expand All @@ -326,10 +329,16 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
AuthOrchestrationOperateScope,
);
const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
const stripAttachments = composerStripAttachments(
draftAttachments,
(attachment) => uploadStates[composerAttachmentUploadKey(props.environmentId, attachment.id)],
);
// A finished attachment keeps its placeholder's id; skip the placeholder once it lands.
const stripAttachments = [
...composerStripAttachments(
draftAttachments,
(attachment) => uploadStates[composerAttachmentUploadKey(props.environmentId, attachment.id)],
),
...(pendingMedia ?? []).filter(
(placeholder) => !draftAttachments.some(({ id }) => id === placeholder.id),
),
];
const attachmentsUploading =
props.connectionState === "connected" &&
composerAttachmentsStillUploading({
Expand Down Expand Up @@ -501,6 +510,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
(props.canOperateThread || props.connectionState !== "connected") &&
hasContent &&
!contextImports[composerDraftKey] &&
pendingMedia === undefined &&
!isSubmissionLocked &&
sendBlockedReason === null &&
!modelUnavailable;
Expand All @@ -516,7 +526,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
(current) =>
current ?? {
...source,
gallery: filePreviewGallery(source, composerImageGallery(draftAttachments)),
gallery: filePreviewGallery(source, composerImageGallery(stripAttachments)),
},
);
};
Expand Down
11 changes: 10 additions & 1 deletion apps/mobile/src/lib/composerFiles.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -385,8 +385,17 @@ describe("composer file attachments", () => {
uri.endsWith("clip.mov") ? video.fileSize : 3,
);

const result = await pickComposerMedia({ existingCount: 0, maxVideoBytes: 50 * 1024 * 1024 });
const onPicked = vi.fn();
const result = await pickComposerMedia({
existingCount: 0,
maxVideoBytes: 50 * 1024 * 1024,
onPicked,
});

expect(onPicked).toHaveBeenCalledWith([
expect.objectContaining({ id: "attachment-id", type: "image", previewUri: image.uri }),
expect.objectContaining({ id: "attachment-id", type: "file", fileUri: video.uri }),
]);
expect(mocks.pickMedia).toHaveBeenCalledWith(
expect.objectContaining({
mediaTypes: ["images", "videos"],
Expand Down
41 changes: 33 additions & 8 deletions apps/mobile/src/lib/composerImages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,8 @@ export async function pickComposerImages(input: { readonly existingCount: number
export async function pickComposerMedia(input: {
readonly existingCount: number;
readonly maxVideoBytes?: number;
/** Receives placeholders over the picker's local copies before processing; each keeps its attachment's id. */
readonly onPicked?: (placeholders: ReadonlyArray<DraftComposerAttachment>) => void;
readonly acceptSelection?: () => boolean;
}): Promise<{
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
Expand Down Expand Up @@ -488,11 +490,28 @@ export async function pickComposerMedia(input: {
error: null,
};
}
const ids = result.assets.map(() => uuidv4());
input.onPicked?.(
result.assets.flatMap((asset, index): DraftComposerAttachment[] => {
const common = {
id: ids[index]!,
name: asset.fileName ?? "",
mimeType: asset.mimeType ?? "",
sizeBytes: asset.fileSize ?? 0,
};
if (asset.type === "image" || asset.mimeType?.startsWith("image/")) {
return [{ ...common, type: "image", previewUri: asset.uri }];
}
return input.maxVideoBytes === undefined
? []
: [{ ...common, type: "file", fileUri: asset.uri }];
}),
);

const attachments: DraftComposerAttachment[] = [];
let error: string | null = null;

for (const asset of result.assets) {
for (const [index, asset] of result.assets.entries()) {
if (attachments.length >= remainingSlots) {
error = m(
msg("You can attach up to {max} attachments per message.", {
Expand All @@ -510,15 +529,16 @@ export async function pickComposerMedia(input: {
try {
const { File } = await import("expo-file-system");
const file = new File(asset.uri);
attachments.push(
await createComposerFileAttachment({
attachments.push({
...(await createComposerFileAttachment({
uri: asset.uri,
name: asset.fileName?.trim() || file.name || "video",
mimeType: mimeType || file.type || "application/octet-stream",
sizeBytes: asset.fileSize ?? null,
maxBytes: clampFileAttachmentUploadBytes(input.maxVideoBytes),
}),
);
})),
id: ids[index]!,
});
} catch (cause) {
error =
errorDisplayMessage(cause, m) ??
Expand Down Expand Up @@ -592,9 +612,14 @@ export async function pickComposerMedia(input: {
image.name,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
);
attachments.push(
await ownedComposerImageAttachment({ fileUri, name: image.name, mimeType: image.mimeType }),
);
attachments.push({
...(await ownedComposerImageAttachment({
fileUri,
name: image.name,
mimeType: image.mimeType,
})),
id: ids[index]!,
});
} catch (cause) {
error = errorDisplayMessage(cause, m) ?? m(msg("Failed to read ''{name}''.", { name }));
}
Expand Down
1 change: 1 addition & 0 deletions apps/mobile/src/state/thread-task-permissions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ vi.mock("./use-composer-drafts", async () => {
return {
composerDraftsAtom: Atom.make({}),
composerContextImportsAtom: Atom.make({}),
composerDraftBusy: () => false,
getComposerDraftSnapshot: () => state.draft,
isFreshSessionPending: () => state.freshPending,
setFreshSessionPending: state.setFreshPending,
Expand Down
26 changes: 19 additions & 7 deletions apps/mobile/src/state/use-composer-attachment-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ import {
captureComposerDraftInsertion,
countComposerDraftAttachmentsAfterSelection,
getComposerDraftSnapshot,
addComposerPendingMedia,
keepPendingComposerMedia,
removeComposerPendingMedia,
type ComposerDraftInsertion,
} from "./use-composer-drafts";
import { startComposerDraftOperation } from "./composerDraftOperations";
Expand Down Expand Up @@ -72,15 +75,24 @@ export function useComposerAttachmentActions(props: {
if (!key || props.locked) return;
const insertion = captureComposerDraftInsertion(key);
await withDraftOperation(key, async (signal) => {
const result = await pickComposerMedia({
let placeholderIds: ReadonlyArray<string> = [];
await pickComposerMedia({
existingCount: countComposerDraftAttachmentsAfterSelection(key, insertion),
maxVideoBytes: capabilities?.fileAttachments?.maxUploadBytes,
});
report(
m(msg("Could not attach photo or video")),
result.error,
await append(key, signal, result.attachments, insertion),
);
onPicked: (placeholders) => {
placeholderIds = placeholders.map(({ id }) => id);
addComposerPendingMedia(key, placeholders);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
},
})
.then(async (result) => {
// append writes the draft before its first await, so no removal lands in between.
report(
m(msg("Could not attach photo or video")),
result.error,
await append(key, signal, keepPendingComposerMedia(key, result.attachments), insertion),
);
})
.finally(() => removeComposerPendingMedia(key, placeholderIds));
});
};
const onPickDraftFiles = async () => {
Expand Down
33 changes: 33 additions & 0 deletions apps/mobile/src/state/use-composer-drafts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,9 @@ import {
findNewTaskDraftKeys,
flushComposerDrafts,
getComposerDraftSnapshot,
addComposerPendingMedia,
keepPendingComposerMedia,
removeComposerDraftAttachment,
mergeComposerDraftContentState,
migrateLegacyNewTaskDraft,
modelOptionMemoryAtom,
Expand Down Expand Up @@ -1170,6 +1173,36 @@ describe("mobile composer drafts", () => {
expect(appAtomRegistry.get(composerDraftsAtom)[draftKey]?.attachments).toHaveLength(101);
});

it("releases picked media whose placeholder was removed while it processed", async () => {
const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
onTestFinished(() => outboxLoad.mockRestore());
const cleanup = Promise.withResolvers<void>();
composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
cleanup.resolve();
});
const video = (id: string) => ({
id,
type: "file" as const,
name: `${id}.mov`,
mimeType: "video/quicktime",
sizeBytes: 42,
fileUri: `file:///documents/t3-composer-attachments/${id}.mov`,
});
const draftKey = "thread-pending-media";
appAtomRegistry.set(composerDraftsAtom, { [draftKey]: { text: "", attachments: [] } });
addComposerPendingMedia(draftKey, [video("kept"), video("removed")]);

removeComposerDraftAttachment(draftKey, "removed");

expect(keepPendingComposerMedia(draftKey, [video("kept"), video("removed")])).toEqual([
video("kept"),
]);
await cleanup.promise;
expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledExactlyOnceWith(
video("removed").fileUri,
);
});

it("drops duplicate attachments, releases their files, and keeps them on restore", async () => {
const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
onTestFinished(() => outboxLoad.mockRestore());
Expand Down
54 changes: 54 additions & 0 deletions apps/mobile/src/state/use-composer-drafts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,59 @@ export function setComposerContextImporting(draftKey: string, importing: boolean
appAtomRegistry.set(composerContextImportsAtom, next);
}

/** Placeholders for picked media still being processed, shown in the strip until their attachments land. */
export const composerPendingMediaAtom = Atom.make<
Record<string, ReadonlyArray<DraftComposerAttachment>>
>({}).pipe(Atom.keepAlive);

function updateComposerPendingMedia(
draftKey: string,
update: (current: ReadonlyArray<DraftComposerAttachment>) => DraftComposerAttachment[],
): void {
const all = appAtomRegistry.get(composerPendingMediaAtom);
const current = all[draftKey] ?? [];
const placeholders = update(current);
if (placeholders.length === current.length) return;
const next = { ...all };
if (placeholders.length > 0) next[draftKey] = placeholders;
else delete next[draftKey];
appAtomRegistry.set(composerPendingMediaAtom, next);
}

export function addComposerPendingMedia(
draftKey: string,
placeholders: ReadonlyArray<DraftComposerAttachment>,
): void {
updateComposerPendingMedia(draftKey, (current) => [...current, ...placeholders]);
}

export function removeComposerPendingMedia(draftKey: string, ids: ReadonlyArray<string>): void {
updateComposerPendingMedia(draftKey, (current) =>
current.filter((placeholder) => !ids.includes(placeholder.id)),
);
}

/** Picked attachments whose placeholder the user removed while processing are released, not added. */
export function keepPendingComposerMedia(
draftKey: string,
attachments: ReadonlyArray<DraftComposerAttachment>,
): ReadonlyArray<DraftComposerAttachment> {
const pending = appAtomRegistry.get(composerPendingMediaAtom)[draftKey] ?? [];
const kept = attachments.filter(({ id }) => pending.some((placeholder) => placeholder.id === id));
scheduleUnusedComposerAttachmentCleanup(
attachments.filter((attachment) => !kept.includes(attachment)),
);
return kept;
}

/** A draft can't be sent while context is importing or picked media is still processing. */
export function composerDraftBusy(draftKey: string): boolean {
return (
appAtomRegistry.get(composerContextImportsAtom)[draftKey] === true ||
appAtomRegistry.get(composerPendingMediaAtom)[draftKey] !== undefined
);
}

interface ComposerDraftSelection {
readonly text: string;
readonly start: number;
Expand Down Expand Up @@ -1548,6 +1601,7 @@ export function replaceComposerDraftAttachments(
}

export function removeComposerDraftAttachment(draftKey: string, imageId: string): void {
removeComposerPendingMedia(draftKey, [imageId]);
const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
updateComposerDrafts((current) => {
const existing = normalizeDraft(current[draftKey]);
Expand Down
10 changes: 6 additions & 4 deletions apps/mobile/src/state/use-thread-composer-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ import {
insertComposerDraftContext,
clearComposerDraft,
clearComposerDraftContent,
composerContextImportsAtom,
composerDraftBusy,
getComposerDraftSnapshot,
isFreshSessionPending,
mergeComposerDraftContent,
Expand Down Expand Up @@ -508,7 +508,9 @@ export function useThreadComposerState(input: {
const threadKey = scopedThreadKey(thread.environmentId, thread.id);
const edit = getQueuedRunEdit(threadKey);
if (edit === null) return;
const draft = getComposerDraftSnapshot(queuedEditDraftKey(threadKey, edit.runId));
const editDraftKey = queuedEditDraftKey(threadKey, edit.runId);
if (composerDraftBusy(editDraftKey)) return;
const draft = getComposerDraftSnapshot(editDraftKey);
const text = draft.text.trim();
if (
text.length === 0 &&
Expand Down Expand Up @@ -649,7 +651,7 @@ export function useThreadComposerState(input: {
if (startingSideChatRef.current) return null;
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
const draft = getComposerDraftSnapshot(threadKey);
if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
if (composerDraftBusy(threadKey)) return null;
const thread = selectedThreadShell;
const text = draft.text.trim();
const attachments = draft.attachments;
Expand Down Expand Up @@ -851,7 +853,7 @@ export function useThreadComposerState(input: {
if (!response) return null;
// A context paste still landing, or any draft or settings change while approvals were
// declined, means this snapshot is no longer what the user sent.
if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
if (composerDraftBusy(threadKey)) return null;
const current = getComposerDraftSnapshot(threadKey);
if (
current.text !== draft.text ||
Expand Down
Loading