Skip to content
3 changes: 3 additions & 0 deletions apps/mobile/src/lib/composerContext.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,9 @@ describe("host context compatibility", () => {
text: ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
context,
});
expect(serializeComposerMessageForServer(" ", undefined)).toEqual({
text: ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
});
const withProse = `${reference} what is this?`;
expect(serializeComposerMessageForServer(withProse, context)).toEqual({
text: withProse,
Expand Down
7 changes: 4 additions & 3 deletions apps/mobile/src/lib/composerContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -300,8 +300,9 @@ export function serializeComposerMessageForServer(
composerText: string,
context: OrchestrationMessageContext | undefined,
): { text: string; context?: OrchestrationMessageContext } {
const text = isImageReferencesOnly(composerText)
? ATTACHMENT_ONLY_BOOTSTRAP_PROMPT
: composerText;
const text =
composerText.trim() === "" || isImageReferencesOnly(composerText)
? ATTACHMENT_ONLY_BOOTSTRAP_PROMPT
: composerText;
return { text, ...(context ? { context } : {}) };
}
15 changes: 7 additions & 8 deletions apps/mobile/src/state/threadOutboxDelivery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -837,12 +837,11 @@ describe("thread outbox recovery rollback", () => {
});
const attachment = {
id: "late-paste",
type: "image" as const,
name: "pasted.png",
mimeType: "image/png",
type: "file" as const,
name: "pasted.txt",
mimeType: "text/plain",
sizeBytes: 1,
dataUrl: "data:image/png;base64,AA==",
previewUri: "data:image/png;base64,AA==",
fileUri: "file:///pasted.txt",
};
try {
const recovering = recoverFailedThreadDraft(message);
Expand All @@ -855,11 +854,11 @@ describe("thread outbox recovery rollback", () => {
const restored = composerDrafts.getComposerDraftSnapshot(targetKey);
expect(restored.attachments).toContainEqual(attachment);
expect(restored.context?.records).toHaveLength(201);
const imageRecord = restored.context?.records.find(
const fileRecord = restored.context?.records.find(
(record) => "attachmentId" in record && record.attachmentId === attachment.id,
);
expect(imageRecord).toBeDefined();
expect(restored.text).toContain(`/${imageRecord!.contextId})`);
expect(fileRecord).toBeDefined();
expect(restored.text).toContain(`/${fileRecord!.contextId})`);
expect(composerDrafts.getComposerDraftSnapshot(sourceKey).attachments).toEqual([]);
} finally {
resume.resolve();
Expand Down
64 changes: 63 additions & 1 deletion apps/mobile/src/state/use-composer-drafts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -707,6 +707,7 @@ describe("mobile composer drafts", () => {
const fileLink = formatComposerContextReference(
getComposerDraftSnapshot(key).context!.records[0]!,
);
expect(getComposerDraftSnapshot(key).text).toBe(`${fileLink} `);
setComposerDraftText(key, `${fileLink} ${fileLink}`);
expect(getComposerDraftSnapshot(key).attachments).toEqual([file, image]);
setComposerDraftText(key, fileLink);
Expand All @@ -724,7 +725,7 @@ describe("mobile composer drafts", () => {
},
);

it("rejects attachments atomically when no context slots remain", async () => {
it("rejects files but keeps images when no context slots remain", async () => {
const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
onTestFinished(() => outboxLoad.mockRestore());
const cleanup = Promise.withResolvers<void>();
Expand Down Expand Up @@ -767,6 +768,67 @@ describe("mobile composer drafts", () => {
).toBe(1);
expect(getComposerDraftSnapshot(key)).toEqual(before);
await cleanup.promise;
const image = {
id: "photo",
type: "image" as const,
name: "photo.png",
mimeType: "image/png",
sizeBytes: 4,
previewUri: "file:///photo.png",
};
const video = {
id: "video",
type: "file" as const,
name: "clip.mp4",
mimeType: "video/mp4",
sizeBytes: 4,
fileUri: "file:///clip.mp4",
};
const videoCleanup = Promise.withResolvers<void>();
composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
videoCleanup.resolve();
});
expect(appendComposerDraftAttachments(key, [image, video], { appendReference: true })).toBe(1);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
expect(getComposerDraftSnapshot(key)).toEqual({ ...before, attachments: [image] });
await videoCleanup.promise;
});

it("fills images only into slots left after file chips replace the selection", async () => {
const key = "environment-1:replace-at-limit";
const file = (id: string) => ({
id,
type: "file" as const,
name: `${id}.txt`,
mimeType: "text/plain",
sizeBytes: 4,
fileUri: `file:///${id}.txt`,
});
const image = {
id: "photo",
type: "image" as const,
name: "photo.png",
mimeType: "image/png",
sizeBytes: 4,
previewUri: "file:///photo.png",
};
appendComposerDraftAttachments(key, [file("old")], { appendReference: true });
const { text } = getComposerDraftSnapshot(key);
const insertion = captureComposerDraftInsertion(key, { start: 0, end: text.length });
const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
onTestFinished(() => outboxLoad.mockRestore());
const cleanup = Promise.withResolvers<void>();
composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
cleanup.resolve();
});
expect(
appendComposerDraftAttachments(key, [image, file("new")], {
appendReference: true,
insertion,
maxAttachments: 1,
}),
).toBe(1);
expect(getComposerDraftSnapshot(key).attachments).toEqual([file("new")]);
await cleanup.promise;
});
it.each(["environment-1:thread", "environment-1:new-task:draft"])(
"preserves the captured paste selection across async writes in %s",
Expand Down
90 changes: 50 additions & 40 deletions apps/mobile/src/state/use-composer-drafts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1461,50 +1461,60 @@ export function appendComposerDraftAttachments(
return true;
});
duplicates = incoming.filter((attachment) => !attachments.includes(attachment));
const remaining = options?.restore
? attachments.length
: Math.max(
const limit = Math.min(
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
options?.maxAttachments ?? PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
);
const capacity = (draft: ComposerDraft, wanted: number) =>
options?.restore ? wanted : Math.max(0, limit - draft.attachments.length);
// Chips replace the selection, so files are placed first and images fill the slots left after.
const chipped = options?.appendReference
? attachments.filter((attachment) => attachment.type !== "image")
: [];
let draft = existing;
if (chipped.length > 0) {
const records = chipped
.slice(
0,
Math.min(
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
options?.maxAttachments ?? PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
) - retained.attachments.length,
Math.max(
0,
Math.min(
capacity(retained, chipped.length),
options?.restore
? Infinity
: COMPOSER_CONTEXT_MAX_RECORDS - (retained.context?.records.length ?? 0),
),
),
)
.map((attachment) => attachmentContextRecord(attachment));
const inserted =
records.length > 0 &&
draftWithInsertedContext(
draftKey,
{
...existing,
attachments: [...existing.attachments, ...chipped.slice(0, records.length)],
},
{
text: records.map(formatComposerContextReference).join(" "),
context: { version: 1, records },
},
options?.insertion,
options?.restore ? Infinity : COMPOSER_CONTEXT_MAX_RECORDS,
);
const contextCapacity =
options?.appendReference && !options.restore
? Math.max(0, COMPOSER_CONTEXT_MAX_RECORDS - (retained.context?.records.length ?? 0))
: attachments.length;
const accepted = attachments.slice(0, Math.min(remaining, contextCapacity));
rejected = attachments.slice(accepted.length);
if (accepted.length === 0) {
return current;
if (inserted) draft = { ...inserted, attachments: [...inserted.attachments] };
}
let draft = { ...existing, attachments: [...existing.attachments, ...accepted] };
if (options?.appendReference) {
const records = accepted.map((attachment) => attachmentContextRecord(attachment));
const inserted = draftWithInsertedContext(
draftKey,
draft,
{
text: records.map(formatComposerContextReference).join(" "),
context: { version: 1, records },
},
options.insertion,
options.restore ? Infinity : COMPOSER_CONTEXT_MAX_RECORDS,
);
if (!inserted) {
rejected = attachments;
return current;
}
draft = { ...inserted, attachments: [...inserted.attachments] };
removed = existing.attachments.filter(
(attachment) => !draft.attachments.includes(attachment),
);
}
return {
...current,
[draftKey]: draft,
const plain = options?.appendReference
? attachments.filter((attachment) => attachment.type === "image")
: attachments;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
draft = {
...draft,
attachments: [...draft.attachments, ...plain.slice(0, capacity(draft, plain.length))],
};
rejected = attachments.filter((attachment) => !draft.attachments.includes(attachment));
if (rejected.length === attachments.length) return current;
removed = existing.attachments.filter((attachment) => !draft.attachments.includes(attachment));
return { ...current, [draftKey]: draft };
});
scheduleUnusedComposerAttachmentCleanup([...rejected, ...removed, ...duplicates]);
return rejected.length;
Expand Down
Loading