The best way to control Claude Code, Codex and more from any computer or phone

main
ts 57 lines 2.12 KB
Raw
1 import type { QueuedThreadMessage } from "./thread-outbox-model";
2 import type { DraftComposerAttachment } from "../lib/composerImages";
3 import { scopedThreadKey } from "../lib/scopedEntities";
4 import { abortComposerDraftOperations } from "./composerDraftOperations";
5 import { restoredNewTaskDraftKey } from "./new-task-draft-key";
6 import {
7 appendComposerDraftAttachments,
8 clearComposerDraftContent,
9 flushComposerDrafts,
10 getComposerDraftSnapshot,
11 mergeComposerDraftContent,
12 } from "./use-composer-drafts";
13
14 export async function recoverFailedThreadDraft(message: QueuedThreadMessage): Promise<void> {
15 const sourceKey = scopedThreadKey(message.environmentId, message.threadId);
16 const targetKey = restoredNewTaskDraftKey(message.messageId);
17 const source = getComposerDraftSnapshot(sourceKey);
18 if (source.text.length === 0 && source.attachments.length === 0) {
19 abortComposerDraftOperations(sourceKey);
20 return;
21 }
22
23 await mergeComposerDraftContent(targetKey, {
24 text: source.text,
25 context: source.context,
26 attachments: [],
27 });
28 // Recovery may exceed caps; preserve every file and leave trimming to the editor.
29 appendComposerDraftAttachments(targetKey, attachmentsMissingFrom(targetKey, source.attachments), {
30 restore: true,
31 });
32 await flushComposerDrafts();
33 abortComposerDraftOperations(sourceKey);
34 // A paste still preparing can land in the source during the saves; move it with its reference.
35 const sourceIds = new Set(source.attachments.map((attachment) => attachment.id));
36 appendComposerDraftAttachments(
37 targetKey,
38 attachmentsMissingFrom(
39 targetKey,
40 getComposerDraftSnapshot(sourceKey).attachments.filter(
41 (attachment) => !sourceIds.has(attachment.id),
42 ),
43 ),
44 { restore: true, appendReference: true },
45 );
46 clearComposerDraftContent(sourceKey);
47 }
48
49 function attachmentsMissingFrom(
50 draftKey: string,
51 attachments: ReadonlyArray<DraftComposerAttachment>,
52 ) {
53 const existingIds = new Set(
54 getComposerDraftSnapshot(draftKey).attachments.map((attachment) => attachment.id),
55 );
56 return attachments.filter((attachment) => !existingIds.has(attachment.id));
57 }