Skip to content

Commit bb90548

Browse files
shivamhwpclaude
andcommitted
fix(mobile): relaunch a created thread's unchanged first message instead of assuming it landed
The server commits thread.create and the first message.dispatch separately, so a thread in the shell list does not prove its first message was accepted. Removing an unchanged queued creation once its thread appeared could drop a message the server never got. An unchanged creation whose thread exists is now relaunched with the same command and message ids. The server replays that launch, finishing a claim-only launch or returning the earlier result, and only its success removes the queued task. Edited and legacy creations still recover into the composer. Delivery also rechecks operate access, payload, and the editor or deletion hold after recording the launch, so a task deleted during that write is never started. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent f240f14 commit bb90548

4 files changed

Lines changed: 143 additions & 38 deletions

File tree

‎apps/mobile/src/state/thread-outbox-model.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,10 @@ export function queuedMessageContentKey(message: QueuedThreadMessage): string {
145145
]);
146146
}
147147

148+
export function isQueuedLaunchContentUnchanged(message: QueuedThreadMessage): boolean {
149+
return message.dispatchedContentKey === queuedMessageContentKey(message);
150+
}
151+
148152
export function encodeQueuedThreadMessage(message: QueuedThreadMessage): unknown {
149153
return encodeStoredQueuedThreadMessage({
150154
schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION,
@@ -198,9 +202,14 @@ export function resolveThreadOutboxDeliveryAction(input: {
198202
* only a settled family read without the row is.
199203
*/
200204
readonly familyRead?: ThreadFamilyRead;
205+
/**
206+
* A created thread does not prove its first message landed. Relaunching the unchanged
207+
* content replays the same command, and only its success settles the creation.
208+
*/
209+
readonly launchedContentUnchanged?: boolean;
201210
}): ThreadOutboxDeliveryAction {
202211
if (input.isCreation) {
203-
if (input.threadExists) {
212+
if (input.threadExists && input.launchedContentUnchanged !== true) {
204213
return "remove";
205214
}
206215
// Wait for live shells; an unsynchronized list can hide delivered creations and cause duplicate re-issuance.

‎apps/mobile/src/state/thread-outbox.test.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1191,7 +1191,7 @@ describe("thread outbox", () => {
11911191
).toBe("wait");
11921192
});
11931193

1194-
it("sends queued creations once connected and live, removing already-created ones", () => {
1194+
it("sends queued creations once connected and live, relaunching unchanged already-created ones", () => {
11951195
expect(
11961196
resolveThreadOutboxDeliveryAction({
11971197
isCreation: true,
@@ -1224,6 +1224,14 @@ describe("thread outbox", () => {
12241224
environmentConnected: true,
12251225
}),
12261226
).toBe("remove");
1227+
const launched = {
1228+
isCreation: true,
1229+
threadExists: true,
1230+
launchedContentUnchanged: true,
1231+
environmentConnected: true,
1232+
} as const;
1233+
expect(resolveThreadOutboxDeliveryAction({ ...launched, shellStatus: "live" })).toBe("send");
1234+
expect(resolveThreadOutboxDeliveryAction({ ...launched, shellStatus: "cached" })).toBe("wait");
12271235
});
12281236

12291237
it("round-trips queued PR checkout sources and gates incomplete creations from sending", () => {

‎apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts‎

Lines changed: 102 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ const state = vi.hoisted(() => ({
3131
manager: null as unknown as ReturnType<
3232
typeof import("./thread-outbox-manager").createThreadOutboxManager
3333
>,
34+
// Encoded records, as the app's storage holds them across restarts.
35+
stored: new Map<string, unknown>(),
36+
beforeWrite: null as (() => Promise<void>) | null,
37+
createManager: null as unknown as () => ReturnType<
38+
typeof import("./thread-outbox-manager").createThreadOutboxManager
39+
>,
3440
thread: {
3541
environmentId: "secondary",
3642
id: "thread",
@@ -109,17 +115,33 @@ vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "abcd" })
109115
vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: state.prepare }));
110116
vi.mock("./thread-outbox", async () => {
111117
const { createThreadOutboxManager } = await import("./thread-outbox-manager");
118+
const { decodeQueuedThreadMessage, encodeQueuedThreadMessage } =
119+
await import("./thread-outbox-model");
112120
const { appAtomRegistry } = await import("./atom-registry");
113-
state.manager = createThreadOutboxManager({
114-
registry: appAtomRegistry,
115-
storage: {
116-
load: async () => ({ messages: [], errors: [] }),
117-
write: async () => {},
118-
remove: async () => {},
119-
},
120-
});
121+
state.createManager = () =>
122+
createThreadOutboxManager({
123+
registry: appAtomRegistry,
124+
storage: {
125+
load: async () => ({
126+
messages: [...state.stored.values()].map((record) => decodeQueuedThreadMessage(record)),
127+
errors: [],
128+
}),
129+
write: async (message) => {
130+
await state.beforeWrite?.();
131+
state.stored.set(message.messageId, encodeQueuedThreadMessage(message));
132+
},
133+
remove: async (message) => {
134+
state.stored.delete(message.messageId);
135+
},
136+
},
137+
});
138+
state.manager = state.createManager();
121139
return {
122-
threadOutboxManager: state.manager,
140+
// A restart swaps the manager; delivery keeps its module-level reference.
141+
threadOutboxManager: new Proxy(
142+
{},
143+
{ get: (_target, key) => state.manager[key as keyof typeof state.manager] },
144+
),
123145
threadOutboxRevision: (id: MessageId) => state.manager.revisionOf(id),
124146
confirmThreadOutboxMessageQueued: (message: QueuedThreadMessage) =>
125147
state.manager.confirmQueued(message),
@@ -212,6 +234,8 @@ beforeEach(() => {
212234
setOperateGrant("primary", true);
213235
setOperateGrant("secondary", false);
214236
state.draftText = "Keep this draft separate";
237+
state.stored.clear();
238+
state.beforeWrite = null;
215239
state.config.shellThreadFamilies = false;
216240
state.modelUnavailable.mockReset().mockReturnValue(false);
217241
state.familyMount.mockReset().mockReturnValue(() => {});
@@ -553,25 +577,37 @@ describe("compaction before a queued send", () => {
553577
});
554578

555579
describe("a new task whose launch reply was lost", () => {
580+
const queuedCreation = () =>
581+
message({
582+
threadId: ThreadId.make("new-thread"),
583+
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
584+
creation: {
585+
projectId: ProjectId.make("project"),
586+
projectCwd: "/repo",
587+
workspaceMode: "local",
588+
branch: null,
589+
worktreePath: null,
590+
},
591+
});
592+
const lostReply = () => AsyncResult.failure(Cause.fail(new Error("Socket is not connected")));
593+
556594
it.each([
557-
{ change: "unchanged", edit: null, recovered: null },
558-
{ change: "edited", edit: { text: "Edited after launch" }, recovered: "Edited after launch" },
595+
{ change: "unchanged", edit: null, relaunch: "accepted", starts: 2, kept: 0, recovered: null },
596+
// The shell can exist without the first message: the server commits them separately.
597+
{ change: "unchanged", edit: null, relaunch: "lost", starts: 2, kept: 1, recovered: null },
598+
{
599+
change: "edited",
600+
edit: { text: "Edited after launch" },
601+
relaunch: null,
602+
starts: 1,
603+
kept: 0,
604+
recovered: "Edited after launch",
605+
},
559606
])(
560-
"drops the launched task once its thread appears, recovering only edits ($change)",
561-
async ({ edit, recovered }) => {
607+
"after a restart, settles a created thread only on an accepted launch ($change, relaunch $relaunch)",
608+
async ({ edit, relaunch, starts, kept, recovered }) => {
562609
setOperateGrant("secondary", true);
563-
const queued = message({
564-
threadId: ThreadId.make("new-thread"),
565-
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
566-
creation: {
567-
projectId: ProjectId.make("project"),
568-
projectCwd: "/repo",
569-
workspaceMode: "local",
570-
branch: null,
571-
worktreePath: null,
572-
},
573-
});
574-
await state.manager.enqueue(queued);
610+
await state.manager.enqueue(queuedCreation());
575611
const started = Promise.withResolvers<void>();
576612
const reply = Promise.withResolvers<AsyncResult.AsyncResult<unknown, Error>>();
577613
state.start.mockImplementationOnce(() => {
@@ -580,27 +616,61 @@ describe("a new task whose launch reply was lost", () => {
580616
});
581617
const drained = runDrain();
582618
await started.promise;
583-
// The launch committed, so its thread reaches the shell, but the reply never arrives.
584619
appAtomRegistry.set(state.threadShells, [
585620
state.thread,
586621
{ ...state.thread, id: "new-thread" },
587622
]);
588-
reply.resolve(AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))));
623+
reply.resolve(lostReply());
589624
await drained;
590-
expect(remaining()).toHaveLength(1);
591625
if (edit !== null) {
592-
await state.manager.update({ ...remaining()[0]!, ...edit });
626+
expect(await state.manager.update({ ...remaining()[0]!, ...edit })).toBe(true);
593627
}
594628

595-
// A relaunched app finds the thread already created.
629+
// A relaunched app hydrates a fresh manager from the stored records.
596630
state.cleanups.splice(0).forEach((cleanup) => cleanup());
631+
state.manager = state.createManager();
632+
expect(await state.manager.load()).toBe(true);
633+
expect(remaining()).toHaveLength(1);
634+
expect(remaining()[0]!.dispatchedContentKey).toBeDefined();
635+
if (relaunch === "lost") state.start.mockResolvedValueOnce(lostReply());
597636
await runDrain();
598637

599-
expect(state.start).toHaveBeenCalledOnce();
600-
expect(remaining()).toEqual([]);
638+
expect(state.start).toHaveBeenCalledTimes(starts);
639+
if (starts === 2) {
640+
expect(state.start.mock.calls[1]![0].input).toMatchObject({
641+
commandId: "command",
642+
message: { messageId: "message", text: "Keep this queued" },
643+
});
644+
}
645+
expect(remaining()).toHaveLength(kept);
646+
expect(state.stored.size).toBe(kept);
601647
expect(state.draftText).toBe(
602648
recovered === null ? "Keep this draft separate" : `Keep this draft separate\n${recovered}`,
603649
);
604650
},
605651
);
652+
653+
it.each([
654+
{
655+
change: "a deletion holds the task",
656+
apply: () => appAtomRegistry.set(editingQueuedMessageIdsAtom, { message: true }),
657+
},
658+
{ change: "operation access is revoked", apply: () => setOperateGrant("secondary", false) },
659+
])("does not launch when $change while the launch is being recorded", async ({ apply }) => {
660+
setOperateGrant("secondary", true);
661+
await state.manager.enqueue(queuedCreation());
662+
const writing = Promise.withResolvers<void>();
663+
const write = Promise.withResolvers<void>();
664+
state.beforeWrite = () => {
665+
writing.resolve();
666+
return write.promise;
667+
};
668+
const drained = runDrain();
669+
await writing.promise;
670+
apply();
671+
write.resolve();
672+
await drained;
673+
expect(state.start).not.toHaveBeenCalled();
674+
expect(remaining()).toHaveLength(1);
675+
});
606676
});

‎apps/mobile/src/state/threadOutboxDelivery.ts‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ import {
5858
} from "./thread-outbox";
5959
import { removeThreadOutboxMessage } from "./thread-outbox-removal";
6060
import {
61+
isQueuedLaunchContentUnchanged,
6162
isQueuedThreadCreationSendable,
6263
queuedMessageContentKey,
6364
resolveThreadOutboxDeliveryAction,
@@ -326,8 +327,10 @@ export async function removeAcknowledgedExistingThreadMessage(
326327
}
327328
}
328329

330+
/** `acceptedContentKey` is the content of a launch the server acknowledged. */
329331
export async function recoverEditedCreationAfterDelivery(
330332
queuedMessage: QueuedThreadMessage,
333+
acceptedContentKey?: string,
331334
): Promise<boolean> {
332335
const kept = Object.values(appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom))
333336
.flat()
@@ -339,8 +342,8 @@ export async function recoverEditedCreationAfterDelivery(
339342
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[kept.messageId]) {
340343
return true;
341344
}
342-
if (kept.dispatchedContentKey === queuedMessageContentKey(kept)) {
343-
// The launch already carried this content; restoring it would let the user send it twice.
345+
if (acceptedContentKey !== undefined && queuedMessageContentKey(kept) === acceptedContentKey) {
346+
// The server has this content; restoring it would let the user send it twice.
344347
try {
345348
await removeDeliveredCloudQueuedMessage(kept).catch((error) => {
346349
console.warn("[thread-outbox] could not update sign-out snapshot after delivery", {
@@ -1113,6 +1116,14 @@ export function createThreadOutboxDelivery(): {
11131116
persistedMessage = dispatchedMessage;
11141117
deliveryRevision += 1;
11151118
}
1119+
// Deletion takes the editor hold without a revision bump, so recheck it after the awaits above.
1120+
if (!hasAccess() || !isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) {
1121+
return true;
1122+
}
1123+
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
1124+
await preserveUploadedAttachmentsForEditor(queuedMessage, persistedMessage);
1125+
return true;
1126+
}
11161127
const deliveryResult = await runDeliveryCommand(threadEnvironment.startTurn, {
11171128
environmentId: queuedMessage.environmentId,
11181129
input: buildProjectThreadStartTurnInput({
@@ -1160,7 +1171,10 @@ export function createThreadOutboxDelivery(): {
11601171
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
11611172
return true;
11621173
}
1163-
return recoverEditedCreationAfterDelivery(persistedMessage);
1174+
return recoverEditedCreationAfterDelivery(
1175+
persistedMessage,
1176+
queuedMessageContentKey(persistedMessage),
1177+
);
11641178
}
11651179
return outcome === "removed";
11661180
};
@@ -1309,11 +1323,14 @@ export function createThreadOutboxDelivery(): {
13091323
);
13101324
}
13111325
}
1326+
const launchedContentUnchanged =
1327+
creation !== undefined && isQueuedLaunchContentUnchanged(nextQueuedMessage);
13121328
const deliveryAction = resolveThreadOutboxDeliveryAction({
13131329
isCreation: creation !== undefined,
13141330
threadExists: thread !== undefined,
13151331
shellStatus,
13161332
environmentConnected: environment?.connectionState === "connected",
1333+
launchedContentUnchanged,
13171334
...(familyRead === undefined ? {} : { familyRead }),
13181335
});
13191336
if (
@@ -1409,14 +1426,15 @@ export function createThreadOutboxDelivery(): {
14091426
threadExists: liveThread !== undefined,
14101427
shellStatus,
14111428
environmentConnected: environment?.connectionState === "connected",
1429+
launchedContentUnchanged,
14121430
});
14131431
if (liveDeliveryAction !== "send") {
14141432
return true;
14151433
}
14161434
}
14171435
return deliveryAction === "remove"
14181436
? creation !== undefined
1419-
? // Recovery drops it when the persisted launch content still matches, else saves the edit.
1437+
? // Edited or legacy content: the composer keeps it, since its acceptance is unknown.
14201438
recoverEditedCreationAfterDelivery(nextQueuedMessage)
14211439
: removeQueuedMessage("[thread-outbox] failed to remove message for a missing thread")
14221440
: creation !== undefined

0 commit comments

Comments
 (0)