Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions desktop/desktop/main.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
nativeTheme,
session,
} from "electron";
import { writeFile } from "node:fs/promises";
import { fileURLToPath, pathToFileURL } from "node:url";
import { join } from "node:path";
import { chunk, fileDetails, publicFile } from "./artifact-files.mjs";
Expand Down Expand Up @@ -568,6 +569,46 @@ else
installFace: faces.install,
removeFace: faces.remove,
purgeFaces: faces.purge,
saveCardImage: async (rect, suggestedName) => {
if (!win || win.isDestroyed()) throw new Error("Window is unavailable.");
const x = Math.max(0, Math.round(Number(rect?.x ?? 0)));
const y = Math.max(0, Math.round(Number(rect?.y ?? 0)));
const width = Math.max(1, Math.round(Number(rect?.width ?? 0)));
const height = Math.max(1, Math.round(Number(rect?.height ?? 0)));
const image = await win.webContents.capturePage({ x, y, width, height });
const png = image.toPNG();
const slug = String(suggestedName ?? "")
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 64) || "card";
const filePath = await host.dialogs.save({
title: "Save card as image",
defaultPath: join(host.paths.documents(), `${slug}.png`),
filters: [{ name: "PNG Image", extensions: ["png"] }],
});
if (!filePath) return { saved: false };
await writeFile(filePath, png);
return { saved: true, path: filePath };
},
saveMessagePdf: async (htmlContent, title) => {
const pdf = await host.pdf(String(htmlContent ?? ""));
const slug = String(title ?? "")
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 64) || "message";
const filePath = await host.dialogs.save({
title: "Save message as PDF",
defaultPath: join(host.paths.documents(), `${slug}.pdf`),
filters: [{ name: "PDF Document", extensions: ["pdf"] }],
});
if (!filePath) return { saved: false };
await writeFile(filePath, pdf);
return { saved: true, path: filePath };
},
"link.pullRequests": (where, query) => runtime.link.prs.lookup(where, query),
"link.pullRequest": (input) => runtime.link.prs.panel(input),
"link.pullRequestDiff": (input) => runtime.link.prs.panel(input, true),
Expand Down
2 changes: 2 additions & 0 deletions desktop/desktop/preload.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,8 @@ for (const name of [
"retry",
"compact",
"copyText",
"saveCardImage",
"saveMessagePdf",
"auth",
"signIn",
"cancelSignIn",
Expand Down
2 changes: 2 additions & 0 deletions desktop/desktop/remotehosts.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ export const HERE = new Set([
"viewing",
"openLink",
"copyText",
"saveCardImage",
"saveMessagePdf",
"showEmojiPanel",
"artifactMessagePage",
"artifactMedia",
Expand Down
7 changes: 6 additions & 1 deletion desktop/src/A2uiSurface.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1290,7 +1290,12 @@ export default function A2uiSurface({
}

return (
<section className="a2ui-surface" aria-label={`Interactive UI ${surface.surfaceId}`}>
<section
className="a2ui-surface"
data-card-capture="true"
data-card-title={surface.surfaceId}
aria-label={`Interactive UI ${surface.surfaceId}`}
>
{renderNode("root", { scopePath: "" }, 0)}
{surface.state === "dispatched" && (
<div className="a2ui-status-row">
Expand Down
12 changes: 7 additions & 5 deletions desktop/src/ChatActivity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1099,15 +1099,17 @@ export function RunCards({
run,
prefill,
pickModel,
onContextMenu,
}: {
run: Run;
prefill: (s: string) => void;
pickModel?: () => void;
onContextMenu?: (e: React.MouseEvent) => void;
}) {
return (
<>
<div onContextMenu={onContextMenu} style={{ display: "contents" }}>
{run.apps?.map((app) => (
<section className="chat-card app-card" key={app.id} aria-label={app.title}>
<section className="chat-card app-card" key={app.id} data-card-capture="true" data-card-title={app.title} aria-label={app.title}>
<span className="app-card-icon" aria-hidden="true">
<AppWindow size={20} />
</span>
Expand All @@ -1122,7 +1124,7 @@ export function RunCards({
</section>
))}
{run.claudeArtifacts?.map((artifact) => (
<section className="chat-card app-card claude-artifact-card" key={artifact.id} aria-label={artifact.title}>
<section className="chat-card app-card claude-artifact-card" key={artifact.id} data-card-capture="true" data-card-title={artifact.title} aria-label={artifact.title}>
<span className="app-card-icon" aria-hidden="true">
<Sparkles size={20} />
</span>
Expand All @@ -1148,7 +1150,7 @@ export function RunCards({
<A2uiSurface key={surface.surfaceId} chatId={run.chatId} surface={surface} />
))}
{run.cards?.map((card) => (
<section className="chat-card" key={card.id} aria-label={card.title}>
<section className="chat-card" key={card.id} data-card-capture="true" data-card-title={card.title || "Card"} aria-label={card.title}>
<h3>{card.title}</h3>
<div className="panel-blocks">
{card.blocks.map((b, i) => (
Expand Down Expand Up @@ -1180,6 +1182,6 @@ export function RunCards({
Choose chat model
</button>
)}
</>
</div>
);
}
123 changes: 109 additions & 14 deletions desktop/src/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@ import { thoughtParts, type IslandUpdate } from "./island";
import { clearReadingError, readAloud, useReading } from "./voice";
import MessageDrawer from "./MessageDrawer";
import type { MessageMenuTarget } from "./messageMenu";
import {
formatAsPlainText,
formatForIMessage,
formatMessageHtmlForPdf,
shareableMarkdown,
type CopyFormat,
} from "./messageExport";
import { keptUnread } from "./unread";
import ContextDetails from "./ContextDetails";
import { BotAvatar, activityLabel, botActivity, chatActivity, useOutcome } from "./Avatar";
Expand Down Expand Up @@ -314,7 +321,11 @@ function ChatViewBody({
const [drawer, setDrawer] = useState<"" | "tasks">("");
const screenMenu = useMenu();
// The message whose drawer is open (MessageDrawer.tsx).
const [menu, setMenu] = useState<{ index: number; message: Message }>();
const [menu, setMenu] = useState<{
index: number;
message: Message;
cardCapture?: { el: HTMLElement; rect: { x: number; y: number; width: number; height: number }; title?: string };
}>();
const [notice, setNotice] = useState("");
const [showChanges, setShowChanges] = useState(false);
const [choosingProject, setChoosingProject] = useState(false);
Expand Down Expand Up @@ -696,6 +707,38 @@ function ChatViewBody({
.copyText(m.text)
.then(() => setNotice("Copied"))
.catch((e) => setNotice(e.message)),
copyFormat: (m: Message, format: CopyFormat) => {
const text = m.text ?? "";
if (format === "markdown") {
void window.botkins
.copyText(shareableMarkdown(text))
.then(() => setNotice("Copied Markdown"))
.catch((e) => setNotice(e.message));
return;
}
if (format === "imessage") {
void window.botkins
.copyText(formatForIMessage(text))
.then(() => setNotice("Copied for iMessage"))
.catch((e) => setNotice(e.message));
return;
}
if (format === "txt") {
void window.botkins
.copyText(formatAsPlainText(text))
.then(() => setNotice("Copied plain text"))
.catch((e) => setNotice(e.message));
return;
}
const title = chat.title && chat.title !== "New chat" ? chat.title : nameOf(m);
const html = formatMessageHtmlForPdf(text, title);
void window.botkins
.saveMessagePdf(html, title)
.then((res) => {
if (res?.saved) setNotice("Saved PDF");
})
.catch((e) => setNotice(e instanceof Error ? e.message : String(e)));
},
reply: (m: Message) => {
setQuote(m.text.trim().slice(0, 1200));
focusComposer();
Expand All @@ -705,6 +748,20 @@ function ChatViewBody({
: forkThread(i)
).catch(e => setNotice(e.message)),
};
const saveCard = async (capture: { el: HTMLElement; rect: { x: number; y: number; width: number; height: number }; title?: string }) => {
// Wait two frames so the drawer scrim unmounts before Electron captures the page region.
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
const liveRect = capture.el.isConnected ? capture.el.getBoundingClientRect() : null;
const rect = liveRect && liveRect.width >= 2 && liveRect.height >= 2
? { x: liveRect.left, y: liveRect.top, width: liveRect.width, height: liveRect.height }
: capture.rect;
try {
const res = await window.botkins.saveCardImage(rect, capture.title);
if (res?.saved) setNotice("Saved card image");
} catch (e) {
setNotice(e instanceof Error ? e.message : String(e));
}
};
// What a message's drawer offers (MessageDrawer.tsx, messageMenu.ts). A reaction is sent at once.
const reactionsOn = !state.remote?.using || state.remote.using.capabilities.includes("message-reactions-v1");
const me = state.team && "me" in state.team ? "member:" + state.team.me.memberId : "owner";
Expand All @@ -721,17 +778,21 @@ function ChatViewBody({
setNotice(error instanceof Error ? error.message : String(error));
}
};
const drawerFor = (m: Message, index: number): MessageMenuTarget => ({
mine: m.reactions?.find((r) => r.actor === me)?.emoji,
const drawerFor = (
m: Message,
index: number,
cardCapture?: { el: HTMLElement; rect: { x: number; y: number; width: number; height: number }; title?: string },
): MessageMenuTarget => ({
mine: index >= 0 ? m.reactions?.find((r) => r.actor === me)?.emoji : undefined,
time: m.time,
pinned: !!chat.pinned,
reading: reading.key === readKey(index),
reading: index >= 0 && reading.key === readKey(index),
actions: {
react: reactionsOn ? (emoji) => void reactNow(index, m.time ?? null, emoji) : undefined,
reply: () => act.reply(m),
fork: group ? undefined : () => act.fork(index),
react: index >= 0 && reactionsOn ? (emoji) => void reactNow(index, m.time ?? null, emoji) : undefined,
reply: m.text ? () => act.reply(m) : undefined,
fork: index >= 0 && !group ? () => act.fork(index) : undefined,
forkLabel,
newChatFork: ownMain ? () => void forkThread(index).catch((e) => setNotice(e.message)) : undefined,
newChatFork: index >= 0 && ownMain ? () => void forkThread(index).catch((e) => setNotice(e.message)) : undefined,
busy,
// The chat stays unread while it is open (it would be read again at once); opening another chat ends that.
markUnread: () => {
Expand All @@ -740,10 +801,12 @@ function ChatViewBody({
},
pin: () => void window.botkins.setChatFlags(chat.id, { pinned: !chat.pinned }).then(() => setNotice(chat.pinned ? "Unpinned" : "Pinned")).catch((e) => setNotice(e.message)),
copy: () => act.copy(m),
read: m.role !== "user" && m.text ? () => void readAloud(readKey(index), m.text, m.botId ?? bot.id) : undefined,
stop: () => void readAloud(readKey(index), m.text, m.botId ?? bot.id),
copyFormat: m.text ? (format) => act.copyFormat(m, format) : undefined,
saveCardImage: cardCapture ? () => void saveCard(cardCapture) : undefined,
read: index >= 0 && m.role !== "user" && m.text ? () => void readAloud(readKey(index), m.text, m.botId ?? bot.id) : undefined,
stop: index >= 0 ? () => void readAloud(readKey(index), m.text, m.botId ?? bot.id) : undefined,
// The words become the browser's own selection, so they can be copied in part.
select: m.text
select: index >= 0 && m.text
? () => {
const text = document.getElementById(`message-${chat.id}-${index}`)?.querySelector(".md, .command-output") ?? document.getElementById(`message-${chat.id}-${index}`);
if (text) window.getSelection()?.selectAllChildren(text);
Expand Down Expand Up @@ -846,10 +909,21 @@ function ChatViewBody({
}

const timelineBusy = latest?.status === "Working";
function cardCaptureFromEvent(e: React.MouseEvent) {
const el = (e.target as HTMLElement | null)?.closest<HTMLElement>("[data-card-capture]");
if (!el) return undefined;
const r = el.getBoundingClientRect();
if (r.width < 2 || r.height < 2) return undefined;
return {
el,
rect: { x: r.left, y: r.top, width: r.width, height: r.height },
title: el.getAttribute("data-card-title") || undefined,
};
}
function messageMenu(e: React.MouseEvent, message: Message, index: number) {
if (window.getSelection()?.toString()) return;
e.preventDefault();
setMenu({ message, index });
setMenu({ message, index, cardCapture: cardCaptureFromEvent(e) });
}
const accessibleChatIds = useMemo(() => new Set(state.chats.map((c) => c.id)), [state.chats]);
const timelineMessage = (m: Message, index: number) =>
Expand Down Expand Up @@ -1083,7 +1157,28 @@ function ChatViewBody({
) : !live && group && (folded || hasActivity) && fold}
{group && !live && crewRunning && crewCard}
<AgentMessageRail run={run} bots={state.bots} tasks={state.tasks} openChat={openChat} />
<RunCards run={run} prefill={prefill} pickModel={canManageAgents ? pickModel : undefined} />
<RunCards
run={run}
prefill={prefill}
pickModel={canManageAgents ? pickModel : undefined}
onContextMenu={(e) => {
if (window.getSelection()?.toString()) return;
const cardCapture = cardCaptureFromEvent(e);
if (!cardCapture) return;
e.preventDefault();
const lastReply = reply.at(-1);
const fallbackMessage: Message = {
role: "assistant",
text: cardCapture.title || "",
time: run.time,
};
setMenu({
message: lastReply?.message ?? fallbackMessage,
index: lastReply ? loadedFrom + lastReply.index : -1,
cardCapture,
});
}}
/>
{!live && (failed.includes(run.status) || !!groupFailure) && (
<div className="error run-error"><span>{groupFailure || (run.ending === "timed-out" ? "Timed out" : run.status) + " · " + (run.detail || "Reply stopped.")}</span>{!groupFailure && run.id === lastUserRun && !busy && <button className="secondary" onClick={() => void window.botkins.retry(run.id).catch((e) => setNotice(e.message))}><RotateCcw size={13} />Try again</button>}</div>
)}
Expand Down Expand Up @@ -1665,7 +1760,7 @@ function ChatViewBody({
)}
<QuoteContext.Provider value={{ quote, setQuote }}>{composer}</QuoteContext.Provider>
</div>
{menu && <MessageDrawer key={menu.index} target={drawerFor(menu.message, menu.index)} close={() => setMenu(undefined)} />}
{menu && <MessageDrawer key={`${menu.index}-${menu.cardCapture?.title ?? ""}`} target={drawerFor(menu.message, menu.index, menu.cardCapture)} close={() => setMenu(undefined)} />}
</div>
{paneShown && narrow && <div className="pane-scrim" aria-hidden="true" onClick={closePane} />}
{paneShown && (
Expand Down
7 changes: 6 additions & 1 deletion desktop/src/McpAppCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,12 @@ export function McpAppCard({ chatId, card }: { chatId: string; card: Card }) {

const name = card.title || card.tool;
return (
<section className={"chat-card mcp-app-card" + (view?.prefersBorder === false ? " borderless" : "")} aria-label={name + " from " + card.server}>
<section
className={"chat-card mcp-app-card" + (view?.prefersBorder === false ? " borderless" : "")}
data-card-capture="true"
data-card-title={name}
aria-label={name + " from " + card.server}
>
<header className="mcp-app-head">
<AppWindow size={15} aria-hidden="true" />
<strong>{name}</strong>
Expand Down
Loading
Loading