Skip to content

Commit db566eb

Browse files
loganjLarry
andcommitted
fix(desktop): retain drafts after synchronous mention extraction failure
Replay the approved first slice from 857ed203 and e0cc5522 (aggregate 58db416d). Keep extraction within failure cleanup; use the existing runtime lookup and upload error rendering through size-gate helper extractions. Remove the inherited unused markdown import for strict builds. Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Signed-off-by: Logan Johnson <[email protected]>
1 parent 802ba61 commit db566eb

7 files changed

Lines changed: 116 additions & 49 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import type { useMediaUpload } from "@/features/messages/lib/useMediaUpload";
2+
3+
/** Display the upload failure without losing the composer's retry controls. */
4+
export function ComposerUploadError({
5+
uploadState,
6+
onDismiss,
7+
}: {
8+
uploadState: ReturnType<typeof useMediaUpload>["uploadState"];
9+
onDismiss: () => void;
10+
}) {
11+
if (uploadState.status !== "error") return null;
12+
return (
13+
<div className="mb-2 rounded-lg bg-destructive/10 px-3 py-2 text-xs text-destructive">
14+
Upload failed: {uploadState.message}
15+
<button className="ml-2 underline" onClick={onDismiss} type="button">
16+
Dismiss
17+
</button>
18+
</div>
19+
);
20+
}

‎desktop/src/features/messages/ui/MessageComposer.tsx‎

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import { ComposerAttachments, DropZoneOverlay } from "./ComposerAttachments";
5252
import { focusMentionOptionsTrigger } from "./MentionAutocomplete";
5353
import { MessageComposerAutocompletes } from "./MessageComposerAutocompletes";
5454
import { ComposerDockToolbar } from "./ComposerDockToolbar";
55+
import { ComposerUploadError } from "./ComposerUploadError";
5556
import { ComposerUploadProgressPill } from "./ComposerUploadProgressPill";
5657
import { NonMemberMentionDialog } from "./NonMemberMentionDialog";
5758
import { useComposerVoiceNote } from "./useComposerVoiceNote";
@@ -897,18 +898,10 @@ function MessageComposerImpl({
897898
onOptionsRevealComplete={completeMentionOptionsReveal}
898899
onToggleAlwaysAddressAgent={toggleAlwaysAddressAgent}
899900
/>
900-
{media.uploadState.status === "error" ? (
901-
<div className="mb-2 rounded-lg bg-destructive/10 px-3 py-2 text-xs text-destructive">
902-
Upload failed: {media.uploadState.message}
903-
<button
904-
className="ml-2 underline"
905-
onClick={() => media.setUploadState({ status: "idle" })}
906-
type="button"
907-
>
908-
Dismiss
909-
</button>
910-
</div>
911-
) : null}
901+
<ComposerUploadError
902+
uploadState={media.uploadState}
903+
onDismiss={() => media.setUploadState({ status: "idle" })}
904+
/>
912905
{composerLinkPreviews}
913906
<output
914907
aria-live="polite"
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import * as React from "react";
2+
import { useAvailableAcpRuntimes } from "@/features/agents/hooks";
3+
import type { AcpRuntime } from "@/shared/api/types";
4+
5+
/** Resolve available runtimes for persona mentions without refetching warm data. */
6+
export function useMentionAvailableRuntimes() {
7+
const availableRuntimesQuery = useAvailableAcpRuntimes();
8+
const getAvailableRuntimes = React.useCallback(async (): Promise<
9+
AcpRuntime[]
10+
> => {
11+
const cached = availableRuntimesQuery.data ?? [];
12+
if (cached.length > 0 || !availableRuntimesQuery.isLoading) {
13+
return cached;
14+
}
15+
const refetched = await availableRuntimesQuery.refetch();
16+
return (refetched.data ?? []).filter(
17+
(runtime): runtime is AcpRuntime =>
18+
runtime.availability === "available" &&
19+
runtime.command !== null &&
20+
runtime.binaryPath !== null,
21+
);
22+
}, [
23+
availableRuntimesQuery.data,
24+
availableRuntimesQuery.isLoading,
25+
availableRuntimesQuery.refetch,
26+
]);
27+
return getAvailableRuntimes;
28+
}

‎desktop/src/features/messages/ui/useMentionSendFlow.authority.test.mjs‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,3 +216,35 @@ test("automatic addressed prefix is programmatic optimistic empty, not new autho
216216
assert.equal(s.store.get("thread:a").content, TEXT);
217217
assert.deepEqual(s.store.get("thread:a").mentionRefs, s.refs);
218218
});
219+
220+
for (const extractor of [
221+
"getDraftMentionRefs",
222+
"extractMentionPubkeys",
223+
"extractMentionPersonas",
224+
]) {
225+
test(`synchronous ${extractor} failure is visible and releases the send latch`, async () => {
226+
const s = await setup({ lifecycle: true });
227+
s.dismiss();
228+
s.options.mentions[extractor] = () => {
229+
throw new Error("Choose an exact recipient");
230+
};
231+
s.rerender();
232+
const input = {
233+
capturedChannelId: "general",
234+
pendingImeta: [],
235+
trimmed: TEXT,
236+
recoveryDraftKey: "thread:a",
237+
sentDraftKey: "thread:a",
238+
};
239+
for (let attempt = 0; attempt < 2; attempt++) {
240+
await s.act(async () =>
241+
s.result.current.sendMessageWithMentionFlow(input),
242+
);
243+
assert.equal(s.result.current.isPreparingMentionSend, false);
244+
assert.equal(s.options.contentRef.current, TEXT);
245+
assert.equal(s.events("error").length, attempt + 1);
246+
assert.equal(s.events("error").at(-1)[1], "Choose an exact recipient");
247+
assert.equal(s.events("SEND").length, 0);
248+
}
249+
});
250+
}

‎desktop/src/features/messages/ui/useMentionSendFlow.test-support.mjs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,10 @@ export async function setup({ lifecycle = false } = {}) {
159159
AgentMentionAuthorizationError: class extends Error {},
160160
},
161161
};
162+
stubs["./useMentionAvailableRuntimes"] = load(
163+
"useMentionAvailableRuntimes",
164+
stubs,
165+
);
162166
stubs["./useNonMemberInvite"] = load("useNonMemberInvite", stubs);
163167
stubs["./useActivePreparedLinkPreviews"] = load(
164168
"useActivePreparedLinkPreviews",

‎desktop/src/features/messages/ui/useMentionSendFlow.ts‎

Lines changed: 27 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import { toast } from "sonner";
44
import {
55
type CreateChannelManagedAgentInput,
66
useAttachManagedAgentToChannelMutation,
7-
useAvailableAcpRuntimes,
87
useCreateChannelManagedAgentMutation,
98
useManagedAgentsQuery,
109
usePersonasQuery,
@@ -15,6 +14,7 @@ import { applyReusableAgentAccessPolicy } from "@/features/agents/channelAgents"
1514
import { resolvePersonaRuntime } from "@/features/agents/lib/resolvePersonaRuntime";
1615
import { useAddChannelMembersMutation } from "@/features/channels/hooks";
1716
import { useCanAddChannelMembers } from "@/features/channels/useCanAddChannelMembers";
17+
import { useMentionAvailableRuntimes } from "./useMentionAvailableRuntimes";
1818
import { useNonMemberInvite } from "./useNonMemberInvite";
1919
import { dmThreadAgentMentionError } from "@/features/messages/lib/dmThreadAgentMentionError";
2020
import {
@@ -27,7 +27,7 @@ import {
2727
} from "@/features/messages/lib/imetaMediaMarkdown";
2828
import { useActivePreparedLinkPreviews } from "./useActivePreparedLinkPreviews";
2929
import { invokeTauri } from "@/shared/api/tauri";
30-
import type { AcpRuntime, ManagedAgent } from "@/shared/api/types";
30+
import type { ManagedAgent } from "@/shared/api/types";
3131
import { normalizePubkey, truncatePubkey } from "@/shared/lib/pubkey";
3232
import { buildCustomEmojiTags } from "@/shared/lib/customEmojiTags";
3333
import {
@@ -111,7 +111,6 @@ export function useMentionSendFlow({
111111
useCreateChannelManagedAgentMutation(channelId);
112112
const provisionPersonaAgentMutation =
113113
useProvisionChannelManagedAgentMutation(channelId);
114-
const availableRuntimesQuery = useAvailableAcpRuntimes();
115114
const managedAgentsQuery = useManagedAgentsQuery();
116115
const personasQuery = usePersonasQuery();
117116
const startAgentMutation = useStartManagedAgentMutation();
@@ -127,25 +126,7 @@ export function useMentionSendFlow({
127126
const getPersonas = React.useCallback(async () => {
128127
return personasQuery.data ?? (await personasQuery.refetch()).data ?? [];
129128
}, [personasQuery.data, personasQuery.refetch]);
130-
const getAvailableRuntimes = React.useCallback(async (): Promise<
131-
AcpRuntime[]
132-
> => {
133-
const cached = availableRuntimesQuery.data ?? [];
134-
if (cached.length > 0 || !availableRuntimesQuery.isLoading) {
135-
return cached;
136-
}
137-
const refetched = await availableRuntimesQuery.refetch();
138-
return (refetched.data ?? []).filter(
139-
(runtime): runtime is AcpRuntime =>
140-
runtime.availability === "available" &&
141-
runtime.command !== null &&
142-
runtime.binaryPath !== null,
143-
);
144-
}, [
145-
availableRuntimesQuery.data,
146-
availableRuntimesQuery.isLoading,
147-
availableRuntimesQuery.refetch,
148-
]);
129+
const getAvailableRuntimes = useMentionAvailableRuntimes();
149130
const ensureManagedAgentMentionsReady = React.useCallback(
150131
async (
151132
mentionPubkeys: string[],
@@ -669,7 +650,11 @@ export function useMentionSendFlow({
669650
await finishSend(uploaded, signal);
670651
} catch (error) {
671652
restoreComposerAfterFailure();
672-
toast.error(error instanceof AgentMentionAuthorizationError ? error.message : formatMessageSendError(error));
653+
toast.error(
654+
error instanceof AgentMentionAuthorizationError
655+
? error.message
656+
: formatMessageSendError(error),
657+
);
673658
} finally {
674659
settleUpload();
675660
}
@@ -697,7 +682,11 @@ export function useMentionSendFlow({
697682
await finishSend([]);
698683
} catch (error) {
699684
restoreComposerAfterFailure();
700-
toast.error(error instanceof AgentMentionAuthorizationError ? error.message : formatMessageSendError(error));
685+
toast.error(
686+
error instanceof AgentMentionAuthorizationError
687+
? error.message
688+
: formatMessageSendError(error),
689+
);
701690
}
702691
}
703692
} catch (error) {
@@ -762,20 +751,22 @@ export function useMentionSendFlow({
762751
}
763752
isMentionSendPendingRef.current = true;
764753
setIsMentionSendPending(true);
765-
// Capture exact selections before any async preparation can navigate the
766-
// reused editor to another draft (possibly with identical display text).
767-
claimDraftSend(effectiveDraftKey);
768-
const composerRevision = getComposerRevision();
769-
const savedMentionRefs = mentions.getDraftMentionRefs(trimmed).slice();
770-
const selectedMentionPubkeys = mentions.extractMentionPubkeys(trimmed);
771-
const selectedPersonas = mentions.extractMentionPersonas(trimmed);
772-
const isSendCancelled = () =>
773-
preparedLinkPreviews?.signal.aborted === true;
774754
let sendPromoted = false;
775-
if (preparedLinkPreviews) {
776-
activePreparedLinkPreviews.add(preparedLinkPreviews);
777-
}
778755
try {
756+
// Capture exact selections before any async preparation can navigate the
757+
// reused editor to another draft (possibly with identical display text).
758+
// Ambiguous-name extraction can throw; it owns the same visible failure
759+
// and pending-state cleanup as the asynchronous preparation below.
760+
claimDraftSend(effectiveDraftKey);
761+
const composerRevision = getComposerRevision();
762+
const savedMentionRefs = mentions.getDraftMentionRefs(trimmed).slice();
763+
const selectedMentionPubkeys = mentions.extractMentionPubkeys(trimmed);
764+
const selectedPersonas = mentions.extractMentionPersonas(trimmed);
765+
const isSendCancelled = () =>
766+
preparedLinkPreviews?.signal.aborted === true;
767+
if (preparedLinkPreviews) {
768+
activePreparedLinkPreviews.add(preparedLinkPreviews);
769+
}
779770
if (isSendCancelled()) return;
780771
const dmThreadAgentMentionErrorMessage = dmThreadAgentMentionError({
781772
trimmed,

‎desktop/src/shared/ui/markdown.tsx‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ import {
1414
type ParsedMessageLink,
1515
} from "@/features/messages/lib/messageLink";
1616
import { renderAudioMessageAttachment } from "@/features/messages/ui/AudioMessageAttachment";
17-
import { invokeTauri } from "@/shared/api/tauri";
1817
import { useChannelNavigation } from "@/shared/context/ChannelNavigationContext";
1918
import { cn } from "@/shared/lib/cn";
2019
import { parseEntityLink } from "@/shared/lib/entityLink";

0 commit comments

Comments
 (0)