Skip to content

Commit afd5cc0

Browse files
fix(mobile): queued edits keep removals, settings sheet follows the ended edit
A removed server attachment now counts as a change when the run starts, the settings sheet edits the thread's draft once a queued edit ends, a failed save whose run already left the queue no longer claims the edit is still in the composer, and a failed preview write is never reused as a cached preview. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent caf4120 commit afd5cc0

8 files changed

Lines changed: 140 additions & 21 deletions

File tree

‎apps/mobile/src/features/threads/ThreadSettingsSheet.tsx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ import {
8787
useComposerDraftSettings,
8888
} from "../../state/use-composer-drafts";
8989
import { useQuietThreadStructure } from "../../state/use-thread-detail";
90+
import { activeComposerDraftKey, useQueuedRunEdit } from "../../state/queued-run-edit";
9091
import { updateThreadDraftModelSelection } from "../../state/use-thread-composer-state";
9192
import { useThreadSelection } from "../../state/use-thread-selection";
9293
import { threadAllowsProviderSwitch } from "../../state/thread-provider-switching";
@@ -1501,7 +1502,10 @@ export function ExistingThreadSettingsRouteScreen({
15011502
const reportedModelSelection = useThreadReportedModelSelection(selectedThreadDetailRef);
15021503
const threadKey = scopedThreadKey(route.params.environmentId, route.params.threadId);
15031504
const draftSettings = useComposerDraftSettings(threadKey);
1504-
const prompt = useComposerDraft(route.params.draftKey).text;
1505+
const queuedRunEdit = useQueuedRunEdit(threadKey);
1506+
// A queued edit can end while the sheet is open; the prompt then belongs to the thread's draft.
1507+
const draftKey = activeComposerDraftKey(threadKey, route.params.draftKey, queuedRunEdit);
1508+
const prompt = useComposerDraft(draftKey).text;
15051509

15061510
if (!selectedThread) {
15071511
return <View className="flex-1 bg-sheet" />;
@@ -1539,7 +1543,7 @@ export function ExistingThreadSettingsRouteScreen({
15391543
providerGroups={groupByProvider(modelOptions)}
15401544
selectedModel={modelSelection}
15411545
prompt={prompt}
1542-
onPromptChange={(text) => setComposerDraftText(route.params.draftKey, text)}
1546+
onPromptChange={(text) => setComposerDraftText(draftKey, text)}
15431547
reportedModelSelection={reportedModelSelection}
15441548
onSelectModel={(option) => updateModelSelection(withRememberedModelOptions(option.selection))}
15451549
restoreSelection={withRememberedModelOptions}

‎apps/mobile/src/lib/composerImagePreview.test.ts‎

Lines changed: 47 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import { describe, expect, it, vi } from "vite-plus/test";
22

3-
const mocks = vi.hoisted(() => ({ write: vi.fn(async () => undefined) }));
3+
const mocks = vi.hoisted(() => ({
4+
files: new Set<string>(),
5+
write: vi.fn(async (_content: string, _options: unknown) => undefined),
6+
}));
47

58
vi.mock("expo-file-system", () => ({
69
Paths: { cache: "file:///cache" },
@@ -12,15 +15,27 @@ vi.mock("expo-file-system", () => ({
1215
create() {}
1316
},
1417
File: class {
15-
readonly uri: string;
18+
uri: string;
1619
constructor(directory: { parent: string; name: string }, name: string) {
1720
this.uri = `${directory.parent}/${directory.name}/${name}`;
1821
}
1922
get exists() {
20-
return false;
23+
return mocks.files.has(this.uri);
24+
}
25+
create() {
26+
mocks.files.add(this.uri);
27+
}
28+
delete() {
29+
mocks.files.delete(this.uri);
30+
}
31+
write(content: string, options: unknown) {
32+
return mocks.write(content, options);
33+
}
34+
async move(destination: { uri: string }) {
35+
mocks.files.delete(this.uri);
36+
mocks.files.add(destination.uri);
37+
this.uri = destination.uri;
2138
}
22-
create() {}
23-
write = mocks.write;
2439
},
2540
}));
2641

@@ -61,4 +76,31 @@ describe("materializedPreviewAtom", () => {
6176
expect(mocks.write).toHaveBeenCalledTimes(1);
6277
unmount();
6378
});
79+
80+
it("writes the preview again after a failed write instead of reusing the partial file", async () => {
81+
const attachment: DraftComposerImageAttachment = {
82+
id: "image-failed",
83+
type: "image",
84+
name: "photo.png",
85+
mimeType: "image/png",
86+
sizeBytes: 3,
87+
previewUri: "data:image/png;base64,AAAA",
88+
};
89+
const materialize = async () => {
90+
const registry = AtomRegistry.make();
91+
const atom = materializedPreviewAtom(new MaterializedPreviewKey(attachment));
92+
const unmount = registry.mount(atom);
93+
await vi.waitFor(() => expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true));
94+
const result = registry.get(atom);
95+
unmount();
96+
return AsyncResult.isSuccess(result) ? result.value : undefined;
97+
};
98+
using _warn = vi.spyOn(console, "warn").mockImplementation(() => {});
99+
mocks.write.mockClear();
100+
mocks.write.mockRejectedValueOnce(new Error("disk full"));
101+
102+
expect(await materialize()).toBeNull();
103+
expect(await materialize()).toBe("file:///cache/t3-composer-previews/image-failed.png");
104+
expect(mocks.write).toHaveBeenCalledTimes(2);
105+
});
64106
});

‎apps/mobile/src/lib/composerImagePreview.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,18 @@ async function materializeDataUrlPreview(id: string, dataUrl: string): Promise<s
1616
const directory = new Directory(Paths.cache, PREVIEW_CACHE_DIRECTORY);
1717
directory.create({ idempotent: true, intermediates: true });
1818
const file = new File(directory, `${id}.${extension}`);
19-
if (!file.exists) {
20-
file.create();
21-
await file.write(dataUrl.slice(comma + 1), { encoding: "base64" });
19+
if (file.exists) return file.uri;
20+
// Write beside the cache entry and move it in, so a failed or interrupted write is never reused.
21+
const partial = new File(directory, `${id}.${extension}.partial`);
22+
if (partial.exists) partial.delete();
23+
partial.create();
24+
try {
25+
await partial.write(dataUrl.slice(comma + 1), { encoding: "base64" });
26+
} catch (error) {
27+
partial.delete();
28+
throw error;
2229
}
30+
await partial.move(file);
2331
return file.uri;
2432
}
2533

‎apps/mobile/src/state/queued-run-edit.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@ import {
1111

1212
import { appAtomRegistry } from "./atom-registry";
1313
import {
14+
activeComposerDraftKey,
1415
beginQueuedRunEdit,
1516
getQueuedRunEdit,
1617
queuedEditDraftKey,
18+
removeQueuedRunEditAttachment,
1719
resolveQueuedEditPayload,
1820
type QueuedRunEdit,
1921
} from "./queued-run-edit";
@@ -110,4 +112,35 @@ describe("beginQueuedRunEdit", () => {
110112
"That message already started, so the edit was discarded.",
111113
);
112114
});
115+
116+
it("treats a removed server attachment as a change when the run starts", () => {
117+
const threadKey = "env-exit:thread-removed";
118+
const runId = RunId.make("run-1");
119+
const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
120+
{ id: runId, status: "queued" },
121+
]);
122+
setComposerDraftText(threadKey, "other work");
123+
beginQueuedRunEdit(threadKey, edit([image("kept")]), runs);
124+
removeQueuedRunEditAttachment(threadKey, "kept");
125+
126+
appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
127+
128+
expect(getQueuedRunEdit(threadKey)).toBeNull();
129+
expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(
130+
"That message already started, so the edit was discarded.",
131+
);
132+
});
133+
});
134+
135+
describe("activeComposerDraftKey", () => {
136+
const threadKey = "env:thread";
137+
const editKey = queuedEditDraftKey(threadKey, RunId.make("run-1"));
138+
139+
it("keeps a queued edit's draft while that edit is open", () => {
140+
expect(activeComposerDraftKey(threadKey, editKey, edit([]))).toBe(editKey);
141+
});
142+
143+
it("falls back to the thread's draft once the edit has ended", () => {
144+
expect(activeComposerDraftKey(threadKey, editKey, null)).toBe(threadKey);
145+
});
113146
});

