feat(desktop): add Bestie message handoff

Co-authored-by: Codex <noreply@openai.com>
Signed-off-by: Arjun Mahanti <arjun@squareup.com>
This commit is contained in:
Arjun Mahanti
2026-08-26 18:33:33 -04:00
committed by Fizz
parent 3072f8b0ff
commit 367b532bdb
5 changed files with 277 additions and 6 deletions

View File

@@ -0,0 +1,150 @@
import * as React from "react";
import { toast } from "sonner";
import { useManagedAgentsQuery } from "@/features/agents/hooks";
import { pickBestieAgent } from "@/features/agents/lib/bestie";
import { useOpenDmMutation } from "@/features/channels/hooks";
import { useCommunities } from "@/features/communities/useCommunities";
import { useSendMessageMutation } from "@/features/messages/hooks";
import { buildMessageLink } from "@/features/messages/lib/messageLink";
import { getThreadReference } from "@/features/messages/lib/threading";
import type { TimelineMessage } from "@/features/messages/types";
import { MessageComposer } from "@/features/messages/ui/MessageComposer";
import { ProfileAvatar } from "@/features/profile/ui/ProfileAvatar";
import { useIdentityQuery } from "@/shared/api/hooks";
import type { ManagedAgent } from "@/shared/api/types";
import { UserAvatar } from "@/shared/ui/UserAvatar";
import { VideoReviewCommentMarkdown } from "@/shared/ui/VideoReviewCommentMarkdown";
export function useBestieMessageAgent() {
const { activeCommunity } = useCommunities();
const managedAgentsQuery = useManagedAgentsQuery();
return React.useMemo(
() =>
pickBestieAgent(managedAgentsQuery.data ?? [], activeCommunity?.relayUrl),
[activeCommunity?.relayUrl, managedAgentsQuery.data],
);
}
/** The Bestie destination rendered inside the persistent message-action shell. */
export function BestieMessagePanel({
bestie,
channelId,
message,
onClose,
}: {
bestie: ManagedAgent;
channelId: string;
message: TimelineMessage;
onClose: () => void;
}) {
const { activeCommunity } = useCommunities();
const identityQuery = useIdentityQuery();
const openDmMutation = useOpenDmMutation();
const sendMessageMutation = useSendMessageMutation(null, identityQuery.data);
const isPending = openDmMutation.isPending || sendMessageMutation.isPending;
const submit = async (
note: string,
mentionPubkeys: string[],
mediaTags?: string[][],
) => {
const { rootId } = getThreadReference(message.tags ?? []);
const link = buildMessageLink({
channelId,
messageId: message.id,
threadRootId: rootId,
});
const trimmedNote = note.trim();
const content = [trimmedNote, `[Open original message](${link})`]
.filter(Boolean)
.join("\n\n");
try {
const dm = await openDmMutation.mutateAsync({
pubkeys: [bestie.pubkey],
expectedRelayUrl: activeCommunity?.relayUrl,
expectedSignerPubkey: identityQuery.data?.pubkey,
});
await sendMessageMutation.mutateAsync({
content,
mediaTags,
mentionPubkeys,
targetChannel: dm,
});
onClose();
toast.success(`Sent to ${bestie.name}`);
} catch (error) {
console.error("Failed to send message to Bestie", error);
toast.error(`Couldn't send to ${bestie.name}`);
throw error;
}
};
return (
<div
className="w-[min(328px,calc(100vw-2rem))] p-4"
data-testid={`bestie-popover-${message.id}`}
>
<div className="space-y-3.5">
<div className="flex items-center gap-2.5">
<ProfileAvatar
avatarUrl={bestie.avatarUrl}
className="size-8 text-xs"
label={bestie.name}
/>
<p className="min-w-0 truncate text-sm font-semibold">Bestie</p>
</div>
<div
className="w-3/4 overflow-hidden rounded-xl border border-border/60 bg-background p-2.5 shadow-sm"
data-testid={`bestie-message-snapshot-${message.id}`}
>
<div className="flex min-w-0 items-start gap-2">
<UserAvatar
avatarUrl={message.avatarUrl ?? null}
className="size-6 shrink-0"
displayName={message.author}
size="sm"
/>
<div className="min-w-0 flex-1">
<div className="flex min-w-0 items-baseline gap-1">
<p className="truncate text-2xs font-semibold leading-3.5">
{message.author}
</p>
<p className="shrink-0 text-3xs leading-3.5 text-muted-foreground/70">
{message.time}
</p>
</div>
<div
className="mt-0.5 max-h-3.5 overflow-hidden"
data-testid={`bestie-message-snapshot-body-${message.id}`}
>
<VideoReviewCommentMarkdown
className="line-clamp-1 text-2xs leading-3.5 text-foreground/80 [&_p]:leading-3.5"
content={message.body}
interactive={false}
messageId={message.id}
/>
</div>
</div>
</div>
</div>
<MessageComposer
allowEmptySend
channelName="Bestie"
channelType="dm"
containerClassName="px-0 pb-0"
disabled={isPending}
draftKey={`bestie-share:${message.id}`}
isSending={isPending}
onSend={submit}
placeholder="Add a note (optional)"
showBackgroundUploadProgress={false}
/>
</div>
</div>
);
}

