Polish agent and team sharing and snapshots (#1852)

This commit is contained in:
klopez4212
2026-07-15 18:19:03 +01:00
committed by GitHub
parent c5996e13a4
commit 2f3fa586f3
54 changed files with 4212 additions and 3402 deletions

View File

@@ -27,6 +27,14 @@ export async function fetchMediaBytes(
return new Uint8Array(bytes);
}
/** Write text through the native clipboard after an asynchronous workflow. */
export async function copyTextToSystemClipboard(
text: string,
html?: string,
): Promise<void> {
await invokeTauri("copy_text_to_clipboard", { html, text });
}
/**
* Fetch an agent snapshot attachment in memory, verifying size, SHA-256, and
* snapshot decode before returning the bytes.

View File

@@ -5,12 +5,11 @@ import {
deriveImportPhase,
getProfileSyncFailures,
deriveImportToast,
buildTeamSnapshotSendArgs,
} from "../../features/agents/ui/teamSnapshotImport.lib.ts";
// Behavior tests for the team snapshot import dialog flow and the send-encode
// contract. These import and exercise the actual production functions used by
// TeamSnapshotImportDialog, useTeamActions, and TeamSnapshotSendDialog.
// Behavior tests for the team snapshot import dialog flow. These import and
// exercise the actual production functions used by TeamSnapshotImportDialog
// and useTeamActions.
// ── Factories ────────────────────────────────────────────────────────────────
@@ -236,20 +235,3 @@ test("mixed_member_outcomes_memory_errors_and_profile_sync", () => {
assert.match(toast.message, /2 memory entr/);
assert.match(toast.message, /1 member failed to sync profile/);
});
// ── buildTeamSnapshotSendArgs ────────────────────────────────────────────────
test("buildTeamSnapshotSendArgs_always_uses_png_format", () => {
const args = buildTeamSnapshotSendArgs("team-123", "core");
assert.equal(args.id, "team-123");
assert.equal(args.memoryLevel, "core");
assert.equal(args.format, "png");
});
test("buildTeamSnapshotSendArgs_passes_through_memory_level", () => {
for (const level of ["none", "core", "everything"]) {
const args = buildTeamSnapshotSendArgs("t", level);
assert.equal(args.memoryLevel, level);
assert.equal(args.format, "png", `format must be png for level "${level}"`);
}
});

View File

@@ -2,6 +2,7 @@ import React, { type CSSProperties, useEffect, useRef, useState } from "react";
export const POOF_TRIGGER_CLASS = "buzz-poof-trigger";
export const POOF_ORIGIN_CLASS = "buzz-poof-origin";
export const POOF_POINTER_ORIGIN_CLASS = "buzz-poof-pointer-origin";
export const POOF_DURATION_MS = 430;
@@ -34,15 +35,23 @@ type PoofStyle = CSSProperties & {
"--buzz-poof-y": string;
};
function getPoofOrigin(target: Element) {
type PoofPointer = {
x: number;
y: number;
};
function getPoofOrigin(target: Element, pointer?: PoofPointer) {
const origin = target.closest(`.${POOF_ORIGIN_CLASS}`) ?? target;
const rect = origin.getBoundingClientRect();
const baseSize = Math.min(Math.max(rect.width * 0.54, 104), 190);
const usesPointerOrigin = Boolean(
pointer && target.closest(`.${POOF_POINTER_ORIGIN_CLASS}`),
);
return {
size: baseSize * POOF_SIZE_SCALE,
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2,
x: usesPointerOrigin && pointer ? pointer.x : rect.left + rect.width / 2,
y: usesPointerOrigin && pointer ? pointer.y : rect.top + rect.height / 2,
};
}
@@ -148,14 +157,12 @@ export function PoofBurstProvider({ children }: { children: React.ReactNode }) {
}, []);
useEffect(() => {
function emitPoof(target: Element) {
function emitPoof(target: Element, pointer?: PoofPointer) {
const id = idRef.current;
idRef.current += 1;
const origin = getPoofOrigin(target, pointer);
setBursts((current) => [
...current.slice(-5),
{ ...getPoofOrigin(target), id },
]);
setBursts((current) => [...current.slice(-5), { ...origin, id }]);
playPoofSound();
const timeoutId = window.setTimeout(() => {
@@ -187,7 +194,7 @@ export function PoofBurstProvider({ children }: { children: React.ReactNode }) {
lastPointerDownTrigger = null;
}
}, POOF_DURATION_MS);
emitPoof(target);
emitPoof(target, { x: event.clientX, y: event.clientY });
}
function handleDocumentClick(event: MouseEvent) {

View File

@@ -1340,8 +1340,13 @@ function createMarkdownComponents(
href,
...props
}: React.ComponentPropsWithoutRef<"a">) {
const { channels, imetaByUrl, onOpenMessageLink, onImportSnapshotFromUrl } =
useMarkdownRuntime();
const {
channels,
imetaByUrl,
onOpenMessageLink,
onImportSnapshotFromUrl,
snapshotSharedBy,
} = useMarkdownRuntime();
if (!interactive) {
return <span className="font-medium text-current">{children}</span>;
}
@@ -1365,8 +1370,10 @@ function createMarkdownComponents(
if (snapshotCard) {
return (
<AgentSnapshotCard
displayName={snapshotCard.displayName}
href={snapshotCard.href}
filename={snapshotCard.filename}
sharedBy={snapshotSharedBy}
size={snapshotCard.size}
sha256={snapshotCard.sha256}
snapshotKind={snapshotCard.snapshotKind}
@@ -1822,6 +1829,7 @@ function MarkdownInner({
mentionNames,
mentionPubkeysByName,
searchQuery,
snapshotSharedBy,
videoReviewContext,
}: MarkdownProps) {
const { channels: rawChannels } = useChannelNavigation();
@@ -1865,6 +1873,7 @@ function MarkdownInner({
mentionPubkeysByName,
onOpenChannel,
onOpenMessageLink,
snapshotSharedBy,
onImportSnapshotFromUrl: (
fileBytes: number[],
fileName: string,
@@ -1881,6 +1890,7 @@ function MarkdownInner({
mentionPubkeysByName,
onOpenChannel,
onOpenMessageLink,
snapshotSharedBy,
goAgents,
],
);
@@ -1984,6 +1994,7 @@ export const Markdown = React.memo(
prev.imetaByUrl === next.imetaByUrl &&
prev.configNudgeAuthorPubkey === next.configNudgeAuthorPubkey &&
prev.searchQuery === next.searchQuery &&
prev.snapshotSharedBy === next.snapshotSharedBy &&
prev.videoReviewContext === next.videoReviewContext,
);
Markdown.displayName = "Markdown";

View File

@@ -1,13 +1,24 @@
import * as React from "react";
import { AlertCircle, Bot, Download, Loader2 } from "lucide-react";
import { Bot, Download, Loader2, Users } from "lucide-react";
import { invokeTauri } from "@/shared/api/tauri";
import { fetchSnapshotBytes } from "@/shared/api/tauriMedia";
import { useSmoothCorners } from "@/shared/ui/smoothCorners";
import { cn } from "@/shared/lib/cn";
import {
Attachment,
AttachmentAction,
AttachmentActions,
AttachmentContent,
AttachmentDescription,
AttachmentMedia,
AttachmentTitle,
} from "@/shared/ui/attachment";
export type AgentSnapshotCardProps = {
displayName: string;
href: string;
filename: string;
sharedBy?: string;
size?: number;
sha256: string;
/** Discriminant used to label the card and route the import. */
@@ -34,29 +45,28 @@ type ImportState =
| { phase: "error"; message: string };
/**
* Snapshot attachment card rendered in a message timeline when an `.agent.json`
* or `.agent.png` attachment is classified as an agent snapshot candidate.
* Snapshot attachment card rendered in a message timeline when an agent or
* team snapshot attachment is classified as an importable snapshot candidate.
*
* Shows two independent actions:
* - **Import agent** — bounded, verified in-memory fetch → existing importer
* - **Add agent/team** — bounded, verified in-memory fetch → existing importer
* - **Download** — native save dialog via the unchanged `download_file` command
*
* The card text identifies the attachment as "Agent snapshot" (untrusted label)
* until the bytes have been verified by the Rust decoder; the sender-supplied
* agent name is never shown here.
* The display name and sharer are presentation-only message metadata. Import
* still fetches and verifies the snapshot bytes before the existing preview
* flow presents the decoded snapshot details.
*/
export function AgentSnapshotCard({
displayName,
href,
filename,
sharedBy,
size,
sha256,
snapshotKind,
thumb,
onImport,
}: AgentSnapshotCardProps) {
const cardRef = React.useRef<HTMLDivElement | null>(null);
useSmoothCorners(cardRef);
const [importState, setImportState] = React.useState<ImportState>({
phase: "idle",
});
@@ -80,7 +90,9 @@ export function AgentSnapshotCard({
setImportState({
phase: "error",
message:
err instanceof Error ? err.message : "Failed to fetch snapshot.",
err instanceof Error
? err.message
: `Couldn’t load this ${snapshotKind}. Try again.`,
});
} finally {
inFlightRef.current = false;
@@ -94,88 +106,109 @@ export function AgentSnapshotCard({
}
const isFetching = importState.phase === "fetching";
const SnapshotIcon = snapshotKind === "team" ? Users : Bot;
const showThumb = !!thumb && !thumbError;
const formattedSize =
size == null
? null
: size < 1024
? `${size} B`
: size < 1024 * 1024
? `${(size / 1024).toFixed(1)} KB`
: `${(size / (1024 * 1024)).toFixed(1)} MB`;
const metadata = [sharedBy ? `Shared by ${sharedBy}` : null, formattedSize]
.filter(Boolean)
.join(" · ");
return (
<div
ref={cardRef}
className="my-1 inline-flex max-w-sm flex-col gap-2 rounded-2xl border border-primary/25 bg-primary/5 px-3 py-2 text-left"
style={{ borderRadius: "1rem" }}
<Attachment
className="my-1 inline-flex w-fit max-w-full shadow-none"
data-testid="agent-snapshot-card"
state={importState.phase === "error" ? "error" : "done"}
>
{/* Header row: icon + filename */}
<div className="flex items-center gap-2">
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary overflow-hidden">
{showThumb ? (
<AttachmentMedia
className={cn(
showThumb
? "relative h-9 w-9"
: "bg-primary/10 text-primary ring-1 ring-primary/20 dark:bg-primary/15",
)}
variant={showThumb ? "image" : "icon"}
>
{showThumb ? (
<>
<img
alt=""
className="h-full w-full object-cover"
aria-hidden="true"
className="pointer-events-none absolute inset-0 h-full w-full scale-150 object-cover"
src={thumb}
referrerPolicy="no-referrer"
/>
<img
alt=""
className="relative h-full w-full object-cover"
data-testid="agent-snapshot-card-thumb"
src={thumb}
referrerPolicy="no-referrer"
onError={() => setThumbError(true)}
/>
) : (
<Bot className="h-4 w-4" />
)}
</span>
<div className="min-w-0 flex-1">
<span
className="block truncate text-sm font-medium text-foreground"
title={filename}
>
{filename}
</span>
<span className="block text-xs text-muted-foreground">
{snapshotKind === "team" ? "Team snapshot" : "Agent snapshot"}
{size != null
? ` · ${size < 1024 ? `${size} B` : size < 1024 * 1024 ? `${(size / 1024).toFixed(1)} KB` : `${(size / (1024 * 1024)).toFixed(1)} MB`}`
: ""}
</span>
</div>
</div>
{/* Error row */}
{importState.phase === "error" && (
<div
className="flex items-start gap-1.5 rounded-md border border-destructive/30 bg-destructive/10 px-2 py-1 text-xs text-destructive"
data-testid="agent-snapshot-card-error"
</>
) : (
<SnapshotIcon />
)}
</AttachmentMedia>
<AttachmentContent>
<AttachmentTitle
className="overflow-visible whitespace-normal text-clip"
title={displayName}
>
<AlertCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
<span>{importState.message}</span>
</div>
)}
{/* Action row */}
<div className="flex items-center gap-2">
<button
{displayName}
</AttachmentTitle>
{importState.phase === "error" ? (
<AttachmentDescription
className="overflow-visible whitespace-normal text-clip text-destructive"
data-testid="agent-snapshot-card-error"
>
{importState.message}
</AttachmentDescription>
) : metadata ? (
<AttachmentDescription className="overflow-visible whitespace-normal text-clip text-secondary-foreground/75">
{metadata}
</AttachmentDescription>
) : null}
</AttachmentContent>
<AttachmentActions
aria-label={`Actions for ${displayName}`}
className="ml-4 gap-2"
role="group"
>
<AttachmentAction
aria-label={`Download ${displayName}`}
data-testid="agent-snapshot-card-download"
onClick={handleDownload}
size="icon"
title="Download"
type="button"
variant="ghost"
>
<Download />
</AttachmentAction>
<AttachmentAction
className="text-primary-foreground shadow-none hover:bg-primary/90 hover:text-primary-foreground hover:shadow-none"
data-testid="agent-snapshot-card-import"
disabled={isFetching}
onClick={handleImport}
className="flex h-7 flex-1 items-center justify-center gap-1.5 rounded-lg bg-primary px-3 text-xs font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50"
data-testid="agent-snapshot-card-import"
>
{isFetching ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Bot className="h-3.5 w-3.5" />
)}
{isFetching
? "Fetching…"
: snapshotKind === "team"
? "Import team"
: "Import agent"}
</button>
<button
size="sm"
type="button"
onClick={handleDownload}
className="flex h-7 items-center justify-center gap-1 rounded-lg border border-border bg-background px-3 text-xs font-medium text-foreground transition-colors hover:bg-muted"
data-testid="agent-snapshot-card-download"
variant="default"
>
<Download className="h-3 w-3" />
Download
</button>
</div>
</div>
{isFetching ? <Loader2 className="animate-spin" /> : <SnapshotIcon />}
{isFetching
? "Loading…"
: snapshotKind === "team"
? "Add team"
: "Add agent"}
</AttachmentAction>
</AttachmentActions>
</Attachment>
);
}

View File

@@ -32,6 +32,8 @@ export type MarkdownRuntime = {
mentionPubkeysByName?: Record<string, string>;
onOpenChannel: (channelId: string) => void;
onOpenMessageLink: (link: ParsedMessageLink) => void;
/** Display name of the message author sharing an agent snapshot. */
snapshotSharedBy?: string;
/**
* Called by AgentSnapshotCard after a successful verified in-memory fetch.
* The implementation should navigate to /agents and trigger the existing
@@ -58,6 +60,8 @@ export type MarkdownProps = {
mentionPubkeysByName?: Record<string, string>;
mediaInset?: boolean;
searchQuery?: string;
/** Display name shown in shared-agent card metadata. */
snapshotSharedBy?: string;
videoReviewContext?: VideoReviewContext;
/**
* When set and the nudge payload's agent_pubkey matches, renders the

View File

@@ -94,6 +94,7 @@ test("resolveSnapshotCard: .agent.json with sha256 returns snapshot card", () =>
"",
);
assert.ok(card !== null, "expected a snapshot card");
assert.equal(card.displayName, "Analyst");
assert.equal(card.filename, "analyst.agent.json");
assert.equal(card.sha256, SHA256);
assert.equal(card.snapshotKind, "agent");
@@ -107,10 +108,27 @@ test("resolveSnapshotCard: .agent.png with image/png mime returns snapshot card"
"",
);
assert.ok(card !== null);
assert.equal(card.displayName, "Analyst");
assert.equal(card.filename, "analyst.agent.png");
assert.equal(card.snapshotKind, "agent");
});
test("resolveSnapshotCard: sender label is used as the agent name", () => {
const card = resolveSnapshotCard(
{
m: "image/png",
size: 2048,
filename: "animation-auditor.agent.png",
x: SHA256,
},
PNG_URL,
"Animation Auditor",
);
assert.ok(card !== null);
assert.equal(card.displayName, "Animation Auditor");
assert.equal(card.filename, "animation-auditor.agent.png");
});
test("resolveSnapshotCard: .agent.json with octet-stream mime is eligible", () => {
// JSON snapshots often arrive as application/octet-stream.
const card = resolveSnapshotCard(
@@ -283,7 +301,7 @@ test("resolveSnapshotCard: .team.png with image/png returns team snapshot card",
);
assert.ok(card !== null);
assert.equal(card.snapshotKind, "team");
assert.ok(card.thumb != null, "PNG team card must have a thumb");
assert.equal(card.thumb, undefined);
});
test("resolveSnapshotCard: plain .team without suffix is not a snapshot", () => {

View File

@@ -25,6 +25,8 @@ export type ResolvedFileCard = {
* can share the same routing path without mixing agent-only assumptions.
*/
export type ResolvedSnapshotCard = {
/** Sender-provided display label, with a filename-derived fallback. */
displayName: string;
href: string;
filename: string;
size?: number;
@@ -40,6 +42,23 @@ export type ResolvedSnapshotCard = {
thumb?: string;
};
function snapshotDisplayName(filename: string, childText: string): string {
const label = childText.trim();
const labelIsSnapshotFilename = /\.agent\.(?:json|png)$/i.test(label);
if (label && !labelIsSnapshotFilename) return label;
const filenameStem = filename
.replace(/\.agent\.(?:json|png)$/i, "")
.replace(/[-_]+/g, " ")
.trim();
if (!filenameStem) return "Agent";
return filenameStem
.split(/\s+/)
.map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`)
.join(" ");
}
/**
* Classify a markdown link as a snapshot candidate.
*
@@ -86,14 +105,15 @@ export function resolveSnapshotCard(
const snapshotKind: "agent" | "team" = isJson || isPng ? "agent" : "team";
return {
displayName: snapshotDisplayName(filename, childText),
href,
filename,
size: entry.size,
sha256,
snapshotKind,
// PNG snapshots use the attachment URL as the thumb source because it is
// the avatar card image. JSON snapshots use the generic icon.
thumb: isAnyPng ? rewriteRelayUrl(href) : undefined,
// Agent PNG snapshots carry the avatar card image. Team PNG snapshots use
// a transport placeholder, so render the team icon instead of that image.
thumb: isPng ? rewriteRelayUrl(href) : undefined,
};
}