‎apps/mobile/src/state/queued-run-edit.ts‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ export interface QueuedRunEdit {
3131
readonly originalText: string;
3232
readonly existingAttachments: ReadonlyArray<ChatAttachment>;
3333
readonly context?: OrchestrationMessageContext;
34+
/** Removing a server attachment changes the message even when the draft looks untouched. */
35+
readonly removedExistingAttachment?: true;
3436
}
3537

3638
const queuedRunEdits = makeQueuedRunEditStore<QueuedRunEdit>({
@@ -42,6 +44,21 @@ export { isQueuedEditDraftKey, queuedEditDraftKey } from "./queued-edit-draft-ke
4244

4345
export const getQueuedRunEdit = queuedRunEdits.get;
4446

47+
/**
48+
* The draft a sheet opened for `requestedKey` should edit now: a queued edit's
49+
* draft only while that edit is still open, else the thread's own draft.
50+
*/
51+
export function activeComposerDraftKey(
52+
threadKey: string,
53+
requestedKey: string,
54+
edit: QueuedRunEdit | null,
55+
): string {
56+
if (requestedKey === threadKey) return threadKey;
57+
return edit !== null && queuedEditDraftKey(threadKey, edit.runId) === requestedKey
58+
? requestedKey
59+
: threadKey;
60+
}
61+
4562
export function useQueuedRunEdit(threadKey: string | null): QueuedRunEdit | null {
4663
const edits = useAtomValue(queuedRunEdits.atom);
4764
return threadKey === null ? null : (edits[threadKey] ?? null);
@@ -59,14 +76,19 @@ function exitQueuedRunEdit(threadKey: string, edit: QueuedRunEdit): void {
5976
const recovery = resolveQueuedEditExit({
6077
editChanged:
6178
(editDraft.text.trim().length > 0 || editDraft.attachments.length > 0) &&
62-
(editDraft.text !== edit.originalText || editDraft.attachments.length > 0),
79+
(editDraft.text !== edit.originalText ||
80+
editDraft.attachments.length > 0 ||
81+
edit.removedExistingAttachment === true),
6382
threadDraftEmpty: threadDraft.text.trim().length === 0 && threadDraft.attachments.length === 0,
6483
});
6584
if (recovery === "kept") {
66-
void mergeComposerDraftContent(threadKey, {
85+
// The merge publishes the draft before writing it, so a failed write only delays persistence to the next one.
86+
mergeComposerDraftContent(threadKey, {
6787
text: editDraft.text,
6888
attachments: editDraft.attachments,
6989
...(editDraft.context ? { context: editDraft.context } : {}),
90+
}).catch((error: unknown) => {
91+
console.warn("[queued-run-edit] could not persist the recovered edit", error);
7092
});
7193
}
7294
clearComposerDraft(editDraftKey, { deferAttachmentCleanup: recovery === "kept" });
@@ -101,6 +123,7 @@ export function beginQueuedRunEdit(
101123
export function removeQueuedRunEditAttachment(threadKey: string, attachmentId: string): void {
102124
queuedRunEdits.update(threadKey, (edit) => ({
103125
...edit,
126+
removedExistingAttachment: true,
104127
existingAttachments: edit.existingAttachments.filter(
105128
(attachment) => attachment.id !== attachmentId,
106129
),

‎apps/mobile/src/state/use-thread-composer-state.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -484,7 +484,8 @@ export function useThreadComposerState() {
484484
savingQueuedEditRef.current = false;
485485
setIsSavingQueuedEdit(false);
486486
if (result._tag !== "Success") {
487-
finishSave(false);
487+
// The run left the queue during the save; its exit already told the composer what happened.
488+
if (!finishSave(false)) return;
488489
Dialog.alert(
489490
"Could not save the queued message",
490491
"It may have already started. Your edit is still in the composer.",

‎packages/client-runtime/src/queuedRunEdit.test.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,19 @@ describe("makeQueuedRunEditStore", () => {
8181
const finishSave = store.startSave("env:thread");
8282
registry.set(runs, []);
8383
expect(exits).toEqual([]);
84-
expect(finishSave?.(false)).toBe(true);
84+
expect(finishSave?.(false)).toBe(false);
8585
expect(exits).toHaveLength(1);
8686
});
8787

88+
it("reports the edit still open when a save fails while its run is queued", () => {
89+
const { store, exits, begin } = setup();
90+
begin();
91+
const finishSave = store.startSave("env:thread");
92+
expect(finishSave?.(false)).toBe(true);
93+
expect(exits).toEqual([]);
94+
expect(store.get("env:thread")).toEqual({ runId: RUN, text: "draft" });
95+
});
96+
8897
it("allows one save at a time and ends the edit when it succeeds", () => {
8998
const { registry, store, begin } = setup();
9099
begin();

‎packages/client-runtime/src/queuedRunEdit.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,9 @@ interface ExitWatch<E> {
6969
}
7070

7171
/**
72-
* Settles a save started with `startSave`. Returns false, changing nothing,
73-
* when the edit the save started from was ended or begun again meanwhile; the
74-
* caller must then leave the edit's drafts alone. Otherwise success ends the
75-
* edit and failure resumes its exit watch.
72+
* Settles a save from `startSave`. False, changing nothing, when the edit was
73+
* ended or begun again meanwhile. Success ends the edit; failure resumes its
74+
* exit watch and returns whether the edit survived it.
7675
*/
7776
export type FinishQueuedRunEditSave = (succeeded: boolean) => boolean;
7877

@@ -196,10 +195,10 @@ export function makeQueuedRunEditStore<E extends { readonly runId: RunId }>(opti
196195
if (succeeded) {
197196
stopWatch(threadKey);
198197
write(threadKey, null);
199-
} else {
200-
subscribe(threadKey, watch);
198+
return true;
201199
}
202-
return true;
200+
subscribe(threadKey, watch);
201+
return watches.get(threadKey) === watch;
203202
};
204203
},
205204
};

0 commit comments

Comments
 (0)