Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(ui): place artifact cards from message-log rows; autosave and download

Sanil074bc4310322
diff --git a/app/src/components/chat/ChatFilesChip.tsx b/app/src/components/chat/ChatFilesChip.tsx
deleted file mode 100644
index 788c3b7be1..0000000000
--- a/app/src/components/chat/ChatFilesChip.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-import { useEffect, useMemo, useState } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import { listArtifactsForThread } from '../../services/artifactDownloadService';
-import { upsertArtifactReadyForThread } from '../../store/chatRuntimeSlice';
-import { useAppDispatch, useAppSelector } from '../../store/hooks';
-import { Button } from '../ui';
-import ChatFilesPanel from './ChatFilesPanel';
-
-/**
- * Header chip surfacing the count of ready artifacts for a thread (#3024).
- *
- * - Hidden when the count is zero (no chrome cost on chats that never
- * generated a file).
- * - Click opens the {@link ChatFilesPanel} popover; clicking again or
- * pressing Esc closes it (panel owns Esc + click-outside).
- *
- * Reads from the persisted `chatRuntime.artifactsByThread` slice — entries
- * survive app restarts via the `artifactsReadyOnlyTransform` configured in
- * `store/index.ts`.
- */
-interface ChatFilesChipProps {
- threadId: string;
-}
-
-export default function ChatFilesChip({ threadId }: ChatFilesChipProps) {
- const { t } = useT();
- const dispatch = useAppDispatch();
- const [open, setOpen] = useState(false);
- const normalizedThreadId = threadId.trim();
- const artifactsByThread = useAppSelector(state => state.chatRuntime.artifactsByThread);
- // Only ready artifacts are listable — in_progress / failed live above the
- // composer until they resolve.
- const readyArtifacts = useMemo(
- () => (artifactsByThread[normalizedThreadId] ?? []).filter(a => a.status === 'ready'),
- [artifactsByThread, normalizedThreadId]
- );
- const count = readyArtifacts.length;
-
- useEffect(() => {
- if (!normalizedThreadId) return;
- let cancelled = false;
- void listArtifactsForThread(normalizedThreadId).then(outcome => {
- if (cancelled) return;
- if (!outcome.ok) {
- console.warn('[artifact] ChatFilesChip failed to hydrate thread artifacts', {
- threadId: normalizedThreadId,
- error: outcome.error,
- });
- return;
- }
- if (outcome.artifacts.length === 0) return;
- console.debug('[artifact] ChatFilesChip hydrating thread artifacts', {
- threadId: normalizedThreadId,
- count: outcome.artifacts.length,
- });
- for (const artifact of outcome.artifacts) {
- dispatch(
- upsertArtifactReadyForThread({
- threadId: normalizedThreadId,
- artifactId: artifact.artifactId,
- kind: artifact.kind,
- title: artifact.title,
- path: artifact.path,
- sizeBytes: artifact.sizeBytes,
- })
- );
- }
- });
- return () => {
- cancelled = true;
- };
- }, [dispatch, normalizedThreadId]);
-
- if (count === 0) return null;
-
- return (
- <div className="relative inline-block">
- <Button
- variant="secondary"
- size="sm"
- analyticsId="chat-files-chip"
- onClick={() => setOpen(prev => !prev)}
- aria-haspopup="dialog"
- aria-expanded={open}
- aria-label={t(
- count === 1 ? 'chat.files.chip.aria.one' : 'chat.files.chip.aria.other'
- ).replace('{count}', String(count))}
- data-testid="chat-files-chip"
- className="h-7! gap-1.5 text-xs font-medium text-content-secondary">
- <svg
- aria-hidden="true"
- className="w-3.5 h-3.5"
- fill="none"
- stroke="currentColor"
- strokeWidth={1.8}
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.49"
- />
- </svg>
- <span data-testid="chat-files-chip-count" className="font-mono leading-none">
- {count}
- </span>
- </Button>
- {open && (
- <ChatFilesPanel
- threadId={normalizedThreadId}
- artifacts={readyArtifacts}
- onClose={() => setOpen(false)}
- />
- )}
- </div>
- );
-}
diff --git a/app/src/components/chat/ChatFilesPanel.tsx b/app/src/components/chat/ChatFilesPanel.tsx
deleted file mode 100644
index 57bfcbec86..0000000000
--- a/app/src/components/chat/ChatFilesPanel.tsx
+++ /dev/null
@@ -1,411 +0,0 @@
-import { useEffect, useRef, useState } from 'react';
-
-import { formatFileSize } from '../../lib/attachments';
-import { useT } from '../../lib/i18n/I18nContext';
-import {
- type ArtifactErrorCode,
- deleteArtifact,
- downloadArtifact,
- revealArtifact,
-} from '../../services/artifactDownloadService';
-import {
- type ArtifactSnapshot,
- removeArtifactForThread,
- upsertArtifactReadyForThread,
-} from '../../store/chatRuntimeSlice';
-import { useAppDispatch } from '../../store/hooks';
-import { Button } from '../ui';
-import { extensionFor } from './artifactExtension';
-
-/**
- * Popover panel listing every `ready` artifact for a thread (#3024).
- *
- * Mounted by {@link ChatFilesChip}. Renders one row per artifact with:
- * - kind icon + title + human-readable size
- * - Download (Tauri `download_artifact_to_downloads`)
- * - Show in folder: opens the file manager at the artifact's real file in
- * the visible files folder (#5505)
- * - Delete with a confirm-step (optimistic slice removal + RPC call,
- * re-upsert on failure with a toast).
- *
- * Closes on Esc + click-outside. Empty state copy is the panel's only
- * fallback (the chip itself is hidden when count is zero, so the empty
- * state only shows if the user deletes the last artifact while the
- * panel is open).
- */
-interface ChatFilesPanelProps {
- threadId: string;
- artifacts: ArtifactSnapshot[];
- onClose: () => void;
-}
-
-/**
- * Map a structured {@link ArtifactErrorCode} to a localized headline.
- * Caller passes the raw `outcome.error` as a fallback — if the service
- * returns no code (e.g. older callers), the raw text wins. Routing all
- * codes through `t(...)` keeps non-English locales from leaking English
- * error copy into the panel.
- */
-function localizeErrorCode(
- t: (key: string, fallback?: string) => string,
- code: ArtifactErrorCode | undefined,
- fallback: string | undefined
-): string {
- if (!code) return fallback ?? '';
- switch (code) {
- case 'NOT_DESKTOP':
- return t('chat.files.error.not_desktop');
- case 'MISSING_ARTIFACT_ID':
- return t('chat.files.error.missing_artifact_id');
- case 'MISSING_ARTIFACT_PATH':
- return t('chat.files.error.missing_artifact_path');
- case 'RESOLVE_FAILED':
- return t('chat.files.error.resolve_failed');
- case 'DOWNLOAD_FAILED':
- return t('chat.files.error.download_failed');
- case 'DELETE_FAILED':
- return t('chat.files.error.delete_failed');
- case 'REVEAL_FAILED':
- return t('chat.files.error.reveal_failed');
- case 'CANCELLED':
- // User-initiated dialog dismissal — not a real error. Callers treat
- // it as a no-op; surface nothing (fall back to raw text if passed).
- return fallback ?? '';
- default: {
- // Exhaustive guard: a new code added to ArtifactErrorCode without a
- // matching arm here will fail to type-check.
- const _exhaustive: never = code;
- return _exhaustive;
- }
- }
-}
-
-function KindIcon({ kind }: { kind: ArtifactSnapshot['kind'] }) {
- const stroke = 'currentColor';
- switch (kind) {
- case 'presentation':
- return (
- <svg
- aria-hidden="true"
- className="w-4 h-4 shrink-0"
- fill="none"
- stroke={stroke}
- strokeWidth={1.8}
- viewBox="0 0 24 24">
- <path strokeLinecap="round" strokeLinejoin="round" d="M3 5h18v12H3z" />
- <path strokeLinecap="round" d="M8 21h8M12 17v4" />
- <path strokeLinecap="round" strokeLinejoin="round" d="M7 11l3 3 4-5 3 4" />
- </svg>
- );
- case 'document':
- return (
- <svg
- aria-hidden="true"
- className="w-4 h-4 shrink-0"
- fill="none"
- stroke={stroke}
- strokeWidth={1.8}
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- d="M14 3H7a2 2 0 00-2 2v14a2 2 0 002 2h10a2 2 0 002-2V8z"
- />
- <path strokeLinecap="round" d="M14 3v5h5M9 13h6M9 17h6" />
- </svg>
- );
- case 'image':
- return (
- <svg
- aria-hidden="true"
- className="w-4 h-4 shrink-0"
- fill="none"
- stroke={stroke}
- strokeWidth={1.8}
- viewBox="0 0 24 24">
- <path strokeLinecap="round" strokeLinejoin="round" d="M3 5h18v14H3z" />
- <circle cx="9" cy="10" r="1.5" />
- <path strokeLinecap="round" strokeLinejoin="round" d="M3 17l5-5 4 4 3-3 6 6" />
- </svg>
- );
- case 'video':
- return (
- <svg
- aria-hidden="true"
- className="w-4 h-4 shrink-0"
- fill="none"
- stroke={stroke}
- strokeWidth={1.8}
- viewBox="0 0 24 24">
- <path strokeLinecap="round" strokeLinejoin="round" d="M3 5h13v14H3z" />
- <path strokeLinecap="round" strokeLinejoin="round" d="M16 10l5-3v10l-5-3z" />
- </svg>
- );
- default:
- return (
- <svg
- aria-hidden="true"
- className="w-4 h-4 shrink-0"
- fill="none"
- stroke={stroke}
- strokeWidth={1.8}
- viewBox="0 0 24 24">
- <path strokeLinecap="round" strokeLinejoin="round" d="M4 4h16v16H4z" />
- </svg>
- );
- }
-}
-
-interface RowDownloadState {
- state: 'idle' | 'downloading' | 'done' | 'error';
- /** Already-localized error headline ready for direct render. */
- error?: string;
-}
-
-export default function ChatFilesPanel({ threadId, artifacts, onClose }: ChatFilesPanelProps) {
- const { t } = useT();
- const dispatch = useAppDispatch();
- const containerRef = useRef<HTMLDivElement | null>(null);
- const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);
- const [downloadState, setDownloadState] = useState<Record<string, RowDownloadState>>({});
- const [deleteError, setDeleteError] = useState<string | null>(null);
- // Per-row "Show in folder" failure, already localized.
- const [revealError, setRevealError] = useState<Record<string, string>>({});
-
- // Esc closes. Use keydown not keyup so a panel that opened via Enter
- // doesn't immediately re-trigger its trigger on the same release.
- useEffect(() => {
- const onKey = (e: KeyboardEvent) => {
- if (e.key === 'Escape') {
- if (confirmDeleteId) {
- setConfirmDeleteId(null);
- } else {
- onClose();
- }
- }
- };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, [confirmDeleteId, onClose]);
-
- // Click-outside closes. Pointerdown fires before click, so the chip's
- // toggle handler doesn't immediately re-open the just-closed panel.
- useEffect(() => {
- const onPointer = (e: PointerEvent) => {
- const node = containerRef.current;
- if (!node) return;
- const target = e.target as Node | null;
- if (target && !node.contains(target)) {
- onClose();
- }
- };
- document.addEventListener('pointerdown', onPointer);
- return () => document.removeEventListener('pointerdown', onPointer);
- }, [onClose]);
-
- const handleDownload = async (artifact: ArtifactSnapshot) => {
- setDownloadState(prev => ({ ...prev, [artifact.artifactId]: { state: 'downloading' } }));
- const ext = extensionFor(artifact.kind, artifact.title);
- const outcome = await downloadArtifact(artifact.artifactId, artifact.title, ext);
- setDownloadState(prev => ({
- ...prev,
- [artifact.artifactId]: outcome.ok
- ? { state: 'done' }
- : {
- state: 'error',
- // Prefer the localized headline; only fall back to the raw
- // detail when the service didn't supply a code (defensive —
- // every documented failure path returns one).
- error: localizeErrorCode(t, outcome.code, outcome.error),
- },
- }));
- };
-
- const handleReveal = async (artifact: ArtifactSnapshot) => {
- setRevealError(({ [artifact.artifactId]: _cleared, ...rest }) => rest);
- const outcome = await revealArtifact(artifact.artifactId);
- if (!outcome.ok) {
- setRevealError(prev => ({
- ...prev,
- [artifact.artifactId]: localizeErrorCode(t, outcome.code, outcome.error),
- }));
- }
- };
-
- const handleDeleteConfirm = async (artifact: ArtifactSnapshot) => {
- setConfirmDeleteId(null);
- setDeleteError(null);
- // Optimistic remove — re-upsert on failure so the row reappears.
- dispatch(removeArtifactForThread({ threadId, artifactId: artifact.artifactId }));
- const outcome = await deleteArtifact(artifact.artifactId);
- if (!outcome.ok) {
- // Re-insert the snapshot so the user sees it again. Keep updatedAt
- // fresh so the row sorts in the same spot it left.
- dispatch(
- upsertArtifactReadyForThread({
- threadId,
- artifactId: artifact.artifactId,
- kind: artifact.kind,
- title: artifact.title,
- path: artifact.path ?? '',
- sizeBytes: artifact.sizeBytes ?? 0,
- })
- );
- // Prefer the localized headline mapped from `code`; if neither
- // code nor a raw detail came back, fall back to the generic
- // delete-failed copy so the user always sees something.
- setDeleteError(
- localizeErrorCode(t, outcome.code, outcome.error) || t('chat.files.delete.failed')
- );
- }
- };
-
- return (
- <div
- ref={containerRef}
- role="dialog"
- aria-label={t('chat.files.panel.aria')}
- data-testid="chat-files-panel"
- className="absolute right-0 top-9 z-30 w-[360px] max-h-[420px] overflow-y-auto rounded-xl border border-line bg-surface shadow-lg">
- <header className="sticky top-0 z-10 bg-surface border-b border-line-subtle px-3 py-2 flex items-center justify-between">
- <span className="text-xs font-semibold uppercase tracking-wide text-content-muted">
- {t('chat.files.panel.title').replace('{count}', String(artifacts.length))}
- </span>
- <Button
- iconOnly
- variant="tertiary"
- size="xs"
- onClick={onClose}
- data-analytics-id="chat-files-panel-close"
- aria-label={t('chat.files.panel.close')}>
- <svg
- className="w-3.5 h-3.5"
- fill="none"
- stroke="currentColor"
- strokeWidth={2}
- viewBox="0 0 24 24">
- <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
- </svg>
- </Button>
- </header>
-
- {artifacts.length === 0 ? (
- <div className="px-3 py-6 text-xs text-content-muted text-center">
- {t('chat.files.panel.empty')}
- </div>
- ) : (
- <ul className="divide-y divide-line-subtle">
- {artifacts.map(artifact => {
- const row = downloadState[artifact.artifactId] ?? { state: 'idle' as const };
- const isConfirming = confirmDeleteId === artifact.artifactId;
- return (
- <li
- key={artifact.artifactId}
- className="px-3 py-2.5 flex flex-col gap-1"
- data-testid={`chat-files-row-${artifact.artifactId}`}>
- <div className="flex items-center gap-2.5 text-sm text-content-secondary">
- <KindIcon kind={artifact.kind} />
- <div className="flex flex-col min-w-0 flex-1">
- <span className="truncate font-medium leading-tight">{artifact.title}</span>
- <span className="text-[11px] font-mono text-content-muted leading-tight">
- {artifact.sizeBytes != null ? formatFileSize(artifact.sizeBytes) : ''}
- </span>
- </div>
- </div>
- {isConfirming ? (
- <div className="flex items-center gap-2 mt-1">
- <span className="text-[11px] text-content-secondary flex-1">
- {t('chat.files.delete.confirm')}
- </span>
- <Button
- variant="secondary"
- size="xs"
- onClick={() => setConfirmDeleteId(null)}
- analyticsId="chat-files-delete-cancel"
- className="text-[11px]">
- {t('chat.files.delete.cancel')}
- </Button>
- <Button
- variant="primary"
- tone="danger"
- size="xs"
- onClick={() => void handleDeleteConfirm(artifact)}
- analyticsId={`chat-files-delete-confirm-${artifact.kind}`}
- data-testid={`chat-files-confirm-${artifact.artifactId}`}
- className="text-[11px]">
- {t('chat.files.delete.action')}
- </Button>
- </div>
- ) : (
- <div className="flex items-center gap-2 mt-0.5">
- <Button
- variant="primary"
- size="xs"
- onClick={() => void handleDownload(artifact)}
- disabled={row.state === 'downloading'}
- analyticsId={`chat-files-download-${artifact.kind}`}
- data-testid={`chat-files-download-${artifact.artifactId}`}
- className="text-[11px]">
- {row.state === 'downloading'
- ? t('chat.artifact.downloading')
- : t('chat.artifact.download')}
- </Button>
- <Button
- variant="tertiary"
- size="xs"
- onClick={() => void handleReveal(artifact)}
- analyticsId={`chat-files-reveal-${artifact.kind}`}
- data-testid={`chat-files-reveal-${artifact.artifactId}`}
- className="text-[11px] underline text-sage-600">
- {t('chat.artifact.reveal')}
- </Button>
- <Button
- iconOnly
- variant="tertiary"
- tone="danger"
- size="xs"
- onClick={() => setConfirmDeleteId(artifact.artifactId)}
- analyticsId={`chat-files-delete-${artifact.kind}`}
- data-testid={`chat-files-delete-${artifact.artifactId}`}
- aria-label={t('chat.files.delete.aria').replace('{title}', artifact.title)}
- className="ml-auto w-auto! px-2">
- <svg
- className="w-3.5 h-3.5"
- fill="none"
- stroke="currentColor"
- strokeWidth={1.8}
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- d="M19 7l-1 12a2 2 0 01-2 2H8a2 2 0 01-2-2L5 7m5 4v6m4-6v6M4 7h16M9 7V4a1 1 0 011-1h4a1 1 0 011 1v3"
- />
- </svg>
- </Button>
- </div>
- )}
- {revealError[artifact.artifactId] && (
- <p
- className="text-[11px] text-coral-600 dark:text-coral-400 mt-0.5 wrap-break-word"
- data-testid={`chat-files-reveal-error-${artifact.artifactId}`}>
- {revealError[artifact.artifactId]}
- </p>
- )}
- {row.state === 'error' && row.error && (
- <p className="text-[11px] text-coral-600 dark:text-coral-400 mt-0.5 wrap-break-word">
- {t('chat.artifact.download_failed').replace('{reason}', row.error)}
- </p>
- )}
- </li>
- );
- })}
- </ul>
- )}
- {deleteError && (
- <div className="px-3 py-2 border-t border-line-subtle text-[11px] text-coral-600 dark:text-coral-400 wrap-break-word">
- {deleteError}
- </div>
- )}
- </div>
- );
-}
diff --git a/app/src/components/chat/__tests__/ChatFilesChip.test.tsx b/app/src/components/chat/__tests__/ChatFilesChip.test.tsx
deleted file mode 100644
index dd2cde0753..0000000000
--- a/app/src/components/chat/__tests__/ChatFilesChip.test.tsx
+++ /dev/null
@@ -1,221 +0,0 @@
-import { configureStore } from '@reduxjs/toolkit';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { Provider } from 'react-redux';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { listArtifactsForThread } from '../../../services/artifactDownloadService';
-import chatRuntimeReducer, {
- type ArtifactSnapshot,
- upsertArtifactInProgressForThread,
- upsertArtifactReadyForThread,
-} from '../../../store/chatRuntimeSlice';
-import ChatFilesChip from '../ChatFilesChip';
-
-vi.mock('../../../services/artifactDownloadService', () => ({
- listArtifactsForThread: vi.fn(),
- downloadArtifact: vi.fn(),
- deleteArtifact: vi.fn(),
- revealArtifact: vi.fn(),
-}));
-
-const THREAD = 't-chip-1';
-
-function mkStore() {
- return configureStore({ reducer: { chatRuntime: chatRuntimeReducer } });
-}
-
-function readyArtifact(
- idx: number
-): Omit<ArtifactSnapshot, 'updatedAt' | 'status'> & { path: string; sizeBytes: number } {
- return {
- artifactId: `art-${idx}`,
- kind: 'presentation' as const,
- title: `Deck ${idx}`,
- path: `artifacts/art-${idx}.pptx`,
- sizeBytes: 1024 * idx,
- };
-}
-
-describe('ChatFilesChip', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- vi.mocked(listArtifactsForThread).mockResolvedValue({ ok: true, artifacts: [] });
- });
-
- it('renders nothing when the thread has zero ready artifacts', () => {
- const store = mkStore();
- const { container } = render(
- <Provider store={store}>
- <ChatFilesChip threadId={THREAD} />
- </Provider>
- );
- // Empty render, no chip in DOM.
- expect(container.firstChild).toBeNull();
- expect(screen.queryByTestId('chat-files-chip')).toBeNull();
- });
-
- it('hydrates thread artifacts from disk when redux starts cold', async () => {
- vi.mocked(listArtifactsForThread).mockResolvedValueOnce({
- ok: true,
- artifacts: [
- {
- artifactId: 'art-cold',
- kind: 'document',
- title: 'Cold Redux Report',
- path: 'artifacts/art-cold/report.pdf',
- sizeBytes: 2048,
- },
- ],
- });
- const store = mkStore();
- render(
- <Provider store={store}>
- <ChatFilesChip threadId={THREAD} />
- </Provider>
- );
-
- await waitFor(() => {
- expect(screen.getByTestId('chat-files-chip-count')).toHaveTextContent('1');
- });
- expect(listArtifactsForThread).toHaveBeenCalledWith(THREAD);
- expect(store.getState().chatRuntime.artifactsByThread[THREAD]).toMatchObject([
- {
- artifactId: 'art-cold',
- kind: 'document',
- title: 'Cold Redux Report',
- status: 'ready',
- path: 'artifacts/art-cold/report.pdf',
- sizeBytes: 2048,
- },
- ]);
- });
-
- it('uses the normalized thread id for hydration and redux lookup', async () => {
- vi.mocked(listArtifactsForThread).mockResolvedValueOnce({
- ok: true,
- artifacts: [
- {
- artifactId: 'art-trimmed',
- kind: 'document',
- title: 'Trimmed Thread Report',
- path: 'artifacts/art-trimmed/report.pdf',
- sizeBytes: 4096,
- },
- ],
- });
- const store = mkStore();
- render(
- <Provider store={store}>
- <ChatFilesChip threadId={` ${THREAD} `} />
- </Provider>
- );
-
- await waitFor(() => {
- expect(screen.getByTestId('chat-files-chip-count')).toHaveTextContent('1');
- });
- expect(listArtifactsForThread).toHaveBeenCalledWith(THREAD);
- expect(store.getState().chatRuntime.artifactsByThread[THREAD]).toMatchObject([
- { artifactId: 'art-trimmed', status: 'ready', path: 'artifacts/art-trimmed/report.pdf' },
- ]);
- expect(store.getState().chatRuntime.artifactsByThread[` ${THREAD} `]).toBeUndefined();
- });
-
- it('keeps the chip hidden when disk hydration fails', async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
- vi.mocked(listArtifactsForThread).mockResolvedValueOnce({
- ok: false,
- artifacts: [],
- error: 'core offline',
- });
- const store = mkStore();
- const { container } = render(
- <Provider store={store}>
- <ChatFilesChip threadId={THREAD} />
- </Provider>
- );
-
- await waitFor(() => {
- expect(listArtifactsForThread).toHaveBeenCalledWith(THREAD);
- });
- expect(container.firstChild).toBeNull();
- expect(store.getState().chatRuntime.artifactsByThread[THREAD]).toBeUndefined();
- warn.mockRestore();
- });
-
- it('hides itself when only in_progress artifacts exist (those live above composer)', () => {
- const store = mkStore();
- store.dispatch(
- upsertArtifactInProgressForThread({
- threadId: THREAD,
- artifactId: 'in-flight',
- kind: 'presentation',
- title: 'In flight',
- })
- );
- render(
- <Provider store={store}>
- <ChatFilesChip threadId={THREAD} />
- </Provider>
- );
- expect(screen.queryByTestId('chat-files-chip')).toBeNull();
- });
-
- it('shows the chip + numeric count when the thread has ready artifacts', () => {
- const store = mkStore();
- store.dispatch(upsertArtifactReadyForThread({ threadId: THREAD, ...readyArtifact(1) }));
- store.dispatch(upsertArtifactReadyForThread({ threadId: THREAD, ...readyArtifact(2) }));
- store.dispatch(upsertArtifactReadyForThread({ threadId: THREAD, ...readyArtifact(3) }));
- render(
- <Provider store={store}>
- <ChatFilesChip threadId={THREAD} />
- </Provider>
- );
- expect(screen.getByTestId('chat-files-chip')).toBeInTheDocument();
- expect(screen.getByTestId('chat-files-chip-count')).toHaveTextContent('3');
- });
-
- it('renders the singular aria-label when exactly one ready artifact exists', () => {
- const store = mkStore();
- store.dispatch(upsertArtifactReadyForThread({ threadId: THREAD, ...readyArtifact(1) }));
- render(
- <Provider store={store}>
- <ChatFilesChip threadId={THREAD} />
- </Provider>
- );
- // Singular form — no trailing "s" on "file".
- expect(screen.getByTestId('chat-files-chip')).toHaveAttribute(
- 'aria-label',
- '1 file in this chat'
- );
- });
-
- it('renders the plural aria-label when the count is greater than one', () => {
- const store = mkStore();
- store.dispatch(upsertArtifactReadyForThread({ threadId: THREAD, ...readyArtifact(1) }));
- store.dispatch(upsertArtifactReadyForThread({ threadId: THREAD, ...readyArtifact(2) }));
- render(
- <Provider store={store}>
- <ChatFilesChip threadId={THREAD} />
- </Provider>
- );
- expect(screen.getByTestId('chat-files-chip')).toHaveAttribute(
- 'aria-label',
- '2 files in this chat'
- );
- });
-
- it('opens the panel on chip click and exposes per-row download/delete actions', () => {
- const store = mkStore();
- store.dispatch(upsertArtifactReadyForThread({ threadId: THREAD, ...readyArtifact(1) }));
- render(
- <Provider store={store}>
- <ChatFilesChip threadId={THREAD} />
- </Provider>
- );
- expect(screen.queryByTestId('chat-files-panel')).toBeNull();
- fireEvent.click(screen.getByTestId('chat-files-chip'));
- expect(screen.getByTestId('chat-files-panel')).toBeInTheDocument();
- expect(screen.getByTestId('chat-files-download-art-1')).toBeInTheDocument();
- expect(screen.getByTestId('chat-files-delete-art-1')).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/chat/__tests__/ChatFilesPanel.test.tsx b/app/src/components/chat/__tests__/ChatFilesPanel.test.tsx
deleted file mode 100644
index d4285d5677..0000000000
--- a/app/src/components/chat/__tests__/ChatFilesPanel.test.tsx
+++ /dev/null
@@ -1,436 +0,0 @@
-import { configureStore } from '@reduxjs/toolkit';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { Provider } from 'react-redux';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import {
- deleteArtifact,
- downloadArtifact,
- revealArtifact,
-} from '../../../services/artifactDownloadService';
-import chatRuntimeReducer, {
- type ArtifactSnapshot,
- upsertArtifactReadyForThread,
-} from '../../../store/chatRuntimeSlice';
-import ChatFilesPanel from '../ChatFilesPanel';
-
-vi.mock('../../../services/artifactDownloadService', () => ({
- downloadArtifact: vi.fn(),
- deleteArtifact: vi.fn(),
- revealArtifact: vi.fn(),
-}));
-
-const THREAD = 't-panel-1';
-
-function mkStore(artifactPayloads: Array<Parameters<typeof upsertArtifactReadyForThread>[0]>) {
- const store = configureStore({ reducer: { chatRuntime: chatRuntimeReducer } });
- for (const p of artifactPayloads) {
- store.dispatch(upsertArtifactReadyForThread(p));
- }
- return store;
-}
-
-function readyArtifact(id: string, title: string): ArtifactSnapshot {
- return {
- artifactId: id,
- kind: 'presentation',
- title,
- status: 'ready',
- path: `artifacts/${id}.pptx`,
- sizeBytes: 4096,
- updatedAt: Date.now(),
- };
-}
-
-describe('ChatFilesPanel', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it('renders an empty-state message when the panel is opened with no artifacts', () => {
- const store = mkStore([]);
- render(
- <Provider store={store}>
- <ChatFilesPanel threadId={THREAD} artifacts={[]} onClose={() => {}} />
- </Provider>
- );
- expect(screen.getByText('No files yet. Ask the agent to generate one.')).toBeInTheDocument();
- });
-
- it('lists rows + per-row actions when populated', () => {
- const a = readyArtifact('art-1', 'Climate Deck');
- const b = readyArtifact('art-2', 'Q2 Report');
- const store = mkStore([
- {
- threadId: THREAD,
- artifactId: a.artifactId,
- kind: a.kind,
- title: a.title,
- path: a.path!,
- sizeBytes: a.sizeBytes!,
- },
- {
- threadId: THREAD,
- artifactId: b.artifactId,
- kind: b.kind,
- title: b.title,
- path: b.path!,
- sizeBytes: b.sizeBytes!,
- },
- ]);
- render(
- <Provider store={store}>
- <ChatFilesPanel threadId={THREAD} artifacts={[a, b]} onClose={() => {}} />
- </Provider>
- );
- expect(screen.getByText('Climate Deck')).toBeInTheDocument();
- expect(screen.getByText('Q2 Report')).toBeInTheDocument();
- expect(screen.getByTestId('chat-files-download-art-1')).toBeInTheDocument();
- expect(screen.getByTestId('chat-files-delete-art-2')).toBeInTheDocument();
- });
-
- const renderOne = (a: ArtifactSnapshot) => {
- const store = mkStore([
- {
- threadId: THREAD,
- artifactId: a.artifactId,
- kind: a.kind,
- title: a.title,
- path: a.path!,
- sizeBytes: a.sizeBytes!,
- },
- ]);
- render(
- <Provider store={store}>
- <ChatFilesPanel threadId={THREAD} artifacts={[a]} onClose={() => {}} />
- </Provider>
- );
- };
-
- it('on Download click → calls downloadArtifact', async () => {
- vi.mocked(downloadArtifact).mockResolvedValueOnce({
- ok: true,
- path: '/Users/me/Downloads/Climate Deck.pptx',
- });
- renderOne(readyArtifact('art-1', 'Climate Deck'));
- fireEvent.click(screen.getByTestId('chat-files-download-art-1'));
- await waitFor(() =>
- expect(downloadArtifact).toHaveBeenCalledWith('art-1', 'Climate Deck', 'pptx')
- );
- });
-
- it('offers Show in folder on every ready file, without downloading first (#5505)', async () => {
- vi.mocked(revealArtifact).mockResolvedValueOnce({ ok: true });
- renderOne(readyArtifact('art-1', 'Climate Deck'));
-
- fireEvent.click(screen.getByTestId('chat-files-reveal-art-1'));
-
- await waitFor(() => expect(revealArtifact).toHaveBeenCalledWith('art-1'));
- expect(downloadArtifact).not.toHaveBeenCalled();
- expect(screen.queryByTestId('chat-files-reveal-error-art-1')).not.toBeInTheDocument();
- });
-
- it('says so when the file cannot be shown', async () => {
- vi.mocked(revealArtifact).mockResolvedValueOnce({
- ok: false,
- code: 'REVEAL_FAILED',
- error: 'raw detail',
- });
- renderOne(readyArtifact('art-1', 'Climate Deck'));
-
- fireEvent.click(screen.getByTestId('chat-files-reveal-art-1'));
-
- expect(await screen.findByTestId('chat-files-reveal-error-art-1')).toHaveTextContent(
- 'Couldn’t show the file. It may have been moved or deleted outside OpenHuman.'
- );
- });
-
- it('Delete → Cancel keeps the artifact and does NOT call the RPC', async () => {
- const a = readyArtifact('art-1', 'Climate Deck');
- const store = mkStore([
- {
- threadId: THREAD,
- artifactId: a.artifactId,
- kind: a.kind,
- title: a.title,
- path: a.path!,
- sizeBytes: a.sizeBytes!,
- },
- ]);
- render(
- <Provider store={store}>
- <ChatFilesPanel threadId={THREAD} artifacts={[a]} onClose={() => {}} />
- </Provider>
- );
- fireEvent.click(screen.getByTestId('chat-files-delete-art-1'));
- expect(screen.getByText('Delete this file?')).toBeInTheDocument();
- fireEvent.click(screen.getByText('Cancel'));
- expect(deleteArtifact).not.toHaveBeenCalled();
- expect(store.getState().chatRuntime.artifactsByThread[THREAD]).toHaveLength(1);
- });
-
- it('Delete → Confirm → RPC ok → row removed from slice', async () => {
- const a = readyArtifact('art-1', 'Climate Deck');
- vi.mocked(deleteArtifact).mockResolvedValueOnce({ ok: true });
- const store = mkStore([
- {
- threadId: THREAD,
- artifactId: a.artifactId,
- kind: a.kind,
- title: a.title,
- path: a.path!,
- sizeBytes: a.sizeBytes!,
- },
- ]);
- render(
- <Provider store={store}>
- <ChatFilesPanel threadId={THREAD} artifacts={[a]} onClose={() => {}} />
- </Provider>
- );
- fireEvent.click(screen.getByTestId('chat-files-delete-art-1'));
- fireEvent.click(screen.getByTestId('chat-files-confirm-art-1'));
- await waitFor(() => {
- expect(deleteArtifact).toHaveBeenCalledWith('art-1');
- });
- // Bucket should be empty (last row removed → key deleted in reducer).
- expect(store.getState().chatRuntime.artifactsByThread[THREAD]).toBeUndefined();
- });
-
- it('Delete → Confirm → RPC fails → row re-inserted + error surfaced', async () => {
- const a = readyArtifact('art-1', 'Climate Deck');
- vi.mocked(deleteArtifact).mockResolvedValueOnce({ ok: false, error: 'core dropped' });
- const store = mkStore([
- {
- threadId: THREAD,
- artifactId: a.artifactId,
- kind: a.kind,
- title: a.title,
- path: a.path!,
- sizeBytes: a.sizeBytes!,
- },
- ]);
- render(
- <Provider store={store}>
- <ChatFilesPanel threadId={THREAD} artifacts={[a]} onClose={() => {}} />
- </Provider>
- );
- fireEvent.click(screen.getByTestId('chat-files-delete-art-1'));
- fireEvent.click(screen.getByTestId('chat-files-confirm-art-1'));
- await waitFor(() => {
- expect(screen.getByText('core dropped')).toBeInTheDocument();
- });
- // Re-inserted: bucket still has the entry.
- expect(store.getState().chatRuntime.artifactsByThread[THREAD]).toHaveLength(1);
- expect(store.getState().chatRuntime.artifactsByThread[THREAD][0].artifactId).toBe('art-1');
- });
-
- it('Delete → typed code surfaces the localized headline, not the raw detail', async () => {
- const a = readyArtifact('art-1', 'Climate Deck');
- // Service returns the new shape: structured code + raw RPC string.
- // UI must prefer the localized headline mapped from `code`.
- vi.mocked(deleteArtifact).mockResolvedValueOnce({
- ok: false,
- code: 'DELETE_FAILED',
- error: 'rpc transport closed',
- });
- const store = mkStore([
- {
- threadId: THREAD,
- artifactId: a.artifactId,
- kind: a.kind,
- title: a.title,
- path: a.path!,
- sizeBytes: a.sizeBytes!,
- },
- ]);
- render(
- <Provider store={store}>
- <ChatFilesPanel threadId={THREAD} artifacts={[a]} onClose={() => {}} />
- </Provider>
- );
- fireEvent.click(screen.getByTestId('chat-files-delete-art-1'));
- fireEvent.click(screen.getByTestId('chat-files-confirm-art-1'));
- await waitFor(() => {
- // Localized headline from chat.files.error.delete_failed (en).
- expect(screen.getByText('Couldn’t delete the file. Please try again.')).toBeInTheDocument();
- });
- // Raw detail MUST NOT leak into the user-facing surface.
- expect(screen.queryByText('rpc transport closed')).toBeNull();
- });
-
- it('passes the title-derived extension to downloadArtifact when title carries one', async () => {
- const a = readyArtifact('art-1', 'climate-deck.pptx');
- vi.mocked(downloadArtifact).mockResolvedValueOnce({ ok: true, path: '/d/x.pptx' });
- const store = mkStore([
- {
- threadId: THREAD,
- artifactId: a.artifactId,
- kind: a.kind,
- title: a.title,
- path: a.path!,
- sizeBytes: a.sizeBytes!,
- },
- ]);
- render(
- <Provider store={store}>
- <ChatFilesPanel threadId={THREAD} artifacts={[a]} onClose={() => {}} />
- </Provider>
- );
- fireEvent.click(screen.getByTestId('chat-files-download-art-1'));
- await waitFor(() => {
- expect(downloadArtifact).toHaveBeenCalledWith('art-1', 'climate-deck.pptx', 'pptx');
- });
- });
-
- it.each([
- ['document' as const, 'docx'],
- ['image' as const, 'png'],
- ['other' as const, 'bin'],
- ])(
- 'falls back to the per-kind extension default when the title has none (kind=%s → ext=%s)',
- async (kind, expectedExt) => {
- const a: ArtifactSnapshot = {
- artifactId: 'art-1',
- kind,
- title: 'no-extension-title',
- status: 'ready',
- path: 'artifacts/x',
- sizeBytes: 1024,
- updatedAt: Date.now(),
- };
- vi.mocked(downloadArtifact).mockResolvedValueOnce({ ok: true, path: '/d/x' });
- const store = mkStore([
- {
- threadId: THREAD,
- artifactId: a.artifactId,
- kind: a.kind,
- title: a.title,
- path: a.path!,
- sizeBytes: a.sizeBytes!,
- },
- ]);
- render(
- <Provider store={store}>
- <ChatFilesPanel threadId={THREAD} artifacts={[a]} onClose={() => {}} />
- </Provider>
- );
- fireEvent.click(screen.getByTestId('chat-files-download-art-1'));
- await waitFor(() => {
- expect(downloadArtifact).toHaveBeenCalledWith('art-1', 'no-extension-title', expectedExt);
- });
- }
- );
-
- it('Esc closes the panel via the keydown handler', async () => {
- const a = readyArtifact('art-1', 'Climate Deck');
- const onClose = vi.fn();
- const store = mkStore([
- {
- threadId: THREAD,
- artifactId: a.artifactId,
- kind: a.kind,
- title: a.title,
- path: a.path!,
- sizeBytes: a.sizeBytes!,
- },
- ]);
- render(
- <Provider store={store}>
- <ChatFilesPanel threadId={THREAD} artifacts={[a]} onClose={onClose} />
- </Provider>
- );
- fireEvent.keyDown(window, { key: 'Escape' });
- expect(onClose).toHaveBeenCalledTimes(1);
- });
-
- it('Esc while a row is in confirm-delete mode dismisses the confirm, NOT the panel', async () => {
- const a = readyArtifact('art-1', 'Climate Deck');
- const onClose = vi.fn();
- const store = mkStore([
- {
- threadId: THREAD,
- artifactId: a.artifactId,
- kind: a.kind,
- title: a.title,
- path: a.path!,
- sizeBytes: a.sizeBytes!,
- },
- ]);
- render(
- <Provider store={store}>
- <ChatFilesPanel threadId={THREAD} artifacts={[a]} onClose={onClose} />
- </Provider>
- );
- fireEvent.click(screen.getByTestId('chat-files-delete-art-1'));
- expect(screen.getByText('Delete this file?')).toBeInTheDocument();
- fireEvent.keyDown(window, { key: 'Escape' });
- expect(onClose).not.toHaveBeenCalled();
- expect(screen.queryByText('Delete this file?')).toBeNull();
- });
-
- it('pointerdown outside the panel closes it (click-outside)', () => {
- const a = readyArtifact('art-1', 'Climate Deck');
- const onClose = vi.fn();
- const store = mkStore([
- {
- threadId: THREAD,
- artifactId: a.artifactId,
- kind: a.kind,
- title: a.title,
- path: a.path!,
- sizeBytes: a.sizeBytes!,
- },
- ]);
- render(
- <Provider store={store}>
- <ChatFilesPanel threadId={THREAD} artifacts={[a]} onClose={onClose} />
- </Provider>
- );
- // Fire a pointerdown event whose target is outside the panel.
- const outside = document.createElement('div');
- document.body.appendChild(outside);
- const evt = new PointerEvent('pointerdown', { bubbles: true });
- Object.defineProperty(evt, 'target', { value: outside });
- document.dispatchEvent(evt);
- expect(onClose).toHaveBeenCalledTimes(1);
- });
-
- it('Download → typed code surfaces the localized headline in the row error', async () => {
- const a = readyArtifact('art-1', 'Climate Deck');
- // Use a deliberately distinct raw `error` so this test only passes when
- // the UI renders the localized copy keyed off `code`, not the raw
- // backend detail. If the row ever regressed to echoing `error` verbatim,
- // the `queryByText(rawError)` assertion below would catch it.
- const rawError = 'transport socket closed mid-resolve';
- vi.mocked(downloadArtifact).mockResolvedValueOnce({
- ok: false,
- code: 'NOT_DESKTOP',
- error: rawError,
- });
- const store = mkStore([
- {
- threadId: THREAD,
- artifactId: a.artifactId,
- kind: a.kind,
- title: a.title,
- path: a.path!,
- sizeBytes: a.sizeBytes!,
- },
- ]);
- render(
- <Provider store={store}>
- <ChatFilesPanel threadId={THREAD} artifacts={[a]} onClose={() => {}} />
- </Provider>
- );
- fireEvent.click(screen.getByTestId('chat-files-download-art-1'));
- await waitFor(() => {
- // The download_failed copy is wrapped by the chat.artifact.download_failed
- // template (`{reason}`), which renders the localized inner text.
- expect(
- screen.getByText(/Downloads are only available in the desktop app/)
- ).toBeInTheDocument();
- });
- // Raw backend detail must NOT leak into the rendered row.
- expect(screen.queryByText(rawError)).toBeNull();
- });
-});
diff --git a/app/src/components/chat/artifactExtension.ts b/app/src/components/chat/artifactExtension.ts
index 79a5461335..33c773fa97 100644
--- a/app/src/components/chat/artifactExtension.ts
+++ b/app/src/components/chat/artifactExtension.ts
@@ -8,10 +8,8 @@ import type { ArtifactSnapshot } from '../../store/chatRuntimeSlice';
* separately, but a malformed title shouldn't crash the card), otherwise
* falls back to a per-kind default.
*
- * Shared by {@link ArtifactCard} and {@link ChatFilesPanel}, which both
- * derive the download filename extension from `(kind, title)` and must
- * stay in lockstep — hence a single source of truth rather than two
- * hand-kept copies.
+ * Used by {@link ArtifactCard} to derive the download filename extension
+ * from `(kind, title)`.
*
* `document` → `docx`: the document artifact producer (`generate_document`,
* GH #4847) emits a real Word `.docx`. The prior `pdf` default predated any
diff --git a/app/src/components/layout/shell/WindowDragBar.tsx b/app/src/components/layout/shell/WindowDragBar.tsx
index c3b7747a73..5231684bd7 100644
--- a/app/src/components/layout/shell/WindowDragBar.tsx
+++ b/app/src/components/layout/shell/WindowDragBar.tsx
@@ -36,8 +36,17 @@ const GLOBAL_DRAG_BAR_LEFT = SIDEBAR_MAX_WIDTH + 8;
* Windows uses the same drag band with room left for its custom controls.
* Linux keeps its native decorated title bar. Outside Tauri it renders nothing.
*/
+/**
+ * Whether the drag band is drawn on this platform. Content whose controls sit
+ * at the top of the window (like the artifact panel header) must clear
+ * `WINDOW_DRAG_BAR_HEIGHT` when this is true, or the band eats their clicks.
+ */
+export function hasWindowDragBar(): boolean {
+ return isTauri() && (isMac() || isWindowsDesktop());
+}
+
export default function WindowDragBar() {
- if (!isTauri() || (!isMac() && !isWindowsDesktop())) return null;
+ if (!hasWindowDragBar()) return null;
const windows = isWindowsDesktop();
return (
<div
diff --git a/app/src/features/conversations/Conversations.tsx b/app/src/features/conversations/Conversations.tsx
index 514bea33e0..17279423a2 100644
--- a/app/src/features/conversations/Conversations.tsx
+++ b/app/src/features/conversations/Conversations.tsx
@@ -6,7 +6,6 @@ import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { type ChatSendError, chatSendError } from '../../chat/chatSendError';
import { checkPromptInjection, promptGuardMessage } from '../../chat/promptInjectionGuard';
import { trackAnalyticsEvent } from '../../components/analytics';
-import ChatFilesChip from '../../components/chat/ChatFilesChip';
import WorkflowProposalCard from '../../components/chat/WorkflowProposalCard';
import { ConfirmationModal } from '../../components/intelligence/ConfirmationModal';
import { SidebarContent } from '../../components/layout/shell/SidebarSlot';
@@ -110,6 +109,7 @@ import {
import { StallWarning } from './aui/StallWarning';
import { ThreadWorkspaceChip } from './aui/ThreadWorkspaceChip';
import { useChatSurfaceRegistration } from './hooks/useChatSurfaceRegistration';
+import { useThreadArtifactsHydration } from './hooks/useThreadArtifactsHydration';
import { useThreadDraft } from './hooks/useThreadDraft';
import { ThreadList } from './threadList/ThreadList';
import { useThreadPins } from './threadList/useThreadPins';
@@ -2144,9 +2144,7 @@ const Conversations = ({
// Surface in-flight + failed artifact cards above the composer (#2779).
// Mirrors the approval-card placement so the user sees the spinner / error
- // without scrolling. `ready` cards are delegated to the header ChatFilesChip
- // panel (#3024) so the chat scroll area isn't permanently occupied —
- // restored decks are listable from the chip on demand.
+ // without scrolling.
//
// The failed-card Retry button re-dispatches the producing tool via
// `ai_regenerate` (#3162): the core reloads the persisted creation args and
@@ -2156,18 +2154,14 @@ const Conversations = ({
// Only artifacts with NO owning tool call belong in the header deck — one
// with a `toolCallId` renders inline through its own tool-call card
// (`MediaAndDocumentCalls.tsx`) instead, per the `ArtifactCardAdapter` doc.
- // We ALSO keep ready artifacts visible as clickable cards (not just the
- // ChatFilesChip count) so the user can open live artifact previews.
const liveArtifacts = artifactDeckThreadId
? (artifactsByThread[artifactDeckThreadId] ?? []).filter(
a =>
- // Cards with a producing turn now render inline inside that
- // message (MessageArtifactCards); only artifacts without an
- // owning requestId (older cores / persisted snapshots) fall
- // back to the end-of-transcript deck.
- !a.ownerRequestId &&
- !a.toolCallId &&
- (a.status === 'in_progress' || a.status === 'ready')
+ // Ready artifacts render inside their turn's reply, placed by the
+ // core's artifact rows (`MessageArtifactCards`); so does an
+ // in-progress one whose event names its turn. Only an in-progress
+ // artifact with no turn (an older core) waits at the end.
+ !a.ownerRequestId && !a.toolCallId && a.status === 'in_progress'
)
: [];
const liveArtifactDeck =
@@ -2188,10 +2182,7 @@ const Conversations = ({
</div>
) : null;
- const chatFilesChip =
- (selectedThreadId ?? firstActiveThreadId) ? (
- <ChatFilesChip threadId={(selectedThreadId ?? firstActiveThreadId) as string} />
- ) : null;
+ useThreadArtifactsHydration(selectedThreadId ?? firstActiveThreadId);
const assistantComposerHeader = (
<div
@@ -2241,7 +2232,6 @@ const Conversations = ({
onChange={applyComposerReasoningEffort}
modelLabel={reasoningModel}
/>
- {chatFilesChip}
</>
);
@@ -2404,10 +2394,7 @@ const Conversations = ({
</SidebarContent>
<div className="flex h-full w-full min-w-0">
{mainPanel}
- {activeArtifactId && (
- <ArtifactPreviewPanel
- />
- )}
+ {activeArtifactId && <ArtifactPreviewPanel />}
</div>
</>
)}
diff --git a/app/src/features/conversations/aui/ArtifactCardAdapter.tsx b/app/src/features/conversations/aui/ArtifactCardAdapter.tsx
index fc1fad7a5c..963f6eecc6 100644
--- a/app/src/features/conversations/aui/ArtifactCardAdapter.tsx
+++ b/app/src/features/conversations/aui/ArtifactCardAdapter.tsx
@@ -8,8 +8,7 @@
* Only artifacts with NO owning tool call (`ArtifactSnapshot.toolCallId`
* absent) reach this deck — `Conversations.tsx`'s `liveArtifactDeck` filters
* those out; an artifact with a `toolCallId` renders inline through its own
- * tool-call card instead (`MediaAndDocumentCalls.tsx`). A `ready` artifact
- * never reaches either: it moves to `ChatFilesChip` (unchanged).
+ * tool-call card instead (`MediaAndDocumentCalls.tsx`).
*
* The vendored card has no built-in failed/retry state (it only knows
* "writing" vs. "settled"), so the failed case renders the settled meta line
@@ -41,7 +40,11 @@ export interface ArtifactCardAdapterProps {
onOpenPreview?: (artifactId: string) => void;
}
-export function ArtifactCardAdapter({ artifact, onRetry, onOpenPreview }: ArtifactCardAdapterProps) {
+export function ArtifactCardAdapter({
+ artifact,
+ onRetry,
+ onOpenPreview,
+}: ArtifactCardAdapterProps) {
const { t } = useT();
const generating = artifact.status === 'in_progress';
const isReady = artifact.status === 'ready';
@@ -72,8 +75,7 @@ export function ArtifactCardAdapter({ artifact, onRetry, onOpenPreview }: Artifa
onClick={handleClick}
onKeyDown={isReady && onOpenPreview ? handleKeyDown : undefined}
className={'flex flex-col items-start gap-1.5' + (isReady ? ' cursor-pointer' : '')}
- data-testid="artifact-card-adapter"
- >
+ data-testid="artifact-card-adapter">
<ArtifactCard
title={artifact.title}
meta={meta}
diff --git a/app/src/features/conversations/aui/ArtifactPreviewPanel.autosave.test.tsx b/app/src/features/conversations/aui/ArtifactPreviewPanel.autosave.test.tsx
new file mode 100644
index 0000000000..30a8498e88
--- /dev/null
+++ b/app/src/features/conversations/aui/ArtifactPreviewPanel.autosave.test.tsx
@@ -0,0 +1,68 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { callCoreRpc } from '../../../services/coreRpcClient';
+import { AUTOSAVE_DELAY_MS, useArtifactAutosave } from './ArtifactPreviewPanel';
+
+vi.mock('../../../services/coreRpcClient', () => ({
+ callCoreRpc: vi.fn().mockResolvedValue({ artifact_id: 'a-1', version: 2, saved: true }),
+}));
+vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn() }));
+vi.mock('../../../lib/i18n/I18nContext', () => ({
+ useT: () => ({ t: (k: string) => k, locale: 'en' }),
+}));
+
+const rpc = vi.mocked(callCoreRpc);
+
+describe('useArtifactAutosave', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ rpc.mockClear();
+ });
+ afterEach(() => vi.useRealTimers());
+
+ it('saves once, 5 s after the last edit', async () => {
+ const { result } = renderHook(() => useArtifactAutosave('a-1', '# v1', 1, true));
+
+ act(() => result.current.schedule('# v1 a'));
+ await act(async () => vi.advanceTimersByTime(AUTOSAVE_DELAY_MS - 1_000));
+ // Typing again restarts the wait.
+ act(() => result.current.schedule('# v1 ab'));
+ await act(async () => vi.advanceTimersByTime(AUTOSAVE_DELAY_MS - 1));
+ expect(rpc).not.toHaveBeenCalled();
+ expect(result.current.status).toBe('pending');
+
+ await act(async () => vi.advanceTimersByTime(1));
+ expect(rpc).toHaveBeenCalledTimes(1);
+ expect(rpc).toHaveBeenCalledWith({
+ method: 'openhuman.ai_save_artifact_version',
+ params: { artifact_id: 'a-1', body: '# v1 ab' },
+ });
+ expect(result.current.version).toBe(2);
+ expect(result.current.status).toBe('saved');
+ });
+
+ it('flush saves a pending edit at once (before a download)', async () => {
+ const { result } = renderHook(() => useArtifactAutosave('a-1', '# v1', 1, true));
+ act(() => result.current.schedule('# edited'));
+ await act(async () => result.current.flush());
+ expect(rpc).toHaveBeenCalledTimes(1);
+ // Nothing left to save when the timer would have fired.
+ await act(async () => vi.advanceTimersByTime(AUTOSAVE_DELAY_MS));
+ expect(rpc).toHaveBeenCalledTimes(1);
+ });
+
+ it('saves a pending edit when the panel closes', async () => {
+ const { result, unmount } = renderHook(() => useArtifactAutosave('a-1', '# v1', 1, true));
+ act(() => result.current.schedule('# edited'));
+ await act(async () => unmount());
+ expect(rpc).toHaveBeenCalledTimes(1);
+ });
+
+ it('never saves a read-only artifact', async () => {
+ const { result } = renderHook(() => useArtifactAutosave('a-1', 'text', 1, false));
+ act(() => result.current.schedule('changed'));
+ await act(async () => vi.advanceTimersByTime(AUTOSAVE_DELAY_MS * 2));
+ expect(rpc).not.toHaveBeenCalled();
+ });
+});
diff --git a/app/src/features/conversations/aui/ArtifactPreviewPanel.dragBar.test.tsx b/app/src/features/conversations/aui/ArtifactPreviewPanel.dragBar.test.tsx
new file mode 100644
index 0000000000..ed11d2144d
--- /dev/null
+++ b/app/src/features/conversations/aui/ArtifactPreviewPanel.dragBar.test.tsx
@@ -0,0 +1,54 @@
+import { configureStore } from '@reduxjs/toolkit';
+import { render } from '@testing-library/react';
+import { Provider } from 'react-redux';
+import { describe, expect, it, vi } from 'vitest';
+
+import chatRuntimeReducer, {
+ openArtifact,
+ upsertArtifactReadyForThread,
+} from '../../../store/chatRuntimeSlice';
+import { ArtifactPreviewPanel } from './ArtifactPreviewPanel';
+
+const dragBar = vi.hoisted(() => ({ shown: false }));
+
+vi.mock('../../../components/layout/shell/WindowDragBar', () => ({
+ WINDOW_DRAG_BAR_HEIGHT: 32,
+ hasWindowDragBar: () => dragBar.shown,
+}));
+
+vi.mock('../../../lib/i18n/I18nContext', () => ({
+ useT: () => ({ t: (k: string) => k, locale: 'en' }),
+}));
+
+function renderPanel() {
+ const store = configureStore({ reducer: { chatRuntime: chatRuntimeReducer } });
+ store.dispatch(
+ upsertArtifactReadyForThread({
+ threadId: 't-1',
+ artifactId: 'a-1',
+ kind: 'document',
+ title: 'Doc One',
+ path: '/tmp/a-1.md',
+ sizeBytes: 12,
+ })
+ );
+ store.dispatch(openArtifact('a-1'));
+ const { container } = render(
+ <Provider store={store}>
+ <ArtifactPreviewPanel />
+ </Provider>
+ );
+ return container.firstElementChild as HTMLElement;
+}
+
+describe('ArtifactPreviewPanel under the window-drag band', () => {
+ it('pushes the header below the band when the band is drawn', () => {
+ dragBar.shown = true;
+ expect(renderPanel().style.paddingTop).toBe('32px');
+ });
+
+ it('adds no padding where there is no band', () => {
+ dragBar.shown = false;
+ expect(renderPanel().style.paddingTop).toBe('');
+ });
+});
diff --git a/app/src/features/conversations/aui/ArtifactPreviewPanel.markdown.test.tsx b/app/src/features/conversations/aui/ArtifactPreviewPanel.markdown.test.tsx
new file mode 100644
index 0000000000..4d9aada8cc
--- /dev/null
+++ b/app/src/features/conversations/aui/ArtifactPreviewPanel.markdown.test.tsx
@@ -0,0 +1,83 @@
+import { configureStore } from '@reduxjs/toolkit';
+import { invoke } from '@tauri-apps/api/core';
+import { render, screen } from '@testing-library/react';
+import { Provider } from 'react-redux';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import chatRuntimeReducer, {
+ openArtifact,
+ upsertArtifactReadyForThread,
+} from '../../../store/chatRuntimeSlice';
+import { ArtifactPreviewPanel } from './ArtifactPreviewPanel';
+
+vi.mock('../../../lib/i18n/I18nContext', () => ({
+ useT: () => ({ t: (k: string) => k, locale: 'en' }),
+}));
+
+const MD = '# Hello\n\nThis is **bold** text.\n';
+
+function renderPanel(kind: string, body: string) {
+ // Stub the body fetch BEFORE mounting so the panel's effect resolves it.
+ vi.mocked(invoke).mockResolvedValue({ kind, title: 'Notes', version: 1, body, is_text: true });
+ const store = configureStore({ reducer: { chatRuntime: chatRuntimeReducer } });
+ store.dispatch(
+ upsertArtifactReadyForThread({
+ threadId: 't-1',
+ artifactId: 'a-1',
+ kind: 'document',
+ title: 'Notes',
+ path: '/tmp/n.md',
+ sizeBytes: body.length,
+ })
+ );
+ store.dispatch(openArtifact('a-1'));
+ render(
+ <Provider store={store}>
+ <ArtifactPreviewPanel />
+ </Provider>
+ );
+}
+
+describe('ArtifactPreviewPanel — preview rendering by kind (#1535)', () => {
+ beforeEach(() => {
+ vi.mocked(invoke).mockReset();
+ });
+
+ it('renders markdown as formatted content, not raw source', async () => {
+ renderPanel('markdown', MD);
+
+ const h1 = await screen.findByRole('heading', { level: 1 });
+ expect(h1.textContent).toBe('Hello');
+
+ // **bold** becomes <strong>, not literal asterisks
+ expect(screen.getByText('bold').tagName).toBe('STRONG');
+
+ // The raw markdown source must NOT be shown verbatim.
+ expect(screen.queryByText(/# Hello/)).toBeNull();
+ });
+
+ it('renders GFM constructs (tables) via remark-gfm', async () => {
+ renderPanel('markdown', '| a | b |\n| --- | --- |\n| one | two |\n');
+
+ const table = await screen.findByRole('table');
+ expect(table).toBeTruthy();
+ expect(screen.getByText('one')).toBeTruthy();
+ });
+
+ it('keeps rendering HTML kind in the sandboxed iframe (unchanged)', async () => {
+ renderPanel('html', '<h1>Hi</h1><p>body</p>');
+
+ const frame = await screen.findByTitle('HTML preview');
+ expect(frame.tagName).toBe('IFRAME');
+ expect(frame.getAttribute('sandbox')).toBe('allow-scripts allow-same-origin');
+ expect(frame.getAttribute('srcdoc')).toContain('<h1>Hi</h1>');
+ });
+
+ it('still renders plain text kind as raw preformatted source', async () => {
+ renderPanel('text', 'plain **not** markdown\n');
+
+ const pre = await screen.findByText(/plain \*\*not\*\* markdown/);
+ expect(pre.tagName).toBe('PRE');
+ expect(screen.queryByRole('heading')).toBeNull();
+ });
+});
diff --git a/app/src/features/conversations/aui/ArtifactPreviewPanel.share.test.tsx b/app/src/features/conversations/aui/ArtifactPreviewPanel.share.test.tsx
new file mode 100644
index 0000000000..a17cc1e2f9
--- /dev/null
+++ b/app/src/features/conversations/aui/ArtifactPreviewPanel.share.test.tsx
@@ -0,0 +1,113 @@
+import { act, fireEvent, render, renderHook, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { callCoreRpc } from '../../../services/coreRpcClient';
+import { ShareStatus, useArtifactShare } from './ArtifactPreviewPanel';
+
+vi.mock('../../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
+vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn() }));
+vi.mock('../../../lib/i18n/I18nContext', () => ({
+ useT: () => ({ t: (k: string) => k, locale: 'en' }),
+}));
+
+const rpc = vi.mocked(callCoreRpc);
+const writeText = vi.fn().mockResolvedValue(undefined);
+
+describe('useArtifactShare', () => {
+ beforeEach(() => {
+ rpc.mockReset();
+ writeText.mockClear();
+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
+ });
+
+ it('saves a pending edit, uploads, then copies and shows the link', async () => {
+ const order: string[] = [];
+ const flush = vi.fn(async () => {
+ order.push('flush');
+ });
+ rpc.mockImplementation(async () => {
+ order.push('share');
+ return {
+ url: 'https://s3.example/presigned?sig=abc',
+ version: 3,
+ public: false,
+ expires_at_millis: 1_894_060_800_000,
+ reused: false,
+ };
+ });
+ const { result } = renderHook(() => useArtifactShare('a-1', flush));
+
+ await act(async () => result.current.share());
+
+ expect(order).toEqual(['flush', 'share']);
+ expect(rpc).toHaveBeenCalledWith({
+ method: 'openhuman.ai_share_artifact',
+ params: { artifact_id: 'a-1' },
+ });
+ expect(writeText).toHaveBeenCalledWith('https://s3.example/presigned?sig=abc');
+ expect(result.current.state).toMatchObject({
+ status: 'shared',
+ url: 'https://s3.example/presigned?sig=abc',
+ version: 3,
+ copied: true,
+ });
+ });
+
+ it('shows why sharing failed (e.g. signed out)', async () => {
+ rpc.mockRejectedValue(new Error('sign in to share artifacts'));
+ const { result } = renderHook(() => useArtifactShare('a-1'));
+ await act(async () => result.current.share());
+ expect(result.current.state).toEqual({
+ status: 'error',
+ message: 'sign in to share artifacts',
+ });
+ expect(writeText).not.toHaveBeenCalled();
+ });
+
+ it('still shows the link when the clipboard is refused', async () => {
+ writeText.mockRejectedValueOnce(new Error('denied'));
+ rpc.mockResolvedValue({ url: 'https://x', version: 1, public: true, reused: true });
+ const { result } = renderHook(() => useArtifactShare('a-1'));
+ await act(async () => result.current.share());
+ expect(result.current.state).toMatchObject({
+ status: 'shared',
+ copied: false,
+ expiresAt: null,
+ });
+
+ await act(async () => result.current.copyAgain());
+ expect(result.current.state).toMatchObject({ copied: true });
+ });
+});
+
+describe('ShareStatus copy button', () => {
+ beforeEach(() => {
+ rpc.mockReset();
+ writeText.mockClear();
+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
+ });
+
+ it('copies the full link, query string included', async () => {
+ const url =
+ 'https://s3.example/f?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=c&X-Amz-Signature=s';
+ rpc.mockResolvedValue({ url, version: 2, public: false, reused: false });
+ function Harness() {
+ const sharing = useArtifactShare('a-1');
+ return (
+ <>
+ <button onClick={() => void sharing.share()}>share</button>
+ <ShareStatus state={sharing.state} onCopy={sharing.copyAgain} />
+ </>
+ );
+ }
+ render(<Harness />);
+ await act(async () => fireEvent.click(screen.getByText('share')));
+ // The share copied the link already; the button still offers to copy.
+ expect(screen.getByTestId('artifact-share-copy').textContent).toBe('Copy');
+ writeText.mockClear();
+
+ await act(async () => fireEvent.click(screen.getByTestId('artifact-share-copy')));
+ expect(writeText).toHaveBeenCalledWith(url);
+ expect(screen.getByTestId('artifact-share-copy').textContent).toContain('Copied');
+ });
+});
diff --git a/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx b/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx
index 6f70164b04..ffeeb24f28 100644
--- a/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx
+++ b/app/src/features/conversations/aui/ArtifactPreviewPanel.tsx
@@ -1,29 +1,24 @@
'use client';
-import {
- Check,
- Clipboard,
- Code2,
- Download,
- Eye,
- FileBox,
- FileText,
- Save,
- X,
-} from 'lucide-react';
-import {
- useCallback,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from 'react';
+import { invoke } from '@tauri-apps/api/core';
+import { Check, Clipboard, Code2, Download, Eye, FileBox, FileText, Share2, X } from 'lucide-react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import Markdown from 'react-markdown';
+import remarkGfm from 'remark-gfm';
+import {
+ hasWindowDragBar,
+ WINDOW_DRAG_BAR_HEIGHT,
+} from '../../../components/layout/shell/WindowDragBar';
import { useT } from '../../../lib/i18n/I18nContext';
-import { useAppDispatch, useAppSelector } from '../../../store/hooks';
+import { callCoreRpc } from '../../../services/coreRpcClient';
import type { ArtifactSnapshot } from '../../../store/chatRuntimeSlice';
-import { activateArtifactTab, closeArtifactTab } from '../../../store/chatRuntimeSlice';
-import { invoke } from '@tauri-apps/api/core';
+import {
+ activateArtifactTab,
+ closeArtifactPanel,
+ closeArtifactTab,
+} from '../../../store/chatRuntimeSlice';
+import { useAppDispatch, useAppSelector } from '../../../store/hooks';
// ─── Types ──────────────────────────────────────────────────────
@@ -72,18 +67,21 @@ export function ArtifactPreviewPanel(_props: ArtifactPreviewPanelProps) {
const activeId = useAppSelector(s => s.chatRuntime.activeArtifactId);
const activeArtifact = useMemo(
() => allArtifacts.find(a => a.artifactId === activeId),
- [allArtifacts, activeId],
+ [allArtifacts, activeId]
);
// ── Resize ──
- const handleMouseDown = useCallback((e: React.MouseEvent) => {
- e.preventDefault();
- dragRef.current = true;
- startXRef.current = e.clientX;
- startWidthRef.current = panelWidth;
- document.body.style.cursor = 'ew-resize';
- document.body.style.userSelect = 'none';
- }, [panelWidth]);
+ const handleMouseDown = useCallback(
+ (e: React.MouseEvent) => {
+ e.preventDefault();
+ dragRef.current = true;
+ startXRef.current = e.clientX;
+ startWidthRef.current = panelWidth;
+ document.body.style.cursor = 'ew-resize';
+ document.body.style.userSelect = 'none';
+ },
+ [panelWidth]
+ );
useEffect(() => {
const onMove = (e: MouseEvent) => {
@@ -99,7 +97,10 @@ export function ArtifactPreviewPanel(_props: ArtifactPreviewPanelProps) {
};
window.addEventListener('mousemove', onMove);
window.addEventListener('mouseup', onUp);
- return () => { window.removeEventListener('mousemove', onMove); window.removeEventListener('mouseup', onUp); };
+ return () => {
+ window.removeEventListener('mousemove', onMove);
+ window.removeEventListener('mouseup', onUp);
+ };
}, []);
// Tabs = the artifacts currently open in the panel, in open order.
@@ -108,13 +109,13 @@ export function ArtifactPreviewPanel(_props: ArtifactPreviewPanelProps) {
openArtifactIds
.map(id => allArtifacts.find(a => a.artifactId === id))
.filter((a): a is ArtifactSnapshot => a !== undefined),
- [openArtifactIds, allArtifacts],
+ [openArtifactIds, allArtifacts]
);
const handleCloseTab = useCallback(
(id: string) => {
dispatch(closeArtifactTab(id));
},
- [dispatch],
+ [dispatch]
);
const showTabs = visibleTabs.length > 1;
@@ -122,8 +123,14 @@ export function ArtifactPreviewPanel(_props: ArtifactPreviewPanelProps) {
return (
<div
className="relative flex flex-col border-l bg-background shadow-xl h-full"
- style={{ width: panelWidth, minWidth: MIN_WIDTH, maxWidth: MAX_WIDTH }}
- >
+ style={{
+ width: panelWidth,
+ minWidth: MIN_WIDTH,
+ maxWidth: MAX_WIDTH,
+ // The panel header is at the top of the window, under the window-drag
+ // band, which would otherwise swallow clicks on the tabs and the X.
+ paddingTop: hasWindowDragBar() ? WINDOW_DRAG_BAR_HEIGHT : undefined,
+ }}>
{/* Drag handle */}
<div
className="absolute left-0 top-0 bottom-0 w-1.5 cursor-ew-resize hover:bg-primary/20 active:bg-primary/30 z-20"
@@ -138,27 +145,25 @@ export function ArtifactPreviewPanel(_props: ArtifactPreviewPanelProps) {
<div
key={a.artifactId}
className={`group flex items-center gap-1 border-b-2 px-2 py-2.5 transition-colors shrink-0 min-w-0 ${
- a.artifactId === activeId
- ? 'border-primary'
- : 'border-transparent'
- }`}
- >
+ a.artifactId === activeId ? 'border-primary' : 'border-transparent'
+ }`}>
<button
onClick={() => dispatch(activateArtifactTab(a.artifactId))}
className={`flex min-w-0 items-center gap-1.5 text-xs font-medium transition-colors ${
a.artifactId === activeId
? 'text-foreground'
: 'text-muted-foreground hover:text-foreground'
- }`}
- >
+ }`}>
<FileText className="h-3.5 w-3.5 shrink-0" />
<span className="truncate max-w-[110px]">{a.title}</span>
</button>
<button
- onClick={(e) => { e.stopPropagation(); handleCloseTab(a.artifactId); }}
+ onClick={e => {
+ e.stopPropagation();
+ handleCloseTab(a.artifactId);
+ }}
className="ml-0.5 rounded p-0.5 text-muted-foreground/50 hover:bg-accent hover:text-foreground shrink-0"
- title="Close artifact"
- >
+ title="Close artifact">
<X className="h-3 w-3" />
</button>
</div>
@@ -172,7 +177,10 @@ export function ArtifactPreviewPanel(_props: ArtifactPreviewPanelProps) {
</div>
)}
</div>
- <button onClick={() => dispatch(closeArtifactTab(activeId as string))} className="mr-2 shrink-0 inline-flex items-center justify-center rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground">
+ <button
+ onClick={() => dispatch(closeArtifactPanel())}
+ title="Close panel"
+ className="mr-2 shrink-0 inline-flex items-center justify-center rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground">
<X className="h-4 w-4" />
</button>
</div>
@@ -226,7 +234,9 @@ function ArtifactContentPanel({ artifact }: { artifact: ArtifactSnapshot }) {
};
fetchBody();
- return () => { cancelled = true; };
+ return () => {
+ cancelled = true;
+ };
}, [artifact.artifactId]);
if (loading) {
@@ -286,16 +296,22 @@ function FileViewer({
}) {
const filePath = body || artifact.path || '';
const fileName = filePath.split('/').pop() || filePath;
+ // Share is hidden until the backend serves viewable files inline (links download today); see useArtifactShare.
+ // const sharing = useArtifactShare(artifact.artifactId);
return (
<div className="flex flex-col h-full">
<div className="flex items-center justify-between border-b px-3 py-1.5 shrink-0 bg-muted/10">
<div className="flex items-center gap-2">
<FileBox className="h-4 w-4 text-muted-foreground" />
- <span className="text-xs font-medium text-muted-foreground capitalize">{artifact.kind}</span>
+ <span className="text-xs font-medium text-muted-foreground capitalize">
+ {artifact.kind}
+ </span>
<span className="text-[11px] text-muted-foreground/60 border-l pl-2">v{version}</span>
</div>
+ {/* <ShareButton state={sharing.state} onShare={() => void sharing.share()} /> */}
</div>
+ {/* <ShareStatus state={sharing.state} onCopy={sharing.copyAgain} /> */}
<div className="flex-1 overflow-auto p-6">
<div className="flex flex-col items-center justify-center gap-4 text-center">
@@ -309,14 +325,12 @@ function FileViewer({
{error && <p className="text-xs text-destructive mt-2">{error}</p>}
</div>
{filePath && (
- <a
- href={`file://${filePath}`}
- download={fileName}
- className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-xs font-medium text-primary-foreground hover:bg-primary/90"
- >
+ <button
+ onClick={() => void saveArtifactAs(artifact)}
+ className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-xs font-medium text-primary-foreground hover:bg-primary/90">
<Download className="h-3.5 w-3.5" />
Download
- </a>
+ </button>
)}
</div>
</div>
@@ -324,6 +338,268 @@ function FileViewer({
);
}
+// ─── Download and autosave ──────────────────────────────────────
+
+/** Versioned kinds whose record holds the content, so an edit is a version. */
+const EDITABLE_KINDS = new Set(['text', 'markdown', 'html']);
+
+/** Wait after the last keystroke before saving the edit as a new version. */
+export const AUTOSAVE_DELAY_MS = 5_000;
+
+/** The artifact's file name: the one it has in the files folder. */
+function downloadName(artifact: ArtifactSnapshot): string {
+ const fromPath = artifact.path?.split(/[\\/]/).pop();
+ return fromPath || artifact.title;
+}
+
+/** Let the user pick where to save the artifact's file (OS save dialog). */
+async function saveArtifactAs(artifact: ArtifactSnapshot): Promise<void> {
+ try {
+ await invoke<string | null>('save_artifact_as', {
+ artifactId: artifact.artifactId,
+ filename: downloadName(artifact),
+ });
+ } catch (err) {
+ console.error('[ArtifactPreviewPanel] download failed:', err);
+ }
+}
+
+type AutosaveStatus = 'saved' | 'pending' | 'saving' | 'error';
+
+/**
+ * Save edits as new operator versions, AUTOSAVE_DELAY_MS after the last
+ * change. A pending edit is saved at once when the artifact changes, the
+ * panel closes, or a download needs the newest file. The core appends nothing
+ * when the text matches the newest version.
+ */
+export function useArtifactAutosave(
+ artifactId: string,
+ body: string,
+ initialVersion: number,
+ enabled: boolean
+) {
+ const [status, setStatus] = useState<AutosaveStatus>('saved');
+ const [version, setVersion] = useState(initialVersion);
+ const pending = useRef<string | null>(null);
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useEffect(() => {
+ setVersion(initialVersion);
+ setStatus('saved');
+ }, [artifactId, body, initialVersion]);
+
+ const save = useCallback(async () => {
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = null;
+ const next = pending.current;
+ pending.current = null;
+ if (next === null) return;
+ setStatus('saving');
+ try {
+ const result = await callCoreRpc<{ version: number }>({
+ method: 'openhuman.ai_save_artifact_version',
+ params: { artifact_id: artifactId, body: next },
+ });
+ if (typeof result?.version === 'number') setVersion(result.version);
+ setStatus(pending.current === null ? 'saved' : 'pending');
+ } catch (err) {
+ console.error('[ArtifactPreviewPanel] autosave failed:', err);
+ setStatus('error');
+ }
+ }, [artifactId]);
+
+ const schedule = useCallback(
+ (next: string) => {
+ if (!enabled) return;
+ pending.current = next;
+ setStatus('pending');
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = setTimeout(() => void save(), AUTOSAVE_DELAY_MS);
+ },
+ [enabled, save]
+ );
+
+ // Save a pending edit when switching artifacts or closing the panel.
+ useEffect(() => () => void save(), [save]);
+
+ return useMemo(
+ () => ({ status, version, schedule, flush: save }),
+ [status, version, schedule, save]
+ );
+}
+
+function AutosaveStatus({ status }: { status: AutosaveStatus }) {
+ const label = {
+ saved: 'Saved',
+ pending: 'Unsaved changes',
+ saving: 'Saving…',
+ error: 'Not saved',
+ }[status];
+ return (
+ <span
+ className={`text-[11px] border-l pl-2 ${
+ status === 'error' ? 'text-destructive' : 'text-muted-foreground/60'
+ }`}>
+ {label}
+ </span>
+ );
+}
+
+// ─── Share ──────────────────────────────────────────────────────
+
+interface ShareResult {
+ url: string;
+ version: number;
+ public: boolean;
+ expires_at_millis?: number | null;
+ reused: boolean;
+}
+
+type ShareState =
+ | { status: 'idle' }
+ | { status: 'sharing' }
+ | { status: 'shared'; url: string; version: number; expiresAt: number | null; copied: boolean }
+ | { status: 'error'; message: string };
+
+/**
+ * Share the artifact's newest version through cloud file storage
+ * (`ai.share_artifact`, which uploads it and returns a link — reused while it
+ * still works) and copy the link. `beforeShare` runs first, e.g. to save a
+ * pending edit so the newest text is what is shared.
+ */
+export function useArtifactShare(artifactId: string, beforeShare?: () => Promise<void>) {
+ const [state, setState] = useState<ShareState>({ status: 'idle' });
+
+ useEffect(() => {
+ setState({ status: 'idle' });
+ }, [artifactId]);
+
+ const copy = useCallback(async (url: string) => {
+ try {
+ await navigator.clipboard.writeText(url);
+ return true;
+ } catch {
+ return false;
+ }
+ }, []);
+
+ const share = useCallback(async () => {
+ setState({ status: 'sharing' });
+ try {
+ await beforeShare?.();
+ const result = await callCoreRpc<ShareResult>({
+ method: 'openhuman.ai_share_artifact',
+ params: { artifact_id: artifactId },
+ });
+ const copied = await copy(result.url);
+ setState({
+ status: 'shared',
+ url: result.url,
+ version: result.version,
+ expiresAt: result.expires_at_millis ?? null,
+ copied,
+ });
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ console.error('[ArtifactPreviewPanel] share failed:', err);
+ setState({ status: 'error', message });
+ }
+ }, [artifactId, beforeShare, copy]);
+
+ const copyAgain = useCallback(async () => {
+ if (state.status !== 'shared') return false;
+ const copied = await copy(state.url);
+ setState({ ...state, copied });
+ return copied;
+ }, [copy, state]);
+
+ return { state, share, copyAgain };
+}
+
+export function ShareButton({ state, onShare }: { state: ShareState; onShare: () => void }) {
+ return (
+ <button
+ onClick={onShare}
+ disabled={state.status === 'sharing'}
+ title="Share: upload and copy a link"
+ className="inline-flex items-center justify-center rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50">
+ {state.status === 'sharing' ? (
+ <div className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
+ ) : (
+ <Share2 className="h-3.5 w-3.5" />
+ )}
+ </button>
+ );
+}
+
+/** How long the Copy button says "Copied" after a click. */
+const COPIED_FEEDBACK_MS = 2000;
+
+export function ShareStatus({
+ state,
+ onCopy,
+}: {
+ state: ShareState;
+ onCopy: () => Promise<boolean>;
+}) {
+ // The button's own feedback: only for a click on it, not for the copy the
+ // share already made (the status text reports that one).
+ const [justCopied, setJustCopied] = useState(false);
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ useEffect(
+ () => () => {
+ if (timer.current) clearTimeout(timer.current);
+ },
+ []
+ );
+ const handleCopy = useCallback(async () => {
+ const copied = await onCopy();
+ if (!copied) return;
+ setJustCopied(true);
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = setTimeout(() => setJustCopied(false), COPIED_FEEDBACK_MS);
+ }, [onCopy]);
+
+ if (state.status === 'error') {
+ return (
+ <div
+ data-testid="artifact-share-status"
+ className="border-b bg-destructive/10 px-3 py-1.5 text-[11px] text-destructive">
+ Not shared: {state.message}
+ </div>
+ );
+ }
+ if (state.status !== 'shared') return null;
+ const expires = state.expiresAt
+ ? ` · expires ${new Date(state.expiresAt).toLocaleDateString()}`
+ : '';
+ return (
+ <div
+ data-testid="artifact-share-status"
+ className="flex items-center gap-2 border-b bg-muted/20 px-3 py-1.5 text-[11px] text-muted-foreground">
+ <span className="shrink-0">
+ {state.copied ? 'Link copied' : 'Link ready'} · v{state.version}
+ {expires}
+ </span>
+ <span className="min-w-0 flex-1 truncate text-foreground/70" title={state.url}>
+ {state.url}
+ </span>
+ <button
+ onClick={() => void handleCopy()}
+ title="Copy the full link"
+ data-testid="artifact-share-copy"
+ className="inline-flex shrink-0 items-center gap-1 rounded border px-1.5 py-0.5 text-[11px] text-foreground hover:bg-accent">
+ {justCopied ? (
+ <Check className="h-3 w-3 text-green-500" />
+ ) : (
+ <Clipboard className="h-3 w-3" />
+ )}
+ {justCopied ? 'Copied' : 'Copy'}
+ </button>
+ </div>
+ );
+}
+
// ─── Editable text viewer (markdown / text / html) ──────────────
function EditableTextViewer({
@@ -341,33 +617,24 @@ function EditableTextViewer({
}) {
const [tab, setTab] = useState<'preview' | 'code'>('preview');
const [editedBody, setEditedBody] = useState(body);
- const [saving, setSaving] = useState(false);
- const [saved, setSaved] = useState(false);
const [copied, setCopied] = useState(false);
+ // Only kinds whose record holds the content itself can take a new version;
+ // a `file` record holds a path, and its text here is read off that file.
+ const editable = EDITABLE_KINDS.has(kind);
+ const autosave = useArtifactAutosave(artifact.artifactId, body, version, editable);
// Sync when body changes (switching artifact tabs)
useEffect(() => {
setEditedBody(body);
- setSaved(false);
}, [body]);
- const handleSave = useCallback(async () => {
- setSaving(true);
- try {
- await invoke('save_artifact_body', {
- args: {
- artifact_id: artifact.artifactId,
- body: editedBody,
- note: null,
- },
- });
- setSaved(true);
- setTimeout(() => setSaved(false), 2000);
- } catch (err) {
- console.error('[ArtifactPreviewPanel] save failed:', err);
- }
- setSaving(false);
- }, [artifact.artifactId, editedBody]);
+ const onEdit = useCallback(
+ (next: string) => {
+ setEditedBody(next);
+ autosave.schedule(next);
+ },
+ [autosave]
+ );
const handleCopy = useCallback(() => {
void navigator.clipboard.writeText(editedBody);
@@ -375,7 +642,18 @@ function EditableTextViewer({
setTimeout(() => setCopied(false), 2000);
}, [editedBody]);
+ const handleDownload = useCallback(async () => {
+ // The file is the newest saved version: save a pending edit first.
+ await autosave.flush();
+ await saveArtifactAs(artifact);
+ }, [artifact, autosave]);
+
+ // Share the newest saved version: save a pending edit first.
+ // Share is hidden until the backend serves viewable files inline (links download today); see useArtifactShare.
+ // const sharing = useArtifactShare(artifact.artifactId, autosave.flush);
+
const isHtml = kind === 'html';
+ const isMarkdown = kind === 'markdown';
return (
<div className="flex flex-col h-full">
@@ -383,7 +661,10 @@ function EditableTextViewer({
<div className="flex items-center justify-between border-b px-3 py-1.5 shrink-0 bg-muted/10">
<div className="flex items-center gap-2">
<span className="text-xs font-medium text-muted-foreground capitalize">{kind}</span>
- <span className="text-[11px] text-muted-foreground/60 border-l pl-2">v{version}</span>
+ <span className="text-[11px] text-muted-foreground/60 border-l pl-2">
+ v{autosave.version}
+ </span>
+ {editable && <AutosaveStatus status={autosave.status} />}
</div>
<div className="flex items-center gap-0.5">
<div className="flex items-center rounded border mr-2">
@@ -393,8 +674,7 @@ function EditableTextViewer({
tab === 'preview'
? 'bg-primary/10 text-primary'
: 'text-muted-foreground hover:text-foreground'
- }`}
- >
+ }`}>
<Eye className="h-3 w-3" />
Preview
</button>
@@ -404,28 +684,34 @@ function EditableTextViewer({
tab === 'code'
? 'bg-primary/10 text-primary'
: 'text-muted-foreground hover:text-foreground'
- }`}
- >
+ }`}>
<Code2 className="h-3 w-3" />
Code
</button>
</div>
- <button onClick={handleCopy} title="Copy to clipboard" className="inline-flex items-center justify-center rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground">
- {copied ? <Check className="h-3.5 w-3.5 text-green-500" /> : <Clipboard className="h-3.5 w-3.5" />}
- </button>
- <button onClick={handleSave} disabled={saving} title="Save as new version" className="inline-flex items-center justify-center rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50">
- {saving ? (
- <div className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
- ) : saved ? (
+ <button
+ onClick={handleCopy}
+ title="Copy to clipboard"
+ className="inline-flex items-center justify-center rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground">
+ {copied ? (
<Check className="h-3.5 w-3.5 text-green-500" />
) : (
- <Save className="h-3.5 w-3.5" />
+ <Clipboard className="h-3.5 w-3.5" />
)}
</button>
+ {/* <ShareButton state={sharing.state} onShare={() => void sharing.share()} /> */}
+ <button
+ onClick={() => void handleDownload()}
+ title="Download"
+ className="inline-flex items-center justify-center rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground">
+ <Download className="h-3.5 w-3.5" />
+ </button>
</div>
</div>
+ {/* <ShareStatus state={sharing.state} onCopy={sharing.copyAgain} /> */}
+
{/* Error banner */}
{error && (
<div className="border-b bg-destructive/10 px-3 py-1.5 text-[11px] text-destructive">
@@ -442,6 +728,15 @@ function EditableTextViewer({
sandbox="allow-scripts allow-same-origin"
title="HTML preview"
/>
+ ) : isMarkdown ? (
+ // Markdown renders as formatted content (headings, lists, tables,
+ // emphasis) just like HTML renders in the iframe above — not as a
+ // raw source dump.
+ <div className="flex-1 overflow-auto">
+ <div className="p-4 prose prose-sm dark:prose-invert max-w-none">
+ <Markdown remarkPlugins={[remarkGfm]}>{editedBody}</Markdown>
+ </div>
+ </div>
) : (
<div className="flex-1 overflow-auto">
<pre className="p-4 text-sm font-mono leading-relaxed whitespace-pre-wrap break-words">
@@ -452,7 +747,8 @@ function EditableTextViewer({
) : (
<textarea
value={editedBody}
- onChange={e => setEditedBody(e.target.value)}
+ onChange={e => onEdit(e.target.value)}
+ readOnly={!editable}
className="flex-1 w-full resize-none border-0 bg-background p-4 text-sm font-mono leading-relaxed outline-none focus:ring-0"
spellCheck={false}
/>
diff --git a/app/src/features/conversations/aui/MediaAndDocumentCalls.tsx b/app/src/features/conversations/aui/MediaAndDocumentCalls.tsx
index d1297bc870..5a24acab76 100644
--- a/app/src/features/conversations/aui/MediaAndDocumentCalls.tsx
+++ b/app/src/features/conversations/aui/MediaAndDocumentCalls.tsx
@@ -15,8 +15,8 @@ import { useAppSelector } from '../../../store/hooks';
* (`crates/openhuman-core/src/media/generation/tools.rs`) per the
* fe-brief's wire contract: an array of produced artifacts. `path` is a
* local, core-served file (opened through the existing artifact
- * download/serve path — see `services/artifactDownloadService.ts` and
- * `ChatFilesPanel`); `source_url` is used directly when the artifact is
+ * download/serve path — see `services/artifactDownloadService.ts`);
+ * `source_url` is used directly when the artifact is
* already externally hosted.
*/
interface MediaArtifact {
diff --git a/app/src/features/conversations/aui/MessageArtifactCards.test.tsx b/app/src/features/conversations/aui/MessageArtifactCards.test.tsx
new file mode 100644
index 0000000000..d57598f5f4
--- /dev/null
+++ b/app/src/features/conversations/aui/MessageArtifactCards.test.tsx
@@ -0,0 +1,68 @@
+import { configureStore } from '@reduxjs/toolkit';
+import { render, screen } from '@testing-library/react';
+import { Provider } from 'react-redux';
+import { describe, expect, it, vi } from 'vitest';
+
+import chatRuntimeReducer, { upsertArtifactReadyForThread } from '../../../store/chatRuntimeSlice';
+import { MessageArtifactCards } from './MessageArtifactCards';
+
+const message = vi.hoisted(() => ({ custom: {} as Record<string, unknown> }));
+
+vi.mock('@assistant-ui/react', () => ({
+ useAuiState: (select: (s: unknown) => unknown) =>
+ select({ message: { metadata: { custom: message.custom } } }),
+}));
+
+vi.mock('../../../lib/i18n/I18nContext', () => ({
+ useT: () => ({ t: (k: string) => k, locale: 'en' }),
+}));
+
+function renderCards(custom: Record<string, unknown>) {
+ message.custom = custom;
+ const store = configureStore({ reducer: { chatRuntime: chatRuntimeReducer } });
+ for (const [artifactId, requestId] of [
+ ['a-1', 'req-last'],
+ ['a-2', 'req-last'],
+ ['a-3', 'req-last'],
+ ]) {
+ store.dispatch(
+ upsertArtifactReadyForThread({
+ threadId: 't-1',
+ artifactId,
+ kind: 'document',
+ title: `Doc ${artifactId}`,
+ path: `/tmp/${artifactId}.md`,
+ sizeBytes: 12,
+ requestId,
+ })
+ );
+ }
+ render(
+ <Provider store={store}>
+ <MessageArtifactCards />
+ </Provider>
+ );
+ return screen.queryAllByTestId('artifact-card-adapter').map(card => card.textContent);
+}
+
+describe('MessageArtifactCards', () => {
+ it('a reply with rows shows exactly its rows, ignoring stale owners', () => {
+ // All three carry the owner `req-last` (a stale guess), but the rows say
+ // only a-3 belongs to this reply.
+ const cards = renderCards({ extraMetadata: { requestId: 'req-last', artifactIds: ['a-3'] } });
+ expect(cards).toHaveLength(1);
+ expect(cards[0]).toContain('Doc a-3');
+ });
+
+ it('a reply without rows yet falls back to the live owner', () => {
+ expect(renderCards({ extraMetadata: { requestId: 'req-last' } })).toHaveLength(3);
+ });
+
+ it('the running turn uses the live owner', () => {
+ expect(renderCards({ requestId: 'req-last', streaming: true })).toHaveLength(3);
+ });
+
+ it('a reply of another turn without rows shows nothing', () => {
+ expect(renderCards({ extraMetadata: { requestId: 'req-other' } })).toHaveLength(0);
+ });
+});
diff --git a/app/src/features/conversations/aui/MessageArtifactCards.tsx b/app/src/features/conversations/aui/MessageArtifactCards.tsx
index d64153230e..09be47bbe9 100644
--- a/app/src/features/conversations/aui/MessageArtifactCards.tsx
+++ b/app/src/features/conversations/aui/MessageArtifactCards.tsx
@@ -3,40 +3,68 @@
import { useAuiState } from '@assistant-ui/react';
import { useMemo } from 'react';
-import { useAppSelector, useAppDispatch } from '../../../store/hooks';
-import { openArtifact } from '../../../store/chatRuntimeSlice';
+import { ARTIFACT_IDS_METADATA_KEY } from '../../../services/api/artifactRows';
+import { type ArtifactSnapshot, openArtifact } from '../../../store/chatRuntimeSlice';
+import { useAppDispatch, useAppSelector } from '../../../store/hooks';
import { ArtifactCardAdapter } from './ArtifactCardAdapter';
/**
- * Renders artifact cards inside the exact assistant message that produced
- * them. Matches the current message's `metadata.custom.requestId` against
- * each artifact's `ownerRequestId` (tagged by `chatRuntimeSlice` when the
- * pending/ready socket event lands while that turn is live).
+ * Renders artifact cards inside the assistant message that produced them.
*
- * Only artifacts WITHOUT an owning tool call (`!toolCallId`) are shown
- * here — ones WITH a tool call id already render inline next to their
- * tool call via `MediaAndDocumentCalls`.
+ * - **Saved replies** list their artifacts under
+ * `extraMetadata.artifactIds`, attached from the core's artifact rows when the
+ * thread's messages load (`services/api/artifactRows.ts`). This is the
+ * durable placement: it survives refreshes, cleared storage and other
+ * devices.
+ * - **The turn in flight**, or one that just finished, has no rows yet (the
+ * list reloads with them on the next load), so its cards come from the
+ * artifact events, which name the turn (`ownerRequestId`). A reply that has
+ * rows ignores owners: the rows are the record, and an owner can be stale.
+ *
+ * Only artifacts WITHOUT an owning tool call (`!toolCallId`) are shown here —
+ * ones WITH a tool call id render inline next to their tool call via
+ * `MediaAndDocumentCalls`.
*/
export function MessageArtifactCards() {
- // requestId lives at different paths for live vs settled messages:
- // - live streaming message: metadata.custom.requestId
- // - settled message: metadata.custom.extraMetadata.requestId
+ // Message metadata lives at different paths for live vs settled messages:
+ // - live streaming message: metadata.custom
+ // - settled message: metadata.custom.extraMetadata
const meta = useAuiState(s => s.message.metadata?.custom as Record<string, unknown> | undefined);
- const requestId = typeof meta?.requestId === 'string' ? meta.requestId
- : typeof (meta?.extraMetadata as Record<string, unknown> | undefined)?.requestId === 'string'
- ? (meta?.extraMetadata as Record<string, unknown> | undefined)?.requestId as string
- : undefined;
- const threadId = useAppSelector(s => s.thread.selectedThreadId as string | undefined);
+ const extra = meta?.extraMetadata as Record<string, unknown> | undefined;
+ const requestId =
+ typeof meta?.requestId === 'string'
+ ? meta.requestId
+ : typeof extra?.requestId === 'string'
+ ? extra.requestId
+ : undefined;
+ const rawIds = extra?.[ARTIFACT_IDS_METADATA_KEY];
+ const artifactIdsKey = Array.isArray(rawIds)
+ ? rawIds.filter((id): id is string => typeof id === 'string').join('\n')
+ : '';
const dispatch = useAppDispatch();
const artifactsByThread = useAppSelector(s => s.chatRuntime.artifactsByThread);
+ // An artifact id or request id belongs to one thread, so look across every
+ // thread rather than depend on which one is selected.
const cards = useMemo(() => {
- if (!threadId || !requestId) return [];
- const list = artifactsByThread[threadId] ?? [];
- return list.filter(
- a => !a.toolCallId && a.ownerRequestId === requestId && (a.status === 'in_progress' || a.status === 'ready')
+ const listed = artifactIdsKey ? artifactIdsKey.split('\n') : [];
+ // Rows when the reply has them; the live owner only until it does.
+ const byOwner = listed.length === 0 ? requestId : undefined;
+ if (listed.length === 0 && !byOwner) return [];
+ const shown = new Map<string, ArtifactSnapshot>();
+ for (const list of Object.values(artifactsByThread)) {
+ for (const a of list) {
+ if (a.toolCallId || (a.status !== 'in_progress' && a.status !== 'ready')) continue;
+ if (listed.includes(a.artifactId) || (byOwner && a.ownerRequestId === byOwner)) {
+ shown.set(a.artifactId, a);
+ }
+ }
+ }
+ // Rows first, in the order the turn made them.
+ return [...shown.values()].sort(
+ (a, b) => indexOrEnd(listed, a.artifactId) - indexOrEnd(listed, b.artifactId)
);
- }, [artifactsByThread, threadId, requestId]);
+ }, [artifactsByThread, artifactIdsKey, requestId]);
if (cards.length === 0) return null;
@@ -54,3 +82,8 @@ export function MessageArtifactCards() {
}
export default MessageArtifactCards;
+
+function indexOrEnd(list: readonly string[], id: string): number {
+ const index = list.indexOf(id);
+ return index === -1 ? list.length : index;
+}
diff --git a/app/src/features/conversations/aui/useMentionSource.ts b/app/src/features/conversations/aui/useMentionSource.ts
index 89cb7e70a2..1aaffb0c97 100644
--- a/app/src/features/conversations/aui/useMentionSource.ts
+++ b/app/src/features/conversations/aui/useMentionSource.ts
@@ -9,8 +9,8 @@
* filter, which would drop semantic hits whose label does not literally
* contain the query, so `search` is extended to always include them.
* - **Files** — the thread's ready artifacts, read from
- * `chatRuntime.artifactsByThread` (the list the header `ChatFilesChip`
- * hydrates). No new RPC.
+ * `chatRuntime.artifactsByThread` (the list
+ * `useThreadArtifactsHydration` loads). No new RPC.
*
* Choosing an item inserts `:type[label]{name=id}` through the default
* directive formatter — the syntax `DirectiveText` renders as a chip in the
diff --git a/app/src/features/conversations/components/AssistantUiChat.tsx b/app/src/features/conversations/components/AssistantUiChat.tsx
index 24317530e9..a0e247046c 100644
--- a/app/src/features/conversations/components/AssistantUiChat.tsx
+++ b/app/src/features/conversations/components/AssistantUiChat.tsx
@@ -16,8 +16,8 @@ import { ChatConversationMap } from '../aui/ChatConversationMap';
import { ComposerTriggers } from '../aui/ComposerTriggers';
import { ContextUsage } from '../aui/ContextUsage';
import { InterruptedTurnNotice } from '../aui/InterruptedTurnNotice';
-import { ActiveTurnTaskCards, TurnTaskCards, TurnTaskProvider } from '../aui/TurnTaskCards';
import { MessageArtifactCards } from '../aui/MessageArtifactCards';
+import { ActiveTurnTaskCards, TurnTaskCards, TurnTaskProvider } from '../aui/TurnTaskCards';
import { ChatSources } from './aui/ChatSources';
import { ChatToolFallback } from './ChatToolParts';
@@ -342,7 +342,10 @@ export function AssistantUiChat({
AfterMessages,
// Artifact cards render INSIDE the message that produced them
// (matched by requestId), not just at the end of the transcript.
- MessageArtifacts: () => <MessageArtifactCards />,
+ // Pass the component itself: an inline arrow is a new component type
+ // each time this memo recomputes (e.g. when a turn starts or ends), which
+ // remounts every card and replays its fade-in, so the cards flicker.
+ MessageArtifacts: MessageArtifactCards,
// The web pages the turn fetched, grouped from its `source` parts into
// one collapsed disclosure under the answer.
SourceGroup: ChatSources,
diff --git a/app/src/features/conversations/hooks/useThreadArtifactsHydration.ts b/app/src/features/conversations/hooks/useThreadArtifactsHydration.ts
new file mode 100644
index 0000000000..484aad9f93
--- /dev/null
+++ b/app/src/features/conversations/hooks/useThreadArtifactsHydration.ts
@@ -0,0 +1,54 @@
+import { useEffect } from 'react';
+
+import { listArtifactsForThread } from '../../../services/artifactDownloadService';
+import { upsertArtifactReadyForThread } from '../../../store/chatRuntimeSlice';
+import { useAppDispatch } from '../../../store/hooks';
+
+/**
+ * Load a thread's ready artifacts from the core into
+ * `chatRuntime.artifactsByThread` when the thread is opened (#3024), so the
+ * artifact cards, the preview panel and the `@` mention list have them after
+ * a restart or on a thread the app has not seen yet.
+ *
+ * Where each card renders comes from the thread's artifact rows, not from
+ * here (`services/api/artifactRows.ts`).
+ */
+export function useThreadArtifactsHydration(threadId: string | null | undefined): void {
+ const dispatch = useAppDispatch();
+ const normalizedThreadId = threadId?.trim() ?? '';
+
+ useEffect(() => {
+ if (!normalizedThreadId) return;
+ let cancelled = false;
+ void listArtifactsForThread(normalizedThreadId).then(outcome => {
+ if (cancelled) return;
+ if (!outcome.ok) {
+ console.warn('[artifact] failed to hydrate thread artifacts', {
+ threadId: normalizedThreadId,
+ error: outcome.error,
+ });
+ return;
+ }
+ if (outcome.artifacts.length === 0) return;
+ console.debug('[artifact] hydrating thread artifacts', {
+ threadId: normalizedThreadId,
+ count: outcome.artifacts.length,
+ });
+ for (const artifact of outcome.artifacts) {
+ dispatch(
+ upsertArtifactReadyForThread({
+ threadId: normalizedThreadId,
+ artifactId: artifact.artifactId,
+ kind: artifact.kind,
+ title: artifact.title,
+ path: artifact.path,
+ sizeBytes: artifact.sizeBytes,
+ })
+ );
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [dispatch, normalizedThreadId]);
+}
diff --git a/app/src/pages/__tests__/Conversations.auiComposerSurfaces.test.tsx b/app/src/pages/__tests__/Conversations.auiComposerSurfaces.test.tsx
index 0cbffff9ea..1999506c83 100644
--- a/app/src/pages/__tests__/Conversations.auiComposerSurfaces.test.tsx
+++ b/app/src/pages/__tests__/Conversations.auiComposerSurfaces.test.tsx
@@ -28,6 +28,7 @@ import { SidebarSlotOutlet, SidebarSlotProvider } from '../../components/layout/
import Conversations from '../../features/conversations/Conversations';
// Type-only: erased at runtime, so it does not defeat `vi.hoisted`.
import type { FlowApprovalRequest } from '../../hooks/useFlowApprovalRequests';
+import { listArtifactsForThread } from '../../services/artifactDownloadService';
import { chatSend } from '../../services/chatService';
import { callCoreRpc } from '../../services/coreRpcClient';
import chatRuntimeReducer, {
@@ -129,8 +130,8 @@ vi.mock('../../store/socketSelectors', () => ({
vi.mock('../../utils/openUrl', () => ({ openUrl: vi.fn() }));
-// ChatFilesChip hydrates ready artifacts through the Tauri artifact service on
-// mount; the chip under test is driven from the preloaded slice instead.
+// The thread's ready artifacts are hydrated through the Tauri artifact service
+// when the thread opens.
vi.mock('../../services/artifactDownloadService', () => ({
listArtifactsForThread: vi.fn().mockResolvedValue({ ok: true, artifacts: [] }),
saveArtifactViaDialog: vi.fn(),
@@ -518,10 +519,11 @@ describe('assistant-ui chat surface — composer-adjacent cards', () => {
expect(chatSend).not.toHaveBeenCalled();
});
- it('lists the thread files chip beside the model pill', async () => {
+ it('loads the thread artifacts without a files chip in the composer', async () => {
await renderChat({ chatRuntime: { artifactsByThread: { [THREAD_ID]: [readyArtifact()] } } });
- expect(await screen.findByTestId('chat-files-chip')).toBeInTheDocument();
+ await waitFor(() => expect(listArtifactsForThread).toHaveBeenCalledWith(THREAD_ID));
+ expect(screen.queryByTestId('chat-files-chip')).not.toBeInTheDocument();
});
it('places context usage in the right action cluster immediately before voice mode', async () => {
diff --git a/app/src/providers/ChatRuntimeProvider.tsx b/app/src/providers/ChatRuntimeProvider.tsx
index de5b271966..799dc423df 100644
--- a/app/src/providers/ChatRuntimeProvider.tsx
+++ b/app/src/providers/ChatRuntimeProvider.tsx
@@ -1391,6 +1391,7 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {
kind: event.kind,
title: event.title,
toolCallId: event.tool_call_id,
+ requestId: event.request_id,
})
);
},
@@ -1410,6 +1411,7 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {
path: event.path,
sizeBytes: event.size_bytes,
toolCallId: event.tool_call_id,
+ requestId: event.request_id,
})
);
},
@@ -1430,6 +1432,7 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {
kind: event.kind,
title: event.title,
error: event.error,
+ requestId: event.request_id,
})
);
},
diff --git a/app/src/services/api/__tests__/artifactRows.test.ts b/app/src/services/api/__tests__/artifactRows.test.ts
new file mode 100644
index 0000000000..1ce114ee03
--- /dev/null
+++ b/app/src/services/api/__tests__/artifactRows.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ThreadMessage } from '../../../types/thread';
+import { ARTIFACT_IDS_METADATA_KEY, attachArtifactRows } from '../artifactRows';
+
+const user = (id: string, requestId: string): ThreadMessage => ({
+ id,
+ content: 'make it',
+ type: 'text',
+ extraMetadata: { requestId },
+ sender: 'user',
+ createdAt: '2026-10-15T09:00:00Z',
+});
+const reply = (id: string, requestId?: string): ThreadMessage => ({
+ id,
+ content: 'Created it.',
+ type: 'text',
+ extraMetadata: requestId ? { requestId } : {},
+ sender: 'agent',
+ createdAt: '2026-10-15T09:01:00Z',
+});
+const row = (artifactId: string, requestId?: string): ThreadMessage => ({
+ id: `artifact:${artifactId}`,
+ content: artifactId,
+ type: 'artifact',
+ extraMetadata: requestId ? { artifactId, requestId } : { artifactId },
+ sender: 'agent',
+ createdAt: '2026-10-15T09:00:30Z',
+});
+const ids = (message: ThreadMessage) => message.extraMetadata[ARTIFACT_IDS_METADATA_KEY];
+
+describe('attachArtifactRows', () => {
+ it('takes rows out of the list and lists each artifact on its turn reply', () => {
+ const out = attachArtifactRows([
+ user('u1', 'req-1'),
+ row('a', 'req-1'),
+ reply('r1', 'req-1'),
+ user('u2', 'req-2'),
+ row('b', 'req-2'),
+ row('c', 'req-2'),
+ reply('r2', 'req-2'),
+ ]);
+ expect(out.map(m => m.id)).toEqual(['u1', 'r1', 'u2', 'r2']);
+ expect(ids(out[1])).toEqual(['a']);
+ expect(ids(out[3])).toEqual(['b', 'c']);
+ expect(ids(out[0])).toBeUndefined();
+ });
+
+ it('places a row by its turn even when it was written after later replies (backfill)', () => {
+ const out = attachArtifactRows([
+ user('u1', 'req-1'),
+ reply('r1', 'req-1'),
+ user('u2', 'req-2'),
+ reply('r2', 'req-2'),
+ row('a', 'req-1'),
+ ]);
+ expect(ids(out[1])).toEqual(['a']);
+ expect(ids(out[3])).toBeUndefined();
+ });
+
+ it('places a row without a turn on the next agent reply', () => {
+ const out = attachArtifactRows([row('a'), reply('r1')]);
+ expect(out.map(m => m.id)).toEqual(['r1']);
+ expect(ids(out[0])).toEqual(['a']);
+ });
+
+ it('drops a row whose turn has no reply yet (the live event places it)', () => {
+ const out = attachArtifactRows([user('u1', 'req-1'), row('a', 'req-1')]);
+ expect(out.map(m => m.id)).toEqual(['u1']);
+ });
+
+ it('keeps message identity when there are no rows', () => {
+ const messages = [user('u1', 'req-1'), reply('r1', 'req-1')];
+ const out = attachArtifactRows(messages);
+ expect(out[0]).toBe(messages[0]);
+ expect(out[1]).toBe(messages[1]);
+ });
+});
diff --git a/app/src/services/api/artifactRows.ts b/app/src/services/api/artifactRows.ts
new file mode 100644
index 0000000000..a5070abcbb
--- /dev/null
+++ b/app/src/services/api/artifactRows.ts
@@ -0,0 +1,89 @@
+/**
+ * Artifact rows in a thread's message list.
+ *
+ * The core writes one row per artifact made in a chat (`type: "artifact"`,
+ * `extraMetadata: { artifactId, requestId }`; see the core's
+ * `threads::artifact_rows`). The row records which turn made the artifact, so
+ * the card renders inside that turn's reply on every load, on every device.
+ *
+ * Rows are never shown as messages. {@link attachArtifactRows} takes them out
+ * of the list and records each artifact id on the reply it belongs to, under
+ * `extraMetadata[ARTIFACT_IDS_METADATA_KEY]`, where `MessageArtifactCards`
+ * reads it.
+ */
+import type { ThreadMessage } from '../../types/thread';
+
+export const ARTIFACT_MESSAGE_TYPE = 'artifact';
+
+/** Reply metadata key listing the artifacts whose cards render in that reply. */
+export const ARTIFACT_IDS_METADATA_KEY = 'artifactIds';
+
+function stringField(metadata: Record<string, unknown> | undefined, key: string) {
+ const value = metadata?.[key];
+ return typeof value === 'string' && value ? value : undefined;
+}
+
+/**
+ * The reply an artifact row belongs to: the last agent message of the row's
+ * turn, or, for a row without a turn, the first agent message after it.
+ */
+function replyIndexFor(messages: readonly ThreadMessage[], rowIndex: number, requestId?: string) {
+ // Rows are agent messages too; a row is never a reply.
+ const isReply = (message: ThreadMessage) =>
+ message.sender === 'agent' && message.type !== ARTIFACT_MESSAGE_TYPE;
+ if (requestId) {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const message = messages[i];
+ if (isReply(message) && stringField(message.extraMetadata, 'requestId') === requestId)
+ return i;
+ }
+ return -1;
+ }
+ return messages.findIndex((message, i) => i > rowIndex && isReply(message));
+}
+
+/**
+ * `messages` without artifact rows, each row's artifact id recorded on its
+ * reply. A row whose reply is not in the list (its turn is still running) is
+ * dropped; the live artifact event places that card meanwhile. Messages that
+ * gain no artifact keep their identity.
+ */
+export function attachArtifactRows(messages: readonly ThreadMessage[]): ThreadMessage[] {
+ if (!messages.some(message => message.type === ARTIFACT_MESSAGE_TYPE)) return [...messages];
+
+ const visible: ThreadMessage[] = [];
+ // Index in `messages` → index in `visible`, so a row's reply can be found in
+ // the original order (a row without a turn is placed by position).
+ const visibleIndex = new Map<number, number>();
+ messages.forEach((message, i) => {
+ if (message.type === ARTIFACT_MESSAGE_TYPE) return;
+ visibleIndex.set(i, visible.length);
+ visible.push(message);
+ });
+
+ const idsByReply = new Map<number, string[]>();
+ messages.forEach((message, i) => {
+ if (message.type !== ARTIFACT_MESSAGE_TYPE) return;
+ const artifactId = stringField(message.extraMetadata, 'artifactId');
+ if (!artifactId) return;
+ const reply = replyIndexFor(messages, i, stringField(message.extraMetadata, 'requestId'));
+ const target = visibleIndex.get(reply);
+ if (target === undefined) return;
+ const ids = idsByReply.get(target) ?? [];
+ if (!ids.includes(artifactId)) ids.push(artifactId);
+ idsByReply.set(target, ids);
+ });
+
+ for (const [index, ids] of idsByReply) {
+ const reply = visible[index];
+ const existing = reply.extraMetadata?.[ARTIFACT_IDS_METADATA_KEY];
+ const merged = Array.isArray(existing)
+ ? [...new Set([...existing.filter((id): id is string => typeof id === 'string'), ...ids])]
+ : ids;
+ visible[index] = {
+ ...reply,
+ extraMetadata: { ...reply.extraMetadata, [ARTIFACT_IDS_METADATA_KEY]: merged },
+ };
+ }
+ return visible;
+}
diff --git a/app/src/services/api/threadApi.ts b/app/src/services/api/threadApi.ts
index 1a0eb388a7..c797c32d0c 100644
--- a/app/src/services/api/threadApi.ts
+++ b/app/src/services/api/threadApi.ts
@@ -26,6 +26,7 @@ import type {
} from '../../types/turnState';
import type { ChatThreadTodoItem, ThreadGoal } from '../chatService';
import { callCoreRpc } from '../coreRpcClient';
+import { attachArtifactRows } from './artifactRows';
interface Envelope<T> {
data?: T;
@@ -78,7 +79,10 @@ export const threadApi = {
params: { thread_id: threadId },
});
const data = unwrapEnvelope(response);
- return { ...data, messages: data.messages.map(normalizeThreadMessage) };
+ // Artifact rows place artifact cards; they are attached to their replies
+ // here so no caller ever sees them as messages.
+ const messages = attachArtifactRows(data.messages.map(normalizeThreadMessage));
+ return { ...data, messages, count: messages.length };
},
/** Message text search across every thread, newest first. */
diff --git a/app/src/services/chatService.ts b/app/src/services/chatService.ts
index 9b0ee3b4b2..566c0787fb 100644
--- a/app/src/services/chatService.ts
+++ b/app/src/services/chatService.ts
@@ -527,6 +527,11 @@ export interface ArtifactReadyEvent {
* deck — see `ArtifactSnapshot.toolCallId`.
*/
tool_call_id?: string;
+ /**
+ * The turn that made the artifact (`turn_request_id` on the wire). Places
+ * the card in that turn's reply while the turn runs.
+ */
+ request_id?: string;
}
/**
@@ -546,6 +551,8 @@ export interface ArtifactFailedEvent {
error: string;
/** See {@link ArtifactReadyEvent.tool_call_id}. */
tool_call_id?: string;
+ /** See {@link ArtifactReadyEvent.request_id}. */
+ request_id?: string;
}
/**
@@ -568,6 +575,8 @@ export interface ArtifactPendingEvent {
path: string;
/** See {@link ArtifactReadyEvent.tool_call_id}. */
tool_call_id?: string;
+ /** See {@link ArtifactReadyEvent.request_id}. */
+ request_id?: string;
}
/** Emitted when the agent turn begins (before the first LLM call). */
@@ -1385,16 +1394,27 @@ export function subscribeChatEvents(listeners: ChatEventListeners): () => void {
const isFiniteNumber = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
const readEnvelope = (
payload: unknown
- ): { thread_id: string; client_id?: string; args: Record<string, unknown> } | null => {
+ ): {
+ thread_id: string;
+ client_id?: string;
+ request_id?: string;
+ args: Record<string, unknown>;
+ } | null => {
if (!payload || typeof payload !== 'object') return null;
- const env = payload as { thread_id?: unknown; client_id?: unknown; args?: unknown };
+ const env = payload as {
+ thread_id?: unknown;
+ client_id?: unknown;
+ turn_request_id?: unknown;
+ args?: unknown;
+ };
if (!isNonEmptyString(env.thread_id)) return null;
const client_id = typeof env.client_id === 'string' ? env.client_id : undefined;
+ const request_id = isNonEmptyString(env.turn_request_id) ? env.turn_request_id : undefined;
const args =
env.args && typeof env.args === 'object' && !Array.isArray(env.args)
? (env.args as Record<string, unknown>)
: {};
- return { thread_id: env.thread_id, client_id, args };
+ return { thread_id: env.thread_id, client_id, request_id, args };
};
if (listeners.onArtifactPending) {
@@ -1429,6 +1449,7 @@ export function subscribeChatEvents(listeners: ChatEventListeners): () => void {
workspace_dir: args.workspace_dir,
path: args.path,
tool_call_id: isNonEmptyString(args.tool_call_id) ? args.tool_call_id : undefined,
+ request_id: env.request_id,
};
chatLog(
'%s thread_id=%s artifact_id=%s kind=%s',
@@ -1476,6 +1497,7 @@ export function subscribeChatEvents(listeners: ChatEventListeners): () => void {
path: args.path,
size_bytes: args.size_bytes,
tool_call_id: isNonEmptyString(args.tool_call_id) ? args.tool_call_id : undefined,
+ request_id: env.request_id,
};
chatLog(
'%s thread_id=%s artifact_id=%s kind=%s size=%d',
@@ -1522,6 +1544,7 @@ export function subscribeChatEvents(listeners: ChatEventListeners): () => void {
workspace_dir: args.workspace_dir,
error: args.error,
tool_call_id: isNonEmptyString(args.tool_call_id) ? args.tool_call_id : undefined,
+ request_id: env.request_id,
};
// Defence-in-depth: producer is expected to pre-truncate, but
// cap the log preview again so a leaky producer cannot blast
diff --git a/app/src/store/__tests__/chatRuntimeSlice.artifactOwner.test.ts b/app/src/store/__tests__/chatRuntimeSlice.artifactOwner.test.ts
new file mode 100644
index 0000000000..e08e80d56b
--- /dev/null
+++ b/app/src/store/__tests__/chatRuntimeSlice.artifactOwner.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from 'vitest';
+
+import chatRuntimeReducer, {
+ liveTurnStarted,
+ turnSettled,
+ upsertArtifactFailedForThread,
+ upsertArtifactInProgressForThread,
+ upsertArtifactReadyForThread,
+} from '../chatRuntimeSlice';
+
+type State = ReturnType<typeof chatRuntimeReducer>;
+
+const THREAD = 't-1';
+const ready = (artifactId: string) =>
+ upsertArtifactReadyForThread({
+ threadId: THREAD,
+ artifactId,
+ kind: 'document',
+ title: artifactId,
+ path: `/tmp/${artifactId}.md`,
+ sizeBytes: 12,
+ });
+const owner = (state: State, artifactId: string) =>
+ state.artifactsByThread[THREAD]?.find(a => a.artifactId === artifactId)?.ownerRequestId;
+
+function apply(state: State, ...actions: Parameters<typeof chatRuntimeReducer>[1][]): State {
+ return actions.reduce(chatRuntimeReducer, state);
+}
+
+describe('artifact owner turn', () => {
+ it('tags an artifact with the turn that was live when it appeared', () => {
+ const state = apply(
+ chatRuntimeReducer(undefined, { type: 'init' }),
+ liveTurnStarted({ threadId: THREAD, requestId: 'req-1' }),
+ ready('a-1')
+ );
+ expect(owner(state, 'a-1')).toBe('req-1');
+ });
+
+ it('keeps the owner when the thread list is re-hydrated after the turn ended (refresh)', () => {
+ let state = apply(
+ chatRuntimeReducer(undefined, { type: 'init' }),
+ liveTurnStarted({ threadId: THREAD, requestId: 'req-1' }),
+ ready('a-1'),
+ turnSettled({ threadId: THREAD, requestId: 'req-1' })
+ );
+ // ChatFilesChip re-hydrates every listed artifact through the same action.
+ state = apply(state, ready('a-1'));
+ expect(owner(state, 'a-1')).toBe('req-1');
+ });
+
+ it('does not move an older artifact into a newer live turn', () => {
+ const state = apply(
+ chatRuntimeReducer(undefined, { type: 'init' }),
+ liveTurnStarted({ threadId: THREAD, requestId: 'req-1' }),
+ ready('a-1'),
+ turnSettled({ threadId: THREAD, requestId: 'req-1' }),
+ liveTurnStarted({ threadId: THREAD, requestId: 'req-2' }),
+ ready('a-1'),
+ ready('a-2')
+ );
+ expect(owner(state, 'a-1')).toBe('req-1');
+ expect(owner(state, 'a-2')).toBe('req-2');
+ });
+
+ it('keeps the owner through a failure and its retry', () => {
+ const state = apply(
+ chatRuntimeReducer(undefined, { type: 'init' }),
+ liveTurnStarted({ threadId: THREAD, requestId: 'req-1' }),
+ upsertArtifactInProgressForThread({
+ threadId: THREAD,
+ artifactId: 'a-1',
+ kind: 'document',
+ title: 'a-1',
+ }),
+ upsertArtifactFailedForThread({
+ threadId: THREAD,
+ artifactId: 'a-1',
+ kind: 'document',
+ title: 'a-1',
+ error: 'boom',
+ }),
+ turnSettled({ threadId: THREAD, requestId: 'req-1' }),
+ ready('a-1')
+ );
+ expect(owner(state, 'a-1')).toBe('req-1');
+ });
+
+ it('leaves an artifact first seen outside any turn unowned', () => {
+ const state = apply(chatRuntimeReducer(undefined, { type: 'init' }), ready('a-1'));
+ expect(owner(state, 'a-1')).toBeUndefined();
+ });
+
+ it('takes the turn the event names over the live turn', () => {
+ const state = apply(
+ chatRuntimeReducer(undefined, { type: 'init' }),
+ liveTurnStarted({ threadId: THREAD, requestId: 'req-2' }),
+ upsertArtifactReadyForThread({
+ threadId: THREAD,
+ artifactId: 'a-1',
+ kind: 'document',
+ title: 'a-1',
+ path: '/tmp/a-1.md',
+ sizeBytes: 12,
+ requestId: 'req-1',
+ })
+ );
+ expect(owner(state, 'a-1')).toBe('req-1');
+ });
+});
diff --git a/app/src/store/__tests__/chatRuntimeSlice.artifactTabs.component.test.tsx b/app/src/store/__tests__/chatRuntimeSlice.artifactTabs.component.test.tsx
new file mode 100644
index 0000000000..4ed675876a
--- /dev/null
+++ b/app/src/store/__tests__/chatRuntimeSlice.artifactTabs.component.test.tsx
@@ -0,0 +1,97 @@
+import { configureStore } from '@reduxjs/toolkit';
+import { fireEvent, render, screen } from '@testing-library/react';
+import { Provider } from 'react-redux';
+import { describe, expect, it, vi } from 'vitest';
+
+import { ArtifactPreviewPanel } from '../../features/conversations/aui/ArtifactPreviewPanel';
+import chatRuntimeReducer, {
+ openArtifact,
+ upsertArtifactReadyForThread,
+} from '../chatRuntimeSlice';
+
+vi.mock('../../lib/i18n/I18nContext', () => ({
+ useT: () => ({ t: (k: string) => k, locale: 'en' }),
+}));
+
+function makeStore() {
+ const store = configureStore({ reducer: { chatRuntime: chatRuntimeReducer } });
+ for (const [id, title] of [
+ ['a-1', 'Doc One'],
+ ['a-2', 'Doc Two'],
+ ] as const) {
+ store.dispatch(
+ upsertArtifactReadyForThread({
+ threadId: 't-1',
+ artifactId: id,
+ kind: 'document',
+ title,
+ path: `/tmp/${id}.md`,
+ sizeBytes: 12,
+ })
+ );
+ }
+ store.dispatch(openArtifact('a-1'));
+ store.dispatch(openArtifact('a-2'));
+ return store;
+}
+
+describe('ArtifactPreviewPanel — tab switching & close (#1535)', () => {
+ it('renders a tab per open artifact and switching updates activeArtifactId', () => {
+ const store = makeStore();
+ render(
+ <Provider store={store}>
+ <ArtifactPreviewPanel />
+ </Provider>
+ );
+
+ // Two tabs rendered (showTabs = length > 1)
+ const tab1 = screen.getByRole('button', { name: 'Doc One' });
+ const tab2 = screen.getByRole('button', { name: 'Doc Two' });
+ expect(tab1).toBeTruthy();
+ expect(tab2).toBeTruthy();
+
+ // activeArtifactId starts at a-2 (last opened)
+ expect(store.getState().chatRuntime.activeArtifactId).toBe('a-2');
+
+ // Clicking the first tab activates it
+ fireEvent.click(tab1);
+ expect(store.getState().chatRuntime.activeArtifactId).toBe('a-1');
+ // tab list unchanged
+ expect(store.getState().chatRuntime.openArtifactIds).toEqual(['a-1', 'a-2']);
+
+ // Clicking the second tab switches back
+ fireEvent.click(tab2);
+ expect(store.getState().chatRuntime.activeArtifactId).toBe('a-2');
+ });
+
+ it('the per-tab X closes that tab and the panel stays on the other tab', () => {
+ const store = makeStore();
+ render(
+ <Provider store={store}>
+ <ArtifactPreviewPanel />
+ </Provider>
+ );
+
+ // Two tabs, each with a close (X) button.
+ const closeBtns = screen.getAllByTitle('Close artifact');
+ expect(closeBtns).toHaveLength(2);
+
+ // Close the non-active tab (a-1): it is removed and a-2 stays active.
+ fireEvent.click(closeBtns[0]);
+ expect(store.getState().chatRuntime.openArtifactIds).toEqual(['a-2']);
+ expect(store.getState().chatRuntime.activeArtifactId).toBe('a-2');
+ });
+
+ it('the header X closes the whole panel, whatever tabs are open', () => {
+ const store = makeStore();
+ render(
+ <Provider store={store}>
+ <ArtifactPreviewPanel />
+ </Provider>
+ );
+
+ fireEvent.click(screen.getByTitle('Close panel'));
+ expect(store.getState().chatRuntime.openArtifactIds).toEqual([]);
+ expect(store.getState().chatRuntime.activeArtifactId).toBeNull();
+ });
+});
diff --git a/app/src/store/__tests__/chatRuntimeSlice.artifactTabs.test.ts b/app/src/store/__tests__/chatRuntimeSlice.artifactTabs.test.ts
new file mode 100644
index 0000000000..65f288573c
--- /dev/null
+++ b/app/src/store/__tests__/chatRuntimeSlice.artifactTabs.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+
+import reducer, { activateArtifactTab, closeArtifactTab, openArtifact } from '../chatRuntimeSlice';
+
+function seeded() {
+ let s = reducer(undefined, openArtifact('a-1'));
+ s = reducer(s, openArtifact('a-2'));
+ return s;
+}
+
+describe('chatRuntimeSlice — artifact tab model (#1535)', () => {
+ it('openArtifact adds a tab idempotently and activates it', () => {
+ const s = seeded();
+ expect(s.openArtifactIds).toEqual(['a-1', 'a-2']);
+ expect(s.activeArtifactId).toBe('a-2');
+
+ const s2 = reducer(s, openArtifact('a-1'));
+ expect(s2.openArtifactIds).toEqual(['a-1', 'a-2']);
+ expect(s2.activeArtifactId).toBe('a-1');
+ });
+
+ it('activateArtifactTab switches the active tab', () => {
+ const s = reducer(seeded(), activateArtifactTab('a-1'));
+ expect(s.activeArtifactId).toBe('a-1');
+ expect(s.openArtifactIds).toEqual(['a-1', 'a-2']);
+ });
+
+ it('closeArtifactTab removes the tab and activates the next one', () => {
+ let s = reducer(seeded(), closeArtifactTab('a-2'));
+ expect(s.openArtifactIds).toEqual(['a-1']);
+ expect(s.activeArtifactId).toBe('a-1');
+
+ s = reducer(s, closeArtifactTab('a-1'));
+ expect(s.openArtifactIds).toEqual([]);
+ expect(s.activeArtifactId).toBeNull();
+ });
+
+ it('closeArtifactTab of a non-active tab keeps the active tab', () => {
+ const s = reducer(seeded(), closeArtifactTab('a-1'));
+ expect(s.openArtifactIds).toEqual(['a-2']);
+ expect(s.activeArtifactId).toBe('a-2');
+ });
+});
diff --git a/app/src/store/chatRuntimeSlice.ts b/app/src/store/chatRuntimeSlice.ts
index 694b665052..ecc7667f52 100644
--- a/app/src/store/chatRuntimeSlice.ts
+++ b/app/src/store/chatRuntimeSlice.ts
@@ -893,10 +893,10 @@ export interface ArtifactSnapshot {
*/
toolCallId?: string;
/**
- * The `request_id` of the chat turn that was live when this artifact's
- * pending/ready event landed. Lets the transcript render the card inside
- * the exact assistant message that produced it (MessageArtifactCards
- * matches message metadata.requestId against this).
+ * The turn that made the artifact, from its pending/ready event. Places the
+ * card in that turn's message while the turn runs; saved replies place
+ * their cards from the core's artifact rows instead
+ * (`services/api/artifactRows.ts`).
*/
ownerRequestId?: string;
}
@@ -1201,6 +1201,20 @@ function subagentRows(
return rows.filter((row, index) => rows.indexOf(row) === index);
}
+/**
+ * The turn an artifact belongs to. The event names it; older cores that do not
+ * fall back to the thread's live turn. An artifact keeps the owner it already
+ * has, so a re-hydration or a late event never moves it.
+ */
+function ownerFor(
+ state: { liveRequestIdByThread: Record<string, string | undefined> },
+ threadId: string,
+ existing: ArtifactSnapshot | undefined,
+ requestId: string | undefined
+): string | undefined {
+ return existing?.ownerRequestId ?? requestId ?? state.liveRequestIdByThread[threadId];
+}
+
/**
* Upsert a single artifact snapshot for a thread. New entries append
* in insertion order (matches the timeline ordering the UI expects);
@@ -2639,9 +2653,10 @@ const chatRuntimeSlice = createSlice({
kind: ArtifactSnapshot['kind'];
title: string;
toolCallId?: string;
+ requestId?: string;
}>
) => {
- const { threadId, artifactId, kind, title, toolCallId } = action.payload;
+ const { threadId, artifactId, kind, title, toolCallId, requestId } = action.payload;
// No-downgrade guard: a late `artifact_pending` (re-delivery, or a
// socket race) must never regress an artifact that already reached
// `ready` / `failed` back to a spinner. Only the regenerate flow
@@ -2663,7 +2678,7 @@ const chatRuntimeSlice = createSlice({
status: 'in_progress',
updatedAt: Date.now(),
toolCallId: toolCallId ?? existing?.toolCallId,
- ownerRequestId: state.liveRequestIdByThread[threadId],
+ ownerRequestId: ownerFor(state, threadId, existing, requestId),
};
state.artifactsByThread[threadId] = upsertArtifact(
state.artifactsByThread[threadId],
@@ -2685,9 +2700,11 @@ const chatRuntimeSlice = createSlice({
path: string;
sizeBytes: number;
toolCallId?: string;
+ requestId?: string;
}>
) => {
- const { threadId, artifactId, kind, title, path, sizeBytes, toolCallId } = action.payload;
+ const { threadId, artifactId, kind, title, path, sizeBytes, toolCallId, requestId } =
+ action.payload;
const existing = (state.artifactsByThread[threadId] ?? []).find(
entry => entry.artifactId === artifactId
);
@@ -2700,7 +2717,7 @@ const chatRuntimeSlice = createSlice({
sizeBytes,
updatedAt: Date.now(),
toolCallId: toolCallId ?? existing?.toolCallId,
- ownerRequestId: state.liveRequestIdByThread[threadId],
+ ownerRequestId: ownerFor(state, threadId, existing, requestId),
};
state.artifactsByThread[threadId] = upsertArtifact(
state.artifactsByThread[threadId],
@@ -2721,9 +2738,10 @@ const chatRuntimeSlice = createSlice({
title: string;
error: string;
toolCallId?: string;
+ requestId?: string;
}>
) => {
- const { threadId, artifactId, kind, title, error, toolCallId } = action.payload;
+ const { threadId, artifactId, kind, title, error, toolCallId, requestId } = action.payload;
const existing = (state.artifactsByThread[threadId] ?? []).find(
entry => entry.artifactId === artifactId
);
@@ -2735,6 +2753,7 @@ const chatRuntimeSlice = createSlice({
error,
updatedAt: Date.now(),
toolCallId: toolCallId ?? existing?.toolCallId,
+ ownerRequestId: ownerFor(state, threadId, existing, requestId),
};
state.artifactsByThread[threadId] = upsertArtifact(
state.artifactsByThread[threadId],
@@ -2772,6 +2791,11 @@ const chatRuntimeSlice = createSlice({
activateArtifactTab: (state, action: PayloadAction<string>) => {
state.activeArtifactId = action.payload;
},
+ /** Close the preview panel and every tab in it (the header X). */
+ closeArtifactPanel: state => {
+ state.openArtifactIds = [];
+ state.activeArtifactId = null;
+ },
clearArtifactsForThread: (state, action: PayloadAction<{ threadId: string }>) => {
delete state.artifactsByThread[action.payload.threadId];
},
@@ -3320,6 +3344,7 @@ export const {
openArtifact,
closeArtifactTab,
activateArtifactTab,
+ closeArtifactPanel,
setQueueStatusForThread,
clearQueueStatusForThread,
beginInferenceTurn,