View File

@@ -9,6 +9,11 @@ import { cn } from "@/shared/lib/cn";
import { Button } from "@/shared/ui/button";
import { isPositiveEmojiParticle } from "@/shared/ui/EmojiBurstProvider";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/shared/ui/tooltip";
import { ProfileAvatar } from "@/features/profile/ui/ProfileAvatar";
import {
BestieMessagePanel,
useBestieMessageAgent,
} from "@/features/messages/ui/BestieMessagePopover";
import type { MessageActionBarProps } from "@/features/messages/ui/MessageActionBar";
import {
MESSAGE_ACTION_BLOOM_EASE_OUT,
@@ -30,7 +35,7 @@ import {
const ACTION_BUTTON_CLASS = "h-8 w-8 rounded-full p-0";
const ACTION_ICON_CLASS = "!h-4 !w-4";
type ActiveSurface = "reactions" | "more" | null;
type ActiveSurface = "reactions" | "bestie" | "more" | null;
export function MessageActionBloomBar({
channelId,
@@ -72,9 +77,11 @@ export function MessageActionBloomBar({
"up" | "down"
>("up");
const reactionTriggerRef = React.useRef<HTMLButtonElement>(null);
const bestieTriggerRef = React.useRef<HTMLButtonElement>(null);
const moreTriggerRef = React.useRef<HTMLButtonElement>(null);
const lastSurfaceRef = React.useRef<ActiveSurface>(null);
const customEmoji = useCustomEmoji();
const bestie = useBestieMessageAgent();
const quickReactionEmojis = useQuickReactionEmojis(3, customEmoji);
const quickReactionItems = React.useMemo(
() =>
@@ -135,6 +142,7 @@ export function MessageActionBloomBar({
if (!restoreFocus) return;
window.requestAnimationFrame(() => {
if (surface === "reactions") reactionTriggerRef.current?.focus();
if (surface === "bestie") bestieTriggerRef.current?.focus();
if (surface === "more") moreTriggerRef.current?.focus();
});
}, []);
@@ -432,6 +440,30 @@ export function MessageActionBloomBar({
<TooltipContent>Reply</TooltipContent>
</Tooltip>
) : null}
{bestie && canCopyMessageLink(message, channelId) ? (
<Tooltip>
<TooltipTrigger asChild>
<Button
aria-label="Send to Bestie"
className={ACTION_BUTTON_CLASS}
data-testid={`send-to-bestie-${message.id}`}
onClick={() => openSurface("bestie")}
ref={bestieTriggerRef}
size="sm"
type="button"
variant="ghost"
>
<ProfileAvatar
avatarUrl={bestie.avatarUrl}
className="size-5 text-3xs"
label={bestie.name}
testId={`bestie-action-avatar-${message.id}`}
/>
</Button>
</TooltipTrigger>
<TooltipContent>Bestie</TooltipContent>
</Tooltip>
) : null}
{canCopyMessageLink(message, channelId) ? (
<Tooltip>
<TooltipTrigger asChild>
@@ -527,6 +559,26 @@ export function MessageActionBloomBar({
/>
</motion.div>
) : null}
{activeSurface === "bestie" && bestie && channelId ? (
<motion.div
{...panelMotion}
className={cn(
"absolute right-0",
expansionDirection === "up" ? "bottom-0" : "top-0",
)}
initial={false}
key="bestie"
ref={activeContentRef}
style={{ pointerEvents: contentReady ? "auto" : "none" }}
>
<BestieMessagePanel
bestie={bestie}
channelId={channelId}
message={message}
onClose={() => closeSurface()}
/>
</motion.div>
) : null}
</AnimatePresence>
</MessageActionBloomSurface>
</div>

View File

@@ -70,6 +70,7 @@ import { useComposerLinkPreviews } from "./useComposerLinkPreviews";
import { scheduleSettleGatedAutoSubmit } from "./messageComposerAutoSubmit";
import type { MessageComposerProps } from "./MessageComposer.types";
function MessageComposerImpl({
allowEmptySend = false,
audienceContext = null,
channelId = null,
channelName,
@@ -599,13 +600,12 @@ function MessageComposerImpl({
});
return;
}
// Normal send
const currentPendingImeta = media.pendingImetaRef.current;
const currentQueuedAttachments = media.queuedAttachmentsRef.current;
const hasMedia =
currentPendingImeta.length > 0 || currentQueuedAttachments.length > 0;
if (
(!trimmed && !hasMedia) ||
(!allowEmptySend && !trimmed && !hasMedia) ||
disabledRef.current ||
isSendingRef.current ||
isSubmitLockedRef.current ||
@@ -652,6 +652,7 @@ function MessageComposerImpl({
onPreparingMentionSendChange?.(false);
}
}, [
allowEmptySend,
channelId,
channelLinks.clearChannels,
customEmoji,
@@ -684,7 +685,6 @@ function MessageComposerImpl({
mentions.revalidateMentionPubkeys,
]);
submitMessageRef.current = submitMessage;
// Draft auto-submit runs once after persisted editor state loads.
const onAutoSubmitCompleteRef = React.useRef(onAutoSubmitComplete);
onAutoSubmitCompleteRef.current = onAutoSubmitComplete;
// biome-ignore lint/correctness/useExhaustiveDependencies: intentionally fires once on mount only
@@ -782,12 +782,12 @@ function MessageComposerImpl({
setPendingImeta: media.setPendingImeta,
uploadFile: media.uploadFile,
});
// ── Send button state ───────────────────────────────────────────────
const sendDisabled =
composerDisabled ||
media.isUploading ||
mentionSendFlow.isPreparingMentionSend ||
(isContentEmpty &&
(!allowEmptySend &&
isContentEmpty &&
media.pendingImeta.length === 0 &&
media.queuedAttachments.length === 0);
const handleCaptureSelection = React.useCallback(() => {}, []);

View File

@@ -24,6 +24,7 @@ export type MessageComposerEditTarget = {
};
export type MessageComposerProps = {
allowEmptySend?: boolean;
audienceContext?: {
type: "channel" | "thread";
} | null;

View File

@@ -376,3 +376,71 @@ test("emoji and overflow expand from one measured message toolbar surface", asyn
),
).toBeLessThanOrEqual(1);
});
test("a message can be handed to Bestie with an optional note", async ({
page,
}) => {
await installMockBridge(page, { managedAgents: [bestie] });
await page.setViewportSize({ width: 1000, height: 760 });
await page.goto("/");
await page.getByTestId("channel-general").click();
const messageId = await page.evaluate(() => {
const emit = window.__BUZZ_E2E_EMIT_MOCK_MESSAGE__;
if (!emit) throw new Error("Mock message emitter is unavailable.");
return emit({
channelName: "general",
content:
"Please fold this launch decision into tomorrow's priorities and name one owner.",
id: "d".repeat(64),
}).id;
});
const row = page.locator(`[data-message-id="${messageId}"]`);
await expect(row).toContainText("launch decision");
await row.hover();
await row.getByTestId(`send-to-bestie-${messageId}`).click();
const actionBar = row.getByTestId(`message-action-bar-${messageId}`);
const popover = page.getByTestId(`bestie-popover-${messageId}`);
await expect(actionBar).toHaveAttribute("data-bloom-surface", "bestie");
await expect(popover).toBeVisible();
await expect(popover).toContainText("Bestie");
await expect(popover).toContainText("Please fold this launch decision");
const snapshot = popover.getByTestId(`bestie-message-snapshot-${messageId}`);
const snapshotBody = popover.getByTestId(
`bestie-message-snapshot-body-${messageId}`,
);
const [popoverBox, snapshotBox, snapshotBodyBox] = await Promise.all([
popover.boundingBox(),
snapshot.boundingBox(),
snapshotBody.boundingBox(),
]);
expect(popoverBox).not.toBeNull();
expect(snapshotBox).not.toBeNull();
expect(snapshotBodyBox).not.toBeNull();
if (popoverBox && snapshotBox && snapshotBodyBox) {
expect(popoverBox.width).toBeLessThanOrEqual(328);
expect(snapshotBox.width / (popoverBox.width - 32)).toBeCloseTo(0.75, 1);
expect(Math.abs(snapshotBox.x - (popoverBox.x + 16))).toBeLessThanOrEqual(
1,
);
expect(snapshotBox.height).toBeLessThan(64);
expect(snapshotBodyBox.height).toBeLessThanOrEqual(14);
}
const composer = popover.getByTestId("message-composer");
await expect(composer.getByRole("button", { name: "Send" })).toBeEnabled();
await composer
.locator('[contenteditable="true"]')
.fill("Make sure product and engineering agree on the owner.");
await composer.getByRole("button", { name: "Send" }).click();
await expect(popover).toBeHidden();
await page.getByTestId("open-bestie-dm").click();
const sentMessage = page.getByTestId("message-row").last();
await expect(sentMessage).toContainText(
"Make sure product and engineering agree on the owner.",
);
await expect(sentMessage).toContainText("Open original message");
});