Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

0.8.0 P4 app: shared pictures show as the bot's, under its reply, without repeats (#468)

Oleksandr Ivanchenkoc9267eaf83c3
diff --git a/frontend/src/components/Attachments.tsx b/frontend/src/components/Attachments.tsx
index bf00d255..5013e082 100644
--- a/frontend/src/components/Attachments.tsx
+++ b/frontend/src/components/Attachments.tsx
@@ -1,24 +1,45 @@
-import React, { useState } from 'react';
-import { AlertCircle, Download, FileText, Film, Loader2, RotateCw, X } from 'lucide-react';
+import React, { useCallback, useEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { AlertCircle, Download, ExternalLink, FileText, Film, Loader2, RotateCw, X } from 'lucide-react';
import { AttachmentRef, PendingUpload, attachKind, attachmentUrl, fileKind, formatBytes, isInlineImage, isVideo, uploadProgressText } from '../attachments';
/**
* A file on a message: images as a thumbnail (opens full size), everything else as a tile.
* Both have a Download button; the server sends non-images as downloads only.
*/
-export const FileTile: React.FC<{ file: AttachmentRef }> = ({ file }) => {
+export const FileTile: React.FC<{
+ file: AttachmentRef;
+ small?: boolean;
+ /** A bot's shared file: names the bot in the alt text and viewer, and caps the tile at 240 px on desktop. */
+ sharedBy?: string;
+ /** When it was shared, for the viewer's bottom bar. */
+ at?: string | null;
+}> = ({ file, small = false, sharedBy, at = null }) => {
const [broken, setBroken] = useState(false);
+ const [viewing, setViewing] = useState(false);
+ const thumbRef = useRef<HTMLAnchorElement>(null);
+ const closeViewer = useCallback(() => {
+ setViewing(false);
+ thumbRef.current?.focus();
+ }, []);
const image = isInlineImage(file.mime) && !broken;
const video = isVideo(file.mime) && !broken;
+ // Shared tiles and small copies get an icon-only 32 px chip, so the name has room; a transparent
+ // ring around it makes the hit area 44 px. Other tiles are 44 px on phones from min size.
+ const iconOnly = small || !!sharedBy;
const download = (
<a
href={attachmentUrl(file.id, true)}
download={file.name}
aria-label={`Download ${file.name}`}
- className="inline-flex items-center gap-1 shrink-0 px-2 py-1 rounded-lg text-[11px] font-medium text-sky-300 bg-sky-500/10 border border-sky-500/30 hover:bg-sky-500/20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ title="Download"
+ data-download=""
+ className={`inline-flex items-center justify-center gap-1 shrink-0 rounded-lg text-[11px] font-medium text-sky-300 bg-sky-500/10 border border-sky-500/30 hover:bg-sky-500/20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${
+ iconOnly ? "relative w-8 h-8 before:absolute before:-inset-[7px] before:content-['']" : 'px-2 py-1 max-sm:min-w-11 max-sm:min-h-11'
+ }`}
>
- <Download size={12} aria-hidden="true" />
- <span className="hidden sm:inline">Download</span>
+ <Download size={iconOnly ? 14 : 12} aria-hidden="true" />
+ <span className={iconOnly ? 'sr-only' : 'hidden sm:inline'}>Download</span>
</a>
);
const label = (
@@ -26,7 +47,7 @@ export const FileTile: React.FC<{ file: AttachmentRef }> = ({ file }) => {
<span className="block truncate text-xs font-medium text-zinc-100" title={file.name}>
{file.name}
</span>
- <span className="block text-[10px] text-zinc-500">
+ <span className={`block text-[10px] text-zinc-500${small ? ' whitespace-nowrap' : ''}`}>
{fileKind(file.mime, file.name)} · {formatBytes(file.size)}
</span>
</span>
@@ -34,17 +55,40 @@ export const FileTile: React.FC<{ file: AttachmentRef }> = ({ file }) => {
if (image) {
return (
- <figure className="w-full sm:w-auto max-w-full sm:max-w-xs rounded-xl overflow-hidden border border-zinc-800 bg-zinc-900/80">
- <a href={attachmentUrl(file.id)} target="_blank" rel="noopener noreferrer" className="block focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500">
+ <figure className={`${small ? 'w-40' : 'w-full sm:w-auto'} max-w-full ${sharedBy ? 'sm:max-w-[240px]' : 'sm:max-w-xs'} rounded-xl overflow-hidden border border-zinc-800 bg-zinc-900/80`}>
+ {/* A plain click opens the in-app viewer; Cmd/Ctrl/middle click still opens the original in a new tab */}
+ <a
+ ref={thumbRef}
+ href={attachmentUrl(file.id)}
+ target="_blank"
+ rel="noopener noreferrer"
+ aria-label={`View ${file.name} full size`}
+ aria-haspopup="dialog"
+ data-image-thumb=""
+ onClick={(e) => {
+ if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
+ e.preventDefault();
+ setViewing(true);
+ }}
+ className="block cursor-zoom-in focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-violet-400"
+ >
<img
src={attachmentUrl(file.id)}
- alt={file.name}
+ alt={sharedBy ? `${file.name}, shared by ${sharedBy}` : file.name}
loading="lazy"
decoding="async"
onError={() => setBroken(true)}
- className="block w-full sm:w-auto max-h-60 object-contain bg-zinc-950"
+ className={`block ${small ? 'w-full h-24' : 'w-full sm:w-auto max-h-60'} object-contain bg-zinc-900`}
/>
</a>
+ {viewing && (
+ <ImageViewer
+ file={file}
+ sharedBy={sharedBy}
+ at={at}
+ onClose={closeViewer}
+ />
+ )}
<figcaption className="flex items-center gap-2 px-2.5 py-1.5">
{label}
{download}
@@ -84,11 +128,183 @@ export const FileTile: React.FC<{ file: AttachmentRef }> = ({ file }) => {
);
};
-export const FileTiles: React.FC<{ files: AttachmentRef[]; align?: 'start' | 'end' }> = ({ files, align = 'start' }) => (
+/**
+ * The full-size view of a chat image (P4, Mira's spec): an always-dark 85% scrim, the picture fit to
+ * the screen (100dvh, so iOS Safari doesn't cut it off), Close top right, and a bottom bar with the
+ * file, bot and time on the left and Open original on the right. Esc, Close or a tap on the scrim
+ * closes it; focus starts on Close, Tab stays inside, the page behind doesn't scroll, and pinch-zoom
+ * is left to the browser. It fades in over 150 ms, with no motion under reduced motion.
+ */
+export const ImageViewer: React.FC<{ file: AttachmentRef; sharedBy?: string; at?: string | null; onClose: () => void }> = ({
+ file,
+ sharedBy,
+ at = null,
+ onClose,
+}) => {
+ const closeRef = useRef<HTMLButtonElement>(null);
+ const boxRef = useRef<HTMLDivElement>(null);
+ // The chat re-renders on every streamed token: keep the latest onClose in a ref so the setup below
+ // runs once on open and never pulls focus back to Close while a reply streams.
+ const onCloseRef = useRef(onClose);
+ onCloseRef.current = onClose;
+ useEffect(() => {
+ closeRef.current?.focus();
+ const body = document.body;
+ const prevOverflow = body.style.overflow;
+ body.style.overflow = 'hidden';
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ e.stopPropagation();
+ onCloseRef.current();
+ return;
+ }
+ if (e.key !== 'Tab' || !boxRef.current) return;
+ const stops = Array.from(boxRef.current.querySelectorAll<HTMLElement>('a[href], button'));
+ if (!stops.length) return;
+ const first = stops[0];
+ const last = stops[stops.length - 1];
+ if (e.shiftKey && document.activeElement === first) {
+ e.preventDefault();
+ last.focus();
+ } else if (!e.shiftKey && document.activeElement === last) {
+ e.preventDefault();
+ first.focus();
+ }
+ };
+ document.addEventListener('keydown', onKey, true);
+ return () => {
+ document.removeEventListener('keydown', onKey, true);
+ body.style.overflow = prevOverflow;
+ };
+ }, []);
+ const titleId = `viewer-${file.id}`;
+ const when = timeLabel(at);
+ const closeOnScrim = (e: React.MouseEvent) => {
+ if (e.target === e.currentTarget) onClose();
+ };
+ return createPortal(
+ <div
+ ref={boxRef}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby={titleId}
+ data-image-viewer=""
+ className="kw-viewer-in fixed inset-0 z-[200] flex flex-col bg-black/85"
+ style={{ height: '100dvh' }}
+ onClick={closeOnScrim}
+ >
+ <button
+ ref={closeRef}
+ type="button"
+ onClick={onClose}
+ aria-label="Close"
+ className="absolute right-2 z-10 inline-flex items-center justify-center w-11 h-11 rounded-full bg-zinc-900/80 text-zinc-100 hover:bg-zinc-800 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-violet-400"
+ style={{ top: 'calc(env(safe-area-inset-top, 0px) + 0.5rem)' }}
+ >
+ <X size={20} aria-hidden="true" />
+ </button>
+ <div className="flex-1 min-h-0 flex items-center justify-center sm:p-6" style={{ paddingTop: 'calc(env(safe-area-inset-top, 0px) + 3.5rem)' }} onClick={closeOnScrim}>
+ <img
+ src={attachmentUrl(file.id)}
+ alt={sharedBy ? `${file.name}, shared by ${sharedBy}` : file.name}
+ className="block max-w-[100vw] max-h-full object-contain"
+ style={{ touchAction: 'pinch-zoom' }}
+ />
+ </div>
+ <div
+ className="flex items-center gap-3 px-3 sm:px-4 bg-black text-zinc-300"
+ style={{ paddingBottom: 'env(safe-area-inset-bottom, 0px)' }}
+ >
+ {/* Phones put the bot and time on a second line so the time is never cut off */}
+ <p id={titleId} className="min-w-0 flex-1 text-xs py-2 sm:py-3 sm:truncate" title={file.name}>
+ <span className="block sm:inline truncate font-medium text-zinc-100">{file.name}</span>
+ {(sharedBy || when) && (
+ <span className="block sm:inline truncate">
+ <span className="hidden sm:inline"> · </span>
+ {[sharedBy, when].filter(Boolean).join(' · ')}
+ </span>
+ )}
+ </p>
+ <a
+ href={attachmentUrl(file.id)}
+ target="_blank"
+ rel="noopener"
+ className="inline-flex items-center gap-1.5 shrink-0 min-h-[44px] px-3 rounded-lg text-xs font-medium text-sky-300 hover:bg-white/10 focus-visible:outline focus-visible:outline-2 focus-visible:outline-violet-400"
+ >
+ <ExternalLink size={14} aria-hidden="true" />
+ Open original
+ </a>
+ </div>
+ </div>,
+ document.body,
+ );
+};
+
+const timeLabel = (at: string | null) => {
+ const t = at ? new Date(at) : null;
+ return t && !Number.isNaN(t.getTime()) ? t.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) : null;
+};
+
+/**
+ * Older copies of a file a bot shared again within a few minutes (P4): folded behind the newest as
+ * "Shared 3 times · Show 2 earlier" in plain grey text under the tile, oldest first when open.
+ */
+export const EarlierCopies: React.FC<{
+ idBase: string;
+ sharedBy?: string;
+ copies: Array<{ id: string; at: string | null; files: AttachmentRef[] }>;
+}> = ({ idBase, sharedBy, copies }) => {
+ const [open, setOpen] = useState(false);
+ const hidden = copies.length;
+ const listId = `${idBase}-list`;
+ const fileName = copies[0]?.files.map((f) => f.name).join(', ') || 'this file';
+ return (
+ <div className="max-w-full" data-earlier-copies={hidden}>
+ <button
+ type="button"
+ aria-expanded={open}
+ aria-controls={listId}
+ aria-label={open ? `Hide earlier copies of ${fileName}` : `Show ${hidden} earlier ${hidden === 1 ? 'copy' : 'copies'} of ${fileName}`}
+ onClick={() => setOpen((o) => !o)}
+ // 44 px tall hit area on phones from padding; the text stays 12 px
+ className="block text-left py-3.5 sm:py-1 text-xs text-zinc-400 hover:text-zinc-200 rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-violet-400"
+ >
+ {open ? 'Hide earlier' : `Shared ${hidden + 1} times · Show ${hidden} earlier`}
+ </button>
+ {open && (
+ <ol id={listId} className="mt-1 flex flex-col gap-2" aria-label="Earlier copies, oldest first">
+ {copies.map((c) => {
+ const when = timeLabel(c.at);
+ return (
+ <li key={c.id} data-earlier-copy={c.id} className="max-w-full">
+ {when && <span className="block mb-1 text-[11px] text-zinc-500">{when}</span>}
+ <ul className="flex flex-wrap gap-2">
+ {c.files.map((f) => (
+ <li key={f.id} className="max-w-full">
+ <FileTile file={f} small sharedBy={sharedBy} at={c.at} />
+ </li>
+ ))}
+ </ul>
+ </li>
+ );
+ })}
+ </ol>
+ )}
+ </div>
+ );
+};
+
+export const FileTiles: React.FC<{ files: AttachmentRef[]; align?: 'start' | 'end'; sharedBy?: string; at?: string | null }> = ({
+ files,
+ align = 'start',
+ sharedBy,
+ at = null,
+}) => (
<ul className={`mt-2 flex flex-wrap gap-2 w-full ${align === 'end' ? 'justify-end' : ''}`} aria-label={files.length === 1 ? 'Attached file' : `${files.length} attached files`}>
{files.map((f) => (
- <li key={f.id} className="max-w-full">
- <FileTile file={f} />
+ <li key={f.id} className={`max-w-full${sharedBy ? ' w-full sm:w-auto' : ''}`}>
+ <FileTile file={f} sharedBy={sharedBy} at={at} />
</li>
))}
</ul>
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 487777f0..c1bf18f4 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -51,7 +51,8 @@ import {
uploadRetryable,
uploadSlotsLeft,
} from '../attachments';
-import { FileTiles, UploadChip } from './Attachments';
+import { EarlierCopies, FileTiles, UploadChip } from './Attachments';
+import { arrangeSharedFiles, botDisplayName, botOf, shareInfo } from '../sharedFiles';
import { ranOnLabel } from '../engines';
import { replyTokens } from '../modelUsage';
import { parseRoutingMeta, ranOnAccount, routingLine } from '../spaces';
@@ -564,6 +565,12 @@ export const ChatView: React.FC<ChatViewProps> = ({
}, [teamsProp]);
const activeKwants = kwantsProp || internalKwants;
+ // Every bot a message here can come from: names and ids resolve against these, never the chat title (P4).
+ const knownBots = useMemo(() => {
+ const all: Array<{ id: string; name: string }> = [...activeKwants, ...(teamMembers ?? [])];
+ if (home?.kind === 'bot' && home.bot) all.push({ id: home.bot.id, name: home.bot.name });
+ return all;
+ }, [activeKwants, teamMembers, home]);
// Each routed reply's question: the person's latest saved message before it ("Wrong bot?").
const questionOf = useMemo(() => questionsOfReplies(messages), [messages]);
const activeTeams = teamsProp || internalTeams;
@@ -816,8 +823,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
};
/** The chip's name: the bot by id or name, else this chat's title. */
const replyBotName = (msg: ChatMessage) => {
- const name = botNameOf(msg.sender_id, activeKwants);
- return name === 'a bot' ? title : name;
+ return botDisplayName(msg.sender_id, knownBots);
};
const cancelReply = () => {
setReplyTo(null);
@@ -1104,9 +1110,15 @@ export const ChatView: React.FC<ChatViewProps> = ({
};
const switchNoteFor = useMemo(
- () => assignSwitchNotes(switchNotes ?? [], messages, (m) => (m.sender_id && m.sender_id.length > 20 ? title : m.sender_id)),
- [switchNotes, messages, title],
+ () => assignSwitchNotes(switchNotes ?? [], messages, (m) => botDisplayName(m.sender_id, knownBots)),
+ [switchNotes, messages, knownBots],
);
+ // P4: each turn's shared files move under their bot's reply, and repeats of one file fold into the newest.
+ // While a bot's live row is on screen, its shares this turn sit under that row from the start (Mira, P4).
+ const liveRowShown = isStreaming && !deciding && routingState?.phase !== 'deciding' && !discussionState?.inProgress;
+ const liveBot = liveRowShown && streamingSpeakerName ? streamingSpeakerName : null;
+ const arranged = useMemo(() => arrangeSharedFiles(messages, knownBots, liveBot), [messages, knownBots, liveBot]);
+ const liveShareIds = useMemo(() => new Set(arranged.live.map((m) => m.id)), [arranged.live]);
const liveNote = isStreaming ? liveSwitchNote(switchNotes ?? [], switchNoteFor, streamingSpeakerName || title) : null;
// Replies that arrive while the chat is open slide in; the first load and a stream handing over to its saved copy do not
@@ -1213,7 +1225,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
<div key={msg.id} data-message-id={msg.id} className="w-full max-w-5xl">
<SetupNeededCard
meta={setup}
- botName={msg.sender_id || title}
+ botName={botDisplayName(msg.sender_id, knownBots)}
spaceName={spaceName ?? 'this space'}
canRun={canRun}
onOpenAccounts={onOpenAccounts}
@@ -1279,24 +1291,34 @@ export const ChatView: React.FC<ChatViewProps> = ({
? emptyTrialReplyLine(parsePick(activeKwants.find((k) => k.id === msg.sender_id || k.name === msg.sender_id)?.preferred_model).family)
: null;
const workAhead = isUser ? null : parseWorkAhead(msg.meta);
- const displayName = isUser ? agentSenderLabel(msg.meta) ?? 'You' : (msg.sender_id && msg.sender_id.length > 20 ? title : msg.sender_id);
+ const displayName = isUser ? agentSenderLabel(msg.meta) ?? 'You' : botDisplayName(msg.sender_id, knownBots);
+ // P4: a share that now sits under its bot's reply reads as part of it, without a second header.
+ const underReply = !isUser && filesOnly && (arranged.attached.has(msg.id) || liveShareIds.has(msg.id));
+ const olderCopies = filesOnly ? arranged.earlier.get(msg.id) : undefined;
const replyQuote = isUser ? replyRefOf(msg.reply_to) : null;
// Whose mood the reply header shows (Pixel's AvatarMood, drawn by ModernAvatar given a kwantId):
// Laya's pick, else this bot chat's bot, else the team member with that name. Unknown: no mood.
const replyKwantId = isUser
? undefined
- : routed?.kwant_id ?? (home?.kind === 'bot' ? home.bot?.id : undefined) ?? activeKwants.find((k) => k.name === displayName)?.id;
+ : routed?.kwant_id ?? (home?.kind === 'bot' ? home.bot?.id : undefined) ?? botOf(msg.sender_id, knownBots)?.id;
return (
<div
key={msg.id}
data-message-id={msg.id}
tabIndex={-1}
+ data-shared-under={underReply ? '' : undefined}
+ // The log's space-y gap would win over a margin class; inline style pulls the tiles up to the reply's actions
+ style={underReply ? { marginTop: '0.5rem' } : undefined}
className={`flex items-start gap-3.5 w-full max-w-5xl rounded-xl focus:outline-none ${isUser ? 'ml-auto flex-row-reverse justify-start' : ''} ${
flashId === msg.id ? (flashKind === 'quote' ? 'kw-flash-quote' : 'kw-flash') : ''
} ${freshTrack.current.fresh.has(msg.id) ? 'kws-in' : ''}`}
>
{/* Phones show the avatar inside the name line instead, so the bubble gets the full width */}
+ {underReply ? (
+ // Keeps the tiles lined up with the reply bubble above, where the avatar would be
+ <span className="hidden sm:block w-9 shrink-0" aria-hidden="true" />
+ ) : (
<span className="hidden sm:contents">
{/* Laya hand-off: a reply she just routed brings the chosen bot's avatar up into the header */}
<span className={routed && freshTrack.current.fresh.has(msg.id) ? 'kws-handoff inline-flex' : 'contents'}>
@@ -1308,9 +1330,12 @@ export const ChatView: React.FC<ChatViewProps> = ({
/>
</span>
</span>
+ )}
<div className={`flex flex-col min-w-0 ${isUser ? 'max-w-[85%] sm:max-w-2xl items-end' : 'flex-1 max-w-4xl items-start'}`}>
- {isUser ? (
+ {underReply ? (
+ <span className="sr-only">Shared by {displayName}</span>
+ ) : isUser ? (
<div className="flex items-center gap-2 mb-1.5 text-[11px] text-zinc-400 font-medium max-w-full min-w-0 whitespace-nowrap">
<span className="text-zinc-200 shrink-0">{displayName}</span>
{fromTelegram(parseMetaObject(msg.meta)) && <ViaTelegram />}
@@ -1413,7 +1438,20 @@ export const ChatView: React.FC<ChatViewProps> = ({
)}
</div>
)}
- {files.length > 0 && <FileTiles files={files} align={isUser ? 'end' : 'start'} />}
+ {files.length > 0 && <FileTiles files={files} align={isUser ? 'end' : 'start'} sharedBy={filesOnly && !isUser ? displayName : undefined} at={msg.created_at ?? null} />}
+ {filesOnly && !isUser && files.length > 0 && shareInfo(msg.meta).auto && (
+ // P4: kwnt posted the turn's last screenshot because the reply claimed a picture and none was shared
+ <p data-shared-auto="" className="mt-1 text-[11px] text-zinc-500">
+ Shared automatically
+ </p>
+ )}
+ {olderCopies && olderCopies.length > 0 && (
+ <EarlierCopies
+ idBase={`earlier-${msg.id}`}
+ sharedBy={displayName}
+ copies={olderCopies.map((m) => ({ id: m.id, at: m.created_at ?? null, files: parseAttachments(m.meta) }))}
+ />
+ )}
{/* A shared-file card has no bubble, so the files block (the table or text preview) is mounted here, after the tiles. */}
{filesOnly && !isUser && msg.results != null && (
// The column is `items-start`, so without a width cap a long cell stretches the preview past the message.
@@ -1712,7 +1750,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
<BotHome home={home} spaceName={spaceName} team={activeKwants} prompts={suggestions} canRun={canRun} onPick={handlePromptSuggestion} />
</div>
)}
- {groupDiscussionThreads(messages).map((item) => {
+ {groupDiscussionThreads(arranged.messages).map((item) => {
if (item.kind === 'message') {
const trial = trialCards.get(item.message.id);
if (!trial) return renderMessage(item.message);
@@ -1844,6 +1882,9 @@ export const ChatView: React.FC<ChatViewProps> = ({
</div>
)}
+ {/* P4: the running bot's shares, already in the place its saved reply will give them */}
+ {liveRowShown && arranged.live.map(renderMessage)}
+
{/* Approvals allowed in Telegram (G4): "✓ Allowed once from Telegram", live and after a reload */}
{settledApprovals.map((approval) => (
<AllowedFromTelegram key={approval.id} lead={approvalLead(approval)} />
diff --git a/frontend/src/sharedFiles.ts b/frontend/src/sharedFiles.ts
new file mode 100644
index 00000000..71f222df
--- /dev/null
+++ b/frontend/src/sharedFiles.ts
@@ -0,0 +1,209 @@
+// Files a bot shares in chat (0.8.0 P4, app half): who sent them, where they sit, and repeats.
+// Shared-file rows store the bot's name as sender_id, like its replies, with the id in meta.kwant_id
+// (vega-080-share-screens). Rows saved before that, and live events from an older server, carry the
+// bot's id instead, so a row is resolved by meta.kwant_id, then id or name, against the chat's bots.
+// It never falls back to the chat title: in a space that title is the space ("@booktun.ing").
+import { isSharedFileMessage, parseAttachments } from './attachments';
+import { parseMetaObject } from './questions';
+
+/** What a row shows when its bot can't be found (deleted, or the list hasn't loaded yet). */
+export const UNKNOWN_BOT_LABEL = 'A bot';
+
+/** How close two shares of one file must be to count as repeats. */
+export const REPEAT_WINDOW_MS = 5 * 60 * 1000;
+
+export interface BotRef {
+ id: string;
+ name: string;
+}
+
+interface Msg {
+ id: string;
+ sender_role: 'user' | 'kwant' | 'system';
+ sender_id: string;
+ meta?: string | null;
+ created_at?: string | null;
+}
+
+// Ids are uuids today; anything long without spaces is treated as an id, never shown as a name.
+const looksLikeId = (s: string) => s.length > 20 && !/\s/.test(s);
+
+/** The bot behind a sender id (or a stored name): the bot itself, or null when it isn't known. */
+export function botOf(senderId: string | undefined | null, bots: ReadonlyArray<BotRef>): BotRef | null {
+ if (!senderId) return null;
+ return bots.find((b) => b.id === senderId) ?? bots.find((b) => b.name === senderId) ?? null;
+}
+
+/** A bot message's name: the bot by id or name, else a short stored name, else the neutral label. */
+export function botDisplayName(senderId: string | undefined | null, bots: ReadonlyArray<BotRef>): string {
+ const bot = botOf(senderId, bots);
+ if (bot) return bot.name;
+ if (!senderId || looksLikeId(senderId)) return UNKNOWN_BOT_LABEL;
+ return senderId;
+}
+
+export interface ShareInfo {
+ /** The bot's id from meta, when the server sent it. */
+ kwantId: string | null;
+ /** True when kwnt shared the turn's last screenshot itself, because the reply claimed a picture. */
+ auto: boolean;
+}
+
+/** What a shared-file row's meta says about who shared it and how. */
+export function shareInfo(meta: string | null | undefined): ShareInfo {
+ const o = parseMetaObject(meta) ?? {};
+ const id = typeof o.kwant_id === 'string' && o.kwant_id ? o.kwant_id : null;
+ return { kwantId: id, auto: o.auto === true };
+}
+
+/** Who a message is from, for matching: a share's meta.kwant_id when present, else its sender_id. */
+const senderOf = (m: Msg) => (isBotFileShare(m) ? shareInfo(m.meta).kwantId : null) ?? m.sender_id;
+
+/** True for a bot's shared-file row (meta kind "file" with at least one file). */
+export function isBotFileShare(m: Msg): boolean {
+ return m.sender_role === 'kwant' && isSharedFileMessage(m.meta) && parseAttachments(m.meta).length > 0;
+}
+
+/** Same bot, by id or name, so an id row and a name reply match. */
+function sameBot(a: string, b: string, bots: ReadonlyArray<BotRef>): boolean {
+ if (a === b) return true;
+ const x = botOf(a, bots);
+ const y = botOf(b, bots);
+ return !!x && !!y && x.id === y.id;
+}
+
+export interface ArrangedFiles<M> {
+ /** The messages in display order: each turn's shares moved right under their bot's reply. */
+ messages: M[];
+ /** Share rows that now sit under their bot's reply (drawn without a second header). */
+ attached: Set<string>;
+ /** Newest share id -> the older copies folded behind it, oldest first. */
+ earlier: Map<string, M[]>;
+ /**
+ * Shares from the bot whose turn is still running, taken out of `messages`: the chat draws them
+ * under that bot's live row, so they are already where its saved reply will put them (no jump).
+ */
+ live: M[];
+}
+
+const timeOf = (m: Msg) => {
+ const t = m.created_at ? Date.parse(m.created_at) : NaN;
+ return Number.isNaN(t) ? null : t;
+};
+// Same name and same size: a re-shot screenshot saved under the old name is a new picture, not a repeat.
+const fileKey = (m: Msg) =>
+ parseAttachments(m.meta)
+ .map((a) => `${a.name}\u0000${a.size}`)
+ .sort()
+ .join('\n');
+
+/**
+ * Within one turn (between two of the person's messages), a bot's shared-file rows move to just
+ * after that bot's next reply in the turn. Rows with no later reply stay where they are. Then in each
+ * run of consecutive shares by one bot, copies of the same file (name and size) within REPEAT_WINDOW_MS fold
+ * into the newest, which takes the place of the last copy.
+ */
+export function arrangeSharedFiles<M extends Msg>(
+ input: ReadonlyArray<M>,
+ bots: ReadonlyArray<BotRef>,
+ /** The bot (id or name) whose reply is streaming now, when its live row is on screen. */
+ liveBot: string | null = null,
+): ArrangedFiles<M> {
+ const attached = new Set<string>();
+ const placed: M[] = [];
+ let i = 0;
+ while (i < input.length) {
+ // One turn: the person's message(s), then everything up to their next message.
+ let j = i;
+ while (j < input.length && input[j].sender_role === 'user') j += 1;
+ while (j < input.length && input[j].sender_role !== 'user') j += 1;
+ const turn = input.slice(i, j);
+ const waiting: M[] = [];
+ for (let k = 0; k < turn.length; k += 1) {
+ const m = turn[k];
+ if (isBotFileShare(m)) {
+ const replyLater = turn.slice(k + 1).some((r) => r.sender_role === 'kwant' && !isBotFileShare(r) && sameBot(r.sender_id, senderOf(m), bots));
+ if (replyLater) {
+ waiting.push(m);
+ continue;
+ }
+ placed.push(m);
+ continue;
+ }
+ placed.push(m);
+ if (m.sender_role === 'kwant') {
+ const mine = waiting.filter((w) => sameBot(senderOf(w), m.sender_id, bots));
+ for (const w of mine) {
+ placed.push(w);
+ attached.add(w.id);
+ waiting.splice(waiting.indexOf(w), 1);
+ }
+ }
+ }
+ placed.push(...waiting);
+ i = j;
+ }
+ // A share that already sat right under its bot's reply is attached too (e.g. the server saved it after).
+ for (let k = 1; k < placed.length; k += 1) {
+ const m = placed[k];
+ if (!isBotFileShare(m) || attached.has(m.id)) continue;
+ let p = k - 1;
+ while (p >= 0 && isBotFileShare(placed[p]) && sameBot(senderOf(placed[p]), senderOf(m), bots)) p -= 1;
+ const prev = placed[p];
+ if (prev && prev.sender_role === 'kwant' && !isBotFileShare(prev) && sameBot(prev.sender_id, senderOf(m), bots)) attached.add(m.id);
+ }
+
+ // Repeats: inside a run of consecutive shares by one bot, group by file name and size.
+ const earlier = new Map<string, M[]>();
+ const out: M[] = [];
+ let r = 0;
+ while (r < placed.length) {
+ if (!isBotFileShare(placed[r])) {
+ out.push(placed[r]);
+ r += 1;
+ continue;
+ }
+ let e = r + 1;
+ while (e < placed.length && isBotFileShare(placed[e]) && sameBot(senderOf(placed[e]), senderOf(placed[r]), bots)) e += 1;
+ const run = placed.slice(r, e);
+ const folded = new Set<string>();
+ // Newest first: each copy joins the newest one of its name while it is within the window of the copy after it.
+ for (let a = run.length - 1; a >= 0; a -= 1) {
+ const head = run[a];
+ if (folded.has(head.id)) continue;
+ const key = fileKey(head);
+ const older: M[] = [];
+ let newer = head;
+ for (let b = a - 1; b >= 0; b -= 1) {
+ const cand = run[b];
+ if (folded.has(cand.id) || fileKey(cand) !== key) continue;
+ const tNew = timeOf(newer);
+ const tOld = timeOf(cand);
+ if (tNew !== null && tOld !== null && tNew - tOld > REPEAT_WINDOW_MS) break;
+ older.unshift(cand);
+ folded.add(cand.id);
+ newer = cand;
+ }
+ if (older.length) earlier.set(head.id, older);
+ }
+ for (const m of run) if (!folded.has(m.id)) out.push(m);
+ // A run sits under a reply when any of its rows does.
+ if (run.some((m) => attached.has(m.id))) for (const m of run) if (!folded.has(m.id)) attached.add(m.id);
+ r = e;
+ }
+
+ // The running turn: its loose shares from the live bot (after the person's last message) go to the live row.
+ const live: M[] = [];
+ if (liveBot) {
+ let start = out.length;
+ while (start > 0 && out[start - 1].sender_role !== 'user') start -= 1;
+ for (let k = out.length - 1; k >= start; k -= 1) {
+ const m = out[k];
+ if (isBotFileShare(m) && !attached.has(m.id) && sameBot(senderOf(m), liveBot, bots)) {
+ live.unshift(m);
+ out.splice(k, 1);
+ }
+ }
+ }
+ return { messages: out, attached, earlier, live };
+}
diff --git a/frontend/src/styles/stream.css b/frontend/src/styles/stream.css
index fa0042cd..c59eba43 100644
--- a/frontend/src/styles/stream.css
+++ b/frontend/src/styles/stream.css
@@ -197,3 +197,13 @@
/* Recipe card (0.7.6): a step's badge pops once when it becomes done. Applied with motion-safe only. */
@keyframes kw-step-done { from { transform: scale(.7); opacity: .4; } to { transform: scale(1); opacity: 1; } }
+
+/* P4 image viewer: a 150 ms fade from 98% scale (Mira); nothing moves under reduced motion. */
+@keyframes kw-viewer-in {
+ from { opacity: 0; transform: scale(0.98); }
+ to { opacity: 1; transform: none; }
+}
+.kw-viewer-in { animation: kw-viewer-in 150ms ease-out both; }
+@media (prefers-reduced-motion: reduce) {
+ .kw-viewer-in { animation: none; }
+}
diff --git a/frontend/tests/sharedImages.test.mjs b/frontend/tests/sharedImages.test.mjs
new file mode 100644
index 00000000..bfb6933f
--- /dev/null
+++ b/frontend/tests/sharedImages.test.mjs
@@ -0,0 +1,437 @@
+// 0.8.0 P4 (app half): pictures a bot shares show as that bot's, under its reply, without repeats.
+// The chat replays Oleks's 2026-11-09 thread: share_file rows stored with the bot's uuid, posted before
+// the reply, the same file three times. The chat's title is the space ("@booktun.ing"), never a sender.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage', 'CSS']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+if (!g.CSS) g.CSS = { escape: (s) => s };
+g.window.matchMedia = g.window.matchMedia || ((q) => ({ matches: false, media: q, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} }));
+g.ResizeObserver = g.window.ResizeObserver = class { observe() {} unobserve() {} disconnect() {} };
+g.IntersectionObserver = g.window.IntersectionObserver = class { observe() {} unobserve() {} disconnect() {} };
+g.window.HTMLElement.prototype.scrollIntoView = function () {};
+g.fetch = g.window.fetch = async () => new Response('[]', { status: 200, headers: { 'Content-Type': 'application/json' } });
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { flushSync } from 'react-dom';
+ export * from './src/sharedFiles';
+ export { ChatView } from './src/components/ChatView';
+`);
+const { React, createRoot, flushSync } = m;
+const h = React.createElement;
+const settle = () => new Promise((r) => setImmediate(r));
+
+const FRONTEND = '7b2657fd-54d1-465b-ab37-5269eb1ed456';
+const GROWTH = '0e7bf95d-cb8b-4396-a0d7-bcf14a38ab47';
+const GONE = '4c6677dc-533e-4706-8028-4afa492d95a4';
+const bots = [
+ { id: FRONTEND, name: 'Frontend', title: 'Frontend engineer', avatar_sprite: 'dev' },
+ { id: GROWTH, name: 'Growth', title: 'Growth', avatar_sprite: 'marketer' },
+];
+let n = 0;
+const fileId = () => `00000000-0000-4000-8000-${String(++n).padStart(12, '0')}`;
+const at = (hm, s = 0) => `2026-11-09T${hm}:${String(s).padStart(2, '0')}Z`;
+const you = (id, text, when) => ({ id, sender_role: 'user', sender_id: 'Oleks', text, created_at: when });
+const reply = (id, sender, text, when) => ({ id, sender_role: 'kwant', sender_id: sender, text, created_at: when });
+// Real, differing sizes: each name has its own size, so only a true re-share of the same bytes matches.
+const sizeOf = (name) => 40000 + [...name].reduce((t, c, i) => t + c.charCodeAt(0) * (i + 1), 0);
+const share = (id, sender, name, when, size = sizeOf(name)) => ({
+ id,
+ sender_role: 'kwant',
+ sender_id: sender,
+ text: `Shared ${name}`,
+ created_at: when,
+ meta: JSON.stringify({ kind: 'file', attachments: [{ id: fileId(), name, mime: 'image/jpeg', size }] }),
+});
+
+// ---- names --------------------------------------------------------------------------------------
+
+test('a uuid sender resolves to its bot; an unknown one is "A bot", never the chat title', () => {
+ assert.equal(m.botDisplayName(FRONTEND, bots), 'Frontend');
+ assert.equal(m.botDisplayName('Frontend', bots), 'Frontend', 'replies store the name');
+ assert.equal(m.botDisplayName(GONE, bots), 'A bot');
+ assert.equal(m.botDisplayName(GONE, []), 'A bot', 'list not loaded yet');
+ assert.equal(m.botDisplayName('', bots), 'A bot');
+ assert.equal(m.botDisplayName('Laya', bots), 'Laya', 'a short stored name stays');
+ assert.equal(m.botOf(FRONTEND, bots).id, FRONTEND);
+ assert.equal(m.botOf('Growth', bots).id, GROWTH);
+ assert.equal(m.botOf(GONE, bots), null);
+});
+
+// ---- placement ----------------------------------------------------------------------------------
+
+test("a turn's shares move right under that bot's reply; other bots' and later turns stay put", () => {
+ const msgs = [
+ you('u1', 'Show mw screenshot in chat!!', at('10:25')),
+ share('f1', FRONTEND, 'find-your-book-bar.jpg', at('10:26', 5)),
+ reply('g1', 'Growth', 'Not mine.', at('10:26', 10)),
+ reply('r1', 'Frontend', 'I took a fresh screenshot and shared it in this chat', at('10:26', 30)),
+ you('u2', 'why it not aligned?', at('10:27')),
+ share('f2', FRONTEND, 'lonely.png', at('10:27', 30)),
+ ];
+ const a = m.arrangeSharedFiles(msgs, bots);
+ assert.deepEqual(a.messages.map((x) => x.id), ['u1', 'g1', 'r1', 'f1', 'u2', 'f2']);
+ assert.equal(a.attached.has('f1'), true);
+ assert.equal(a.attached.has('f2'), false, 'no reply after it in its turn: it keeps its own header');
+ assert.equal(a.earlier.size, 0);
+});
+
+test('a share saved after the reply is attached in place; a share never jumps into another turn', () => {
+ const msgs = [
+ you('u1', 'go', at('10:00')),
+ reply('r1', 'Frontend', 'Here it is', at('10:00', 20)),
+ share('f1', FRONTEND, 'a.png', at('10:00', 21)),
+ you('u2', 'thanks', at('10:01')),
+ reply('r2', 'Frontend', 'ok', at('10:01', 5)),
+ ];
+ const a = m.arrangeSharedFiles(msgs, bots);
+ assert.deepEqual(a.messages.map((x) => x.id), ['u1', 'r1', 'f1', 'u2', 'r2']);
+ assert.equal(a.attached.has('f1'), true);
+});
+
+// ---- repeats ------------------------------------------------------------------------------------
+
+test('identical repeats collapse into the newest; a different file in between does not stop it', () => {
+ const msgs = [
+ you('u1', 'the button is not aligned!!!!', at('10:27')),
+ share('f1', FRONTEND, 'find-your-book-bar.jpg', at('10:28', 0)),
+ share('f2', FRONTEND, 'find-your-book-bar-dark.jpg', at('10:28', 10)),
+ share('f3', FRONTEND, 'find-your-book-bar.jpg', at('10:28', 20)),
+ share('f4', FRONTEND, 'find-your-book-bar.jpg', at('10:28', 40)),
+ reply('r1', 'Frontend', 'Restyled from styles.css', at('10:28', 50)),
+ ];
+ const a = m.arrangeSharedFiles(msgs, bots);
+ assert.deepEqual(a.messages.map((x) => x.id), ['u1', 'r1', 'f2', 'f4']);
+ assert.deepEqual(a.earlier.get('f4').map((x) => x.id), ['f1', 'f3'], 'oldest first');
+ assert.equal(a.attached.has('f2') && a.attached.has('f4'), true);
+});
+
+test('the same bytes fold; the same name with an edited picture does not (Mira 1)', () => {
+ const msgs = [
+ you('u1', 'Fix it and re-shoot', at('10:40')),
+ share('s1', FRONTEND, 'screenshot-example.com.jpg', at('10:40', 5), 51234),
+ share('s2', FRONTEND, 'screenshot-example.com.jpg', at('10:40', 15), 51234),
+ share('s3', FRONTEND, 'screenshot-example.com.jpg', at('10:41', 0), 49870),
+ reply('r1', 'Frontend', 'Fixed, here is before and after', at('10:41', 10)),
+ ];
+ const a = m.arrangeSharedFiles(msgs, bots);
+ assert.deepEqual(a.messages.map((x) => x.id), ['u1', 'r1', 's2', 's3'], 'the edited picture stays its own tile');
+ assert.deepEqual(a.earlier.get('s2').map((x) => x.id), ['s1'], 'the identical copy folds');
+ assert.equal(a.earlier.has('s3'), false);
+});
+
+test('repeats need the same bot, the same name and a few minutes', () => {
+ const msgs = [
+ you('u1', 'go', at('10:00')),
+ share('a1', FRONTEND, 'x.png', at('10:00', 0)),
+ share('a2', GROWTH, 'x.png', at('10:00', 30)),
+ share('a3', FRONTEND, 'x.png', at('10:20', 0)),
+ ];
+ const a = m.arrangeSharedFiles(msgs, bots);
+ assert.deepEqual(a.messages.map((x) => x.id), ['u1', 'a1', 'a2', 'a3'], 'another bot breaks the run; 20 min apart is not a repeat');
+ assert.equal(a.earlier.size, 0);
+});
+
+test('an id row and a name row of the same bot count as the same sender', () => {
+ const msgs = [you('u1', 'go', at('10:00')), share('a1', FRONTEND, 'x.png', at('10:00', 0)), share('a2', 'Frontend', 'x.png', at('10:00', 9))];
+ const a = m.arrangeSharedFiles(msgs, bots);
+ assert.deepEqual(a.messages.map((x) => x.id), ['u1', 'a2']);
+ assert.deepEqual(a.earlier.get('a2').map((x) => x.id), ['a1']);
+});
+
+// ---- ChatView -----------------------------------------------------------------------------------
+
+function mount(messages, extra = {}) {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ const props = {
+ title: '@booktun.ing',
+ messages,
+ streamingText: '',
+ streamingThinking: '',
+ pendingApprovals: [],
+ isStreaming: false,
+ onSendMessage: () => true,
+ onResolveApproval: () => {},
+ contextKey: 'space-1',
+ kwants: bots,
+ ...extra,
+ };
+ flushSync(() => root.render(h(m.ChatView, props)));
+ return { host, unmount: () => { flushSync(() => root.unmount()); host.remove(); } };
+}
+const rowIds = (host) => [...host.querySelectorAll('[role="log"] [data-message-id]')].map((e) => e.getAttribute('data-message-id'));
+
+test("ChatView: the old uuid rows show the bot's name, never the chat title, and sit under its reply", async () => {
+ const msgs = [
+ you('u1', 'Show mw screenshot in chat!!', at('10:25')),
+ share('f1', FRONTEND, 'find-your-book-bar.jpg', at('10:26', 5)),
+ share('f9', GONE, 'mystery.png', at('10:26', 6)),
+ reply('r1', 'Frontend', 'I took a fresh screenshot and shared it in this chat', at('10:26', 30)),
+ ];
+ const v = mount(msgs);
+ await settle();
+ const log = v.host.querySelector('[role="log"]');
+ assert.deepEqual(rowIds(v.host), ['u1', 'f9', 'r1', 'f1'], "the Frontend picture follows Frontend's reply; the unknown one stays");
+ const f1 = log.querySelector('[data-message-id="f1"]');
+ assert.equal(f1.hasAttribute('data-shared-under'), true);
+ assert.match(f1.textContent, /Shared by Frontend/);
+ assert.ok(f1.querySelector('img[alt="find-your-book-bar.jpg, shared by Frontend"]'), "the image names its bot in the alt text");
+ const f9 = log.querySelector('[data-message-id="f9"]');
+ assert.match(f9.textContent, /A bot/);
+ assert.doesNotMatch(log.textContent, /@booktun\.ing/, 'the chat title never names a sender');
+ v.unmount();
+});
+
+test('ChatView: three copies show once, with "Shared 3 times · Show 2 earlier" opening the older two', async () => {
+ const msgs = [
+ you('u1', 'Fix differences!', at('10:29')),
+ share('f1', FRONTEND, 'find-your-book-bar.jpg', at('10:29', 10)),
+ share('f2', FRONTEND, 'find-your-book-bar.jpg', at('10:29', 40)),
+ share('f3', FRONTEND, 'find-your-book-bar.jpg', at('10:30', 0)),
+ reply('r1', 'Frontend', 'Added the pixel edge and the card shadows.', at('10:30', 20)),
+ ];
+ const v = mount(msgs);
+ await settle();
+ assert.deepEqual(rowIds(v.host), ['u1', 'r1', 'f3']);
+ assert.equal(v.host.querySelectorAll('[role="log"] img[alt="find-your-book-bar.jpg, shared by Frontend"]').length, 1);
+ const toggle = v.host.querySelector('[data-earlier-copies] button');
+ assert.equal(toggle.textContent, 'Shared 3 times · Show 2 earlier');
+ assert.equal(toggle.getAttribute('aria-label'), 'Show 2 earlier copies of find-your-book-bar.jpg');
+ assert.equal(toggle.getAttribute('aria-expanded'), 'false');
+ flushSync(() => toggle.click());
+ assert.equal(toggle.getAttribute('aria-expanded'), 'true');
+ assert.equal(toggle.textContent, 'Hide earlier');
+ assert.deepEqual([...v.host.querySelectorAll('[data-earlier-copy]')].map((e) => e.getAttribute('data-earlier-copy')), ['f1', 'f2']);
+ assert.equal(v.host.querySelectorAll('[role="log"] img[alt="find-your-book-bar.jpg, shared by Frontend"]').length, 3);
+ v.unmount();
+});
+
+test('ChatView: a click opens the picture full size; Esc closes it and focus returns', async () => {
+ const msgs = [you('u1', 'show me', at('10:25')), reply('r1', 'Frontend', 'Here', at('10:26')), share('f1', FRONTEND, 'bar.jpg', at('10:26', 2))];
+ const v = mount(msgs);
+ await settle();
+ const thumb = v.host.querySelector('[data-image-thumb]');
+ assert.equal(thumb.getAttribute('aria-label'), 'View bar.jpg full size');
+ flushSync(() => thumb.dispatchEvent(new window.MouseEvent('click', { bubbles: true, cancelable: true, button: 0 })));
+ const dlg = document.querySelector('[data-image-viewer]');
+ assert.ok(dlg, 'viewer open');
+ assert.equal(dlg.getAttribute('role'), 'dialog');
+ assert.equal(dlg.getAttribute('aria-modal'), 'true');
+ assert.ok(dlg.querySelector('img[alt="bar.jpg, shared by Frontend"]'));
+ assert.match(dlg.className, /bg-black\/85/, 'scrim is black at 85%');
+ assert.equal(dlg.style.height, '100dvh');
+ assert.equal(dlg.querySelector('img').style.touchAction, 'pinch-zoom', 'pinch-zoom left to the browser');
+ assert.match(dlg.textContent, /bar\.jpg · Frontend · \S/, 'bottom bar: file, bot, time');
+ const orig = [...dlg.querySelectorAll('a')].find((a) => a.textContent.includes('Open original'));
+ assert.equal(orig.getAttribute('target'), '_blank');
+ assert.equal(orig.getAttribute('rel'), 'noopener');
+ assert.equal(document.body.style.overflow, 'hidden', 'page behind does not scroll');
+ assert.equal(document.activeElement.getAttribute('aria-label'), 'Close');
+ assert.match(document.activeElement.className, /w-11 h-11/, 'Close is 44 px');
+ flushSync(() => document.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));
+ assert.equal(document.querySelector('[data-image-viewer]'), null);
+ assert.equal(document.body.style.overflow, '', 'scroll lock released');
+ assert.equal(document.activeElement, thumb);
+ // a tap on the scrim closes it too
+ flushSync(() => thumb.dispatchEvent(new window.MouseEvent('click', { bubbles: true, cancelable: true, button: 0 })));
+ const dlg2 = document.querySelector('[data-image-viewer]');
+ flushSync(() => dlg2.dispatchEvent(new window.MouseEvent('click', { bubbles: true })));
+ assert.equal(document.querySelector('[data-image-viewer]'), null);
+ // Cmd/Ctrl click keeps the browser's new tab
+ const ev = new window.MouseEvent('click', { bubbles: true, cancelable: true, button: 0, ctrlKey: true });
+ thumb.addEventListener('click', (e) => e.preventDefault(), { once: true });
+ flushSync(() => thumb.dispatchEvent(ev));
+ assert.equal(document.querySelector('[data-image-viewer]'), null);
+ v.unmount();
+});
+
+test("ChatView: in a bot's own chat an id row resolves to that bot even before the list loads", async () => {
+ const home = { kind: 'bot', bot: { id: FRONTEND, name: 'Frontend', title: 'Frontend engineer', avatar_sprite: 'dev' } };
+ const v = mount([you('u1', 'x', at('10:00')), share('f1', FRONTEND, 'a.png', at('10:00', 5))], { kwants: [], home, title: 'Frontend' });
+ await settle();
+ assert.match(v.host.querySelector('[data-message-id="f1"]').textContent, /Frontend/);
+ assert.doesNotMatch(v.host.querySelector('[data-message-id="f1"]').textContent, /A bot/);
+ v.unmount();
+});
+
+// ---- the server's new shape (vega-080-share-screens) --------------------------------------------
+
+const newShare = (id, bot, name, when, auto = false) => ({
+ id,
+ sender_role: 'kwant',
+ sender_id: bot.name,
+ text: `Shared a file: ${name}`,
+ created_at: when,
+ meta: JSON.stringify({ kind: 'file', attachments: [{ id: fileId(), name, mime: 'image/jpeg', size: sizeOf(name) }], kwant_id: bot.id, kwant_name: bot.name, turn_id: 't1', auto }),
+});
+
+test("shareInfo reads kwant_id and auto; a new-shape share follows its bot's reply", () => {
+ const s = newShare('n1', bots[0], 'screenshot-booktun.ing.jpg', at('11:00'), true);
+ assert.deepEqual(m.shareInfo(s.meta), { kwantId: FRONTEND, auto: true });
+ assert.deepEqual(m.shareInfo(null), { kwantId: null, auto: false });
+ assert.deepEqual(m.shareInfo('{"kind":"file","auto":"yes"}'), { kwantId: null, auto: false }, 'only a real true counts');
+ // A share named after its bot, with the id in meta, follows that bot's reply (by id).
+ const msgs = [you('u1', 'show me', at('11:00')), newShare('n2', bots[0], 'screenshot.jpg', at('11:00', 5)), reply('r1', FRONTEND, 'Here it is', at('11:00', 9))];
+ assert.deepEqual(m.arrangeSharedFiles(msgs, bots).messages.map((x) => x.id), ['u1', 'r1', 'n2']);
+});
+
+test('ChatView: a new-shape share shows its bot, and an automatic one says "Shared automatically"', async () => {
+ const msgs = [
+ you('u1', 'Show me the page', at('11:10')),
+ reply('r1', 'Growth', 'Here is the page I opened.', at('11:10', 20)),
+ newShare('n1', bots[1], 'screenshot-booktun.ing.jpg', at('11:10', 21), true),
+ you('u2', 'and the other', at('11:11')),
+ newShare('n2', bots[1], 'screenshot.jpg', at('11:11', 5)),
+ reply('r2', 'Growth', 'Shared above.', at('11:11', 9)),
+ ];
+ const v = mount(msgs);
+ await settle();
+ const log = v.host.querySelector('[role="log"]');
+ assert.deepEqual(rowIds(v.host), ['u1', 'r1', 'n1', 'u2', 'r2', 'n2']);
+ const n1 = log.querySelector('[data-message-id="n1"]');
+ assert.equal(n1.hasAttribute('data-shared-under'), true);
+ assert.match(n1.textContent, /Shared by Growth/);
+ assert.ok(n1.querySelector('[data-shared-auto]'), 'auto share has the hint');
+ assert.match(n1.querySelector('[data-shared-auto]').textContent, /^Shared automatically$/);
+ assert.equal(log.querySelector('[data-message-id="n2"] [data-shared-auto]'), null, 'a share the bot made itself has no hint');
+ v.unmount();
+});
+
+// ---- the running turn (Mira: no jump) -----------------------------------------------------------
+
+test("arrange: while a bot's turn runs, its loose shares go to the live row; others' stay", () => {
+ const msgs = [
+ you('u0', 'earlier', at('10:00')),
+ share('old', FRONTEND, 'old.jpg', at('10:00', 5)),
+ you('u1', 'Show it', at('10:25')),
+ share('f1', FRONTEND, 'bar.jpg', at('10:26', 5)),
+ share('g1', GROWTH, 'chart.png', at('10:26', 6)),
+ ];
+ const a = m.arrangeSharedFiles(msgs, bots, 'Frontend');
+ assert.deepEqual(a.live.map((x) => x.id), ['f1']);
+ assert.deepEqual(a.messages.map((x) => x.id), ['u0', 'old', 'u1', 'g1'], 'an earlier turn never moves');
+ assert.deepEqual(m.arrangeSharedFiles(msgs, bots).live, []);
+});
+
+test("ChatView: a share during the turn shows under the bot's live row, then stays put when the reply lands", async () => {
+ const base = [you('u1', 'Show mw screenshot in chat!!', at('10:25')), share('f1', FRONTEND, 'bar.jpg', at('10:26', 5))];
+ const v = mount(base, { isStreaming: true, streamingSpeakerName: 'Frontend', streamingText: 'Taking a screenshot' });
+ await settle();
+ const ids = rowIds(v.host);
+ assert.deepEqual(ids, ['u1', 'f1']);
+ const f1 = v.host.querySelector('[data-message-id="f1"]');
+ assert.equal(f1.hasAttribute('data-shared-under'), true, 'drawn as part of the live row, no second header');
+ // it sits after the live bubble, not before it
+ const live = [...v.host.querySelectorAll('[role="log"] > *')];
+ const liveIdx = live.findIndex((e) => e.textContent.includes('Taking a screenshot'));
+ assert.ok(liveIdx >= 0 && live.indexOf(f1) > liveIdx, 'after the streaming bubble');
+ v.unmount();
+ const done = mount([...base, reply('r1', 'Frontend', 'Shared it', at('10:26', 30))]);
+ await settle();
+ assert.deepEqual(rowIds(done.host), ['u1', 'r1', 'f1']);
+ assert.equal(done.host.querySelector('[data-message-id="f1"]').hasAttribute('data-shared-under'), true);
+ done.unmount();
+});
+
+// ---- rework after review (Ada A, Mira 2-5, 7, 8; two bots) --------------------------------------
+
+test('ChatView: the open viewer keeps focus where the person put it while a reply streams (Ada A)', async () => {
+ const msgs = [you('u1', 'show me', at('10:25')), reply('r1', 'Frontend', 'Here', at('10:26')), share('f1', FRONTEND, 'bar.jpg', at('10:26', 2))];
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ const props = (text) => ({
+ title: '@booktun.ing', messages: msgs, streamingText: text, streamingThinking: '', pendingApprovals: [], isStreaming: true,
+ streamingSpeakerName: 'Growth', onSendMessage: () => true, onResolveApproval: () => {}, contextKey: 'space-1', kwants: bots,
+ });
+ flushSync(() => root.render(h(m.ChatView, props('Look'))));
+ await settle();
+ const thumb = host.querySelector('[data-image-thumb]');
+ flushSync(() => thumb.dispatchEvent(new window.MouseEvent('click', { bubbles: true, cancelable: true, button: 0 })));
+ const dlg = document.querySelector('[data-image-viewer]');
+ const orig = [...dlg.querySelectorAll('a')].find((a) => a.textContent.includes('Open original'));
+ orig.focus();
+ assert.equal(document.activeElement, orig);
+ for (const t of ['Looking', 'Looking at', 'Looking at the page']) flushSync(() => root.render(h(m.ChatView, props(t))));
+ await settle();
+ assert.ok(document.querySelector('[data-image-viewer]'), 'still open');
+ assert.equal(document.activeElement, orig, 'new tokens do not pull focus back to Close');
+ flushSync(() => document.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));
+ assert.equal(document.querySelector('[data-image-viewer]'), null, 'Esc still closes after re-renders');
+ assert.equal(document.activeElement, host.querySelector('[data-image-thumb]'));
+ flushSync(() => root.unmount());
+ host.remove();
+});
+
+test('ChatView: tap targets and focus ring on shared tiles (Mira 2, 3, 4, 5, 7, 8)', async () => {
+ const msgs = [
+ you('u1', 'go', at('10:29')),
+ share('f1', FRONTEND, 'find-your-book-bar.jpg', at('10:29', 10)),
+ share('f2', FRONTEND, 'find-your-book-bar.jpg', at('10:29', 40)),
+ reply('r1', 'Frontend', 'Done', at('10:30', 20)),
+ ];
+ const v = mount(msgs);
+ await settle();
+ const toggle = v.host.querySelector('[data-earlier-copies] button');
+ assert.match(toggle.className, /(^|\s)py-3\.5(\s|$)/, '44 px tall on phone (16 px line + 2 x 14 px)');
+ assert.match(toggle.className, /sm:py-1/);
+ const tile = v.host.querySelector('[data-message-id="f2"] figure');
+ const dl = tile.querySelector('[data-download]');
+ assert.match(dl.className, /w-8 h-8/, 'icon-only 32 px chip on a shared tile');
+ // 1 px border: ::before insets from the 30 px padding box, so 30 + 2 x 7 = 44 px (Rigel qa-468)
+ assert.match(dl.className, /before:-inset-\[7px\]/, '30 + 2 x 7 = 44 px hit area');
+ assert.doesNotMatch(dl.className, /before:-inset-1\.5/, 'not the 42 px hit area');
+ assert.equal(dl.getAttribute('aria-label'), 'Download find-your-book-bar.jpg');
+ assert.equal(dl.getAttribute('title'), 'Download');
+ assert.match(dl.querySelector('span').className, /sr-only/);
+ const thumb = tile.querySelector('[data-image-thumb]');
+ assert.match(thumb.className, /focus-visible:outline-offset-\[-2px\]/, 'ring drawn inside the clipped figure');
+ assert.match(thumb.className, /focus-visible:outline-violet-400/);
+ assert.match(tile.parentElement.className, /w-full sm:w-auto/, 'full bubble width on phone');
+ flushSync(() => toggle.click());
+ const chips = [...v.host.querySelectorAll('[data-earlier-copy] [data-download]')];
+ assert.ok(chips.length > 0, 'earlier copies have Download chips');
+ for (const chip of chips) {
+ assert.match(chip.className, /before:-inset-\[7px\]/, 'earlier-copy chips get the 44 px hit area too');
+ }
+ const small = v.host.querySelector('[data-earlier-copy="f1"] figure');
+ assert.match(small.querySelector('img').className, /w-full h-24/, 'small copy fills its tile');
+ assert.doesNotMatch(small.querySelector('img').className, /max-h-24|sm:w-auto/);
+ assert.match(small.querySelector('figcaption .whitespace-nowrap').textContent, /JPEG|JPG|Image/i);
+ v.unmount();
+ // a person's own upload keeps the labelled button, 44 px on phone
+ const mine = mount([{ ...you('u9', 'here', at('10:31')), meta: JSON.stringify({ attachments: [{ id: fileId(), name: 'me.png', mime: 'image/png', size: 1200 }] }) }]);
+ await settle();
+ const own = mine.host.querySelector('[data-download]');
+ if (own) assert.match(own.className, /max-sm:min-w-11 max-sm:min-h-11/);
+ mine.unmount();
+});
+
+test("ChatView: in a team chat with two bots, each bot's share sits under its own reply", async () => {
+ const msgs = [
+ you('u1', 'Both of you, show me', at('10:50')),
+ share('fa', FRONTEND, 'header.png', at('10:50', 5)),
+ share('ga', GROWTH, 'funnel.png', at('10:50', 6)),
+ reply('gr', 'Growth', 'Funnel is above.', at('10:50', 20)),
+ reply('fr', 'Frontend', 'Header is fixed.', at('10:50', 30)),
+ ];
+ const v = mount(msgs, { title: 'Ship team' });
+ await settle();
+ assert.deepEqual(rowIds(v.host), ['u1', 'gr', 'ga', 'fr', 'fa'], "Frontend's picture does not land under Growth's reply");
+ assert.match(v.host.querySelector('[data-message-id="ga"]').textContent, /Shared by Growth/);
+ assert.match(v.host.querySelector('[data-message-id="fa"]').textContent, /Shared by Frontend/);
+ assert.ok(v.host.querySelector('img[alt="header.png, shared by Frontend"]'));
+ assert.ok(v.host.querySelector('img[alt="funnel.png, shared by Growth"]'));
+ v.unmount();
+});