fix(webui): restore session-scoped file previews
This commit is contained in:
1 parent
1457904e8d
commit
af5acabb33
15 files changed
+564
-70
No files matched your search
@@ -319,6 +319,53 @@ async def _new_temporary_chat(
|
||||
return payload["chat_id"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_temporary_file_preview_is_owned_restricted_and_not_cached(bus, tmp_path) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
(workspace / "notes.txt").write_text("synthetic preview")
|
||||
outside = tmp_path / "outside.txt"
|
||||
outside.write_text("outside")
|
||||
sessions = SessionManager(workspace)
|
||||
channel = WebSocketChannel(
|
||||
{"enabled": True, "allowFrom": ["*"]}, bus,
|
||||
gateway=_basic_handler(
|
||||
bus, session_manager=sessions, workspace_path=workspace,
|
||||
default_restrict_to_workspace=False,
|
||||
),
|
||||
)
|
||||
owner, other = AsyncMock(), AsyncMock()
|
||||
chat_id = await _new_temporary_chat(channel, owner)
|
||||
channel._webui_connections.add(other)
|
||||
disk_before = {path for path in tmp_path.rglob("*") if path.is_file()}
|
||||
|
||||
async def preview(connection, path="notes.txt", probe=False):
|
||||
await channel._dispatch_envelope(connection, "webui-client", {
|
||||
"type": "webui_request", "request_id": "private-preview",
|
||||
"action": "temporary_chat.file_preview",
|
||||
"payload": {"chat_id": chat_id, "path": path, "probe": probe},
|
||||
})
|
||||
return json.loads(connection.send.await_args.args[0])
|
||||
|
||||
result = await preview(owner)
|
||||
assert result["ok"] is True
|
||||
assert result["result"]["content"] == "synthetic preview"
|
||||
assert (await preview(owner, probe=True))["result"] == {"available": True}
|
||||
assert (await preview(other))["error"]["status"] == 404
|
||||
assert (await preview(owner, str(outside)))["error"]["status"] == 403
|
||||
assert (await preview(owner, str(outside), probe=True))["result"] == {"available": False}
|
||||
assert (await preview(AsyncMock()))["error"]["status"] == 403
|
||||
assert not channel._webui_request_operations
|
||||
assert {path for path in tmp_path.rglob("*") if path.is_file()} == disk_before
|
||||
assert sessions.list_sessions() == []
|
||||
|
||||
await channel._dispatch_envelope(owner, "webui-client", {
|
||||
"type": "discard_temporary_chat", "chat_id": chat_id,
|
||||
})
|
||||
assert (await preview(owner))["error"]["status"] == 404
|
||||
assert not channel._webui_request_operations
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_attach_exposes_the_session_canonical_model_preset(bus, tmp_path) -> None:
|
||||
sessions = SessionManager(tmp_path)
|
||||
@@ -6171,6 +6218,7 @@ def test_handle_file_preview_returns_workspace_file(tmp_path) -> None:
|
||||
assert body["language"] == "python"
|
||||
assert body["content"].splitlines() == ["print('hello')"]
|
||||
assert body["truncated"] is False
|
||||
assert resp.headers["Cache-Control"] == "no-store"
|
||||
|
||||
|
||||
def test_handle_file_preview_probe_checks_availability_without_content(tmp_path) -> None:
|
||||
@@ -6198,6 +6246,7 @@ def test_handle_file_preview_probe_checks_availability_without_content(tmp_path)
|
||||
|
||||
assert resp.status_code == 200
|
||||
assert json.loads(resp.body.decode()) == {"available": True}
|
||||
assert resp.headers["Cache-Control"] == "no-store"
|
||||
|
||||
|
||||
def test_handle_file_preview_probe_reports_missing_file_as_unavailable(tmp_path) -> None:
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -12,6 +13,20 @@ from nanobot.security.workspace_access import WorkspaceScope
|
||||
from nanobot.security.workspace_policy import WorkspaceBoundaryError, resolve_allowed_path
|
||||
|
||||
MAX_FILE_PREVIEW_BYTES = 384 * 1024
|
||||
MAX_IMAGE_PREVIEW_BYTES = 8 * 1024 * 1024
|
||||
|
||||
|
||||
def _image_mime(prefix: bytes) -> str | None:
|
||||
# Only inert raster formats; SVG/HTML continue to be shown as source.
|
||||
if prefix.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||
return "image/png"
|
||||
if prefix.startswith(b"\xff\xd8\xff"):
|
||||
return "image/jpeg"
|
||||
if prefix.startswith((b"GIF87a", b"GIF89a")):
|
||||
return "image/gif"
|
||||
if prefix[:4] == b"RIFF" and prefix[8:12] == b"WEBP":
|
||||
return "image/webp"
|
||||
return None
|
||||
|
||||
|
||||
class WebUIFilePreviewError(ValueError):
|
||||
@@ -29,16 +44,36 @@ def file_preview_payload(
|
||||
scope: WorkspaceScope,
|
||||
max_bytes: int = MAX_FILE_PREVIEW_BYTES,
|
||||
) -> dict[str, Any]:
|
||||
"""Return a text preview for a file allowed by the session workspace scope."""
|
||||
"""Return a bounded source or raster preview within the session workspace scope."""
|
||||
|
||||
resolved = _resolve_preview_path(raw_path, scope=scope)
|
||||
|
||||
try:
|
||||
with open(resolved, "rb") as f:
|
||||
raw = f.read(max_bytes + 1)
|
||||
prefix = f.read(12)
|
||||
mime = _image_mime(prefix)
|
||||
limit = MAX_IMAGE_PREVIEW_BYTES if mime else max_bytes
|
||||
raw = prefix + f.read(max(0, limit + 1 - len(prefix)))
|
||||
size = resolved.stat().st_size
|
||||
except OSError as e:
|
||||
raise WebUIFilePreviewError(500, "failed to read file") from e
|
||||
|
||||
metadata = {
|
||||
"path": str(resolved),
|
||||
"display_path": _display_path(resolved, scope.project_path),
|
||||
"project_path": str(scope.project_path),
|
||||
"size": size,
|
||||
}
|
||||
if mime:
|
||||
if len(raw) > MAX_IMAGE_PREVIEW_BYTES:
|
||||
raise WebUIFilePreviewError(413, "image is too large to preview (maximum 8 MiB)")
|
||||
return {
|
||||
**metadata,
|
||||
"kind": "image",
|
||||
"mime_type": mime,
|
||||
"data_url": f"data:{mime};base64,{base64.b64encode(raw).decode('ascii')}",
|
||||
}
|
||||
|
||||
if b"\0" in raw[:4096]:
|
||||
raise WebUIFilePreviewError(415, "binary files cannot be previewed")
|
||||
|
||||
@@ -49,14 +84,11 @@ def file_preview_payload(
|
||||
except UnicodeDecodeError:
|
||||
content = preview_bytes.decode("utf-8", errors="replace")
|
||||
|
||||
display_path = _display_path(resolved, scope.project_path)
|
||||
return {
|
||||
"path": str(resolved),
|
||||
"display_path": display_path,
|
||||
"project_path": str(scope.project_path),
|
||||
**metadata,
|
||||
"kind": "text",
|
||||
"language": _language_for_path(resolved),
|
||||
"content": content,
|
||||
"size": resolved.stat().st_size,
|
||||
"truncated": truncated,
|
||||
}
|
||||
|
||||
@@ -66,15 +98,19 @@ def file_preview_availability_payload(
|
||||
*,
|
||||
scope: WorkspaceScope,
|
||||
) -> dict[str, bool]:
|
||||
"""Confirm that a path is a readable text preview candidate without loading it fully."""
|
||||
"""Probe a readable source or raster candidate without loading it fully."""
|
||||
|
||||
resolved = _resolve_preview_path(raw_path, scope=scope)
|
||||
try:
|
||||
with open(resolved, "rb") as f:
|
||||
prefix = f.read(4096)
|
||||
size = resolved.stat().st_size
|
||||
except OSError as e:
|
||||
raise WebUIFilePreviewError(500, "failed to read file") from e
|
||||
if b"\0" in prefix:
|
||||
if _image_mime(prefix):
|
||||
if size > MAX_IMAGE_PREVIEW_BYTES:
|
||||
raise WebUIFilePreviewError(413, "image is too large to preview (maximum 8 MiB)")
|
||||
elif b"\0" in prefix:
|
||||
raise WebUIFilePreviewError(415, "binary files cannot be previewed")
|
||||
return {"available": True}
|
||||
|
||||
|
||||
@@ -37,6 +37,11 @@ from nanobot.session.webui_turns import (
|
||||
from nanobot.utils.helpers import safe_filename
|
||||
from nanobot.utils.prompt_templates import render_template
|
||||
from nanobot.webui.cli_apps_api import normalize_cli_app_mentions
|
||||
from nanobot.webui.file_preview import (
|
||||
WebUIFilePreviewError,
|
||||
file_preview_availability_payload,
|
||||
file_preview_payload,
|
||||
)
|
||||
from nanobot.webui.forking import handle_webui_fork_chat
|
||||
from nanobot.webui.gateway_services import GatewayServices
|
||||
from nanobot.webui.mcp_presets_api import normalize_mcp_preset_mentions
|
||||
@@ -781,6 +786,41 @@ class WebUICommandRouter:
|
||||
)
|
||||
return
|
||||
|
||||
if action == "temporary_chat.file_preview":
|
||||
# Connection-owned, read-only, and deliberately outside the mutation
|
||||
# replay cache: private paths/content must not outlive this request.
|
||||
preview_payload = cast(dict[str, object], payload)
|
||||
chat_id = preview_payload.get("chat_id")
|
||||
path = preview_payload.get("path")
|
||||
probe = preview_payload.get("probe") is True
|
||||
if not isinstance(chat_id, str) or not isinstance(path, str):
|
||||
await self.send_webui_response(
|
||||
connection, request_id, status=400, message="invalid preview request",
|
||||
)
|
||||
return
|
||||
try:
|
||||
policy = self._temporary_chats.message_policy(connection, chat_id, "")
|
||||
if policy is None:
|
||||
raise TemporaryChatError("temporary_chat_unavailable")
|
||||
preview = file_preview_availability_payload if probe else file_preview_payload
|
||||
result = preview(path, scope=policy.workspace_scope)
|
||||
except TemporaryChatError as exc:
|
||||
await self.send_webui_response(
|
||||
connection, request_id, status=404, message=exc.detail,
|
||||
)
|
||||
except WebUIFilePreviewError as exc:
|
||||
if probe and exc.status in {400, 403, 404, 413, 415}:
|
||||
await self.send_webui_response(
|
||||
connection, request_id, result={"available": False},
|
||||
)
|
||||
else:
|
||||
await self.send_webui_response(
|
||||
connection, request_id, status=exc.status, message=exc.message,
|
||||
)
|
||||
else:
|
||||
await self.send_webui_response(connection, request_id, result=result)
|
||||
return
|
||||
|
||||
payload_digest = hashlib.sha256(
|
||||
json.dumps(
|
||||
payload,
|
||||
|
||||
@@ -1124,10 +1124,10 @@ class GatewayHTTPHandler:
|
||||
else:
|
||||
payload = file_preview_payload(path, scope=scope)
|
||||
except WebUIFilePreviewError as e:
|
||||
if is_probe and e.status in {400, 403, 404, 415}:
|
||||
return _http_json_response({"available": False})
|
||||
if is_probe and e.status in {400, 403, 404, 413, 415}:
|
||||
return _http_json_response({"available": False}, extra_headers=_NO_STORE_HEADERS)
|
||||
return _http_error(e.status, e.message)
|
||||
return _http_json_response(payload)
|
||||
return _http_json_response(payload, extra_headers=_NO_STORE_HEADERS)
|
||||
|
||||
def _handle_session_automations(self, request: WsRequest, key: str) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
|
||||
@@ -1,9 +1,80 @@
|
||||
import base64
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.security.workspace_access import default_workspace_scope
|
||||
from nanobot.webui.file_preview import WebUIFilePreviewError, file_preview_payload
|
||||
from nanobot.webui.file_preview import (
|
||||
WebUIFilePreviewError,
|
||||
file_preview_availability_payload,
|
||||
file_preview_payload,
|
||||
)
|
||||
|
||||
PNG = base64.b64decode(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/l9sAAAAASUVORK5CYII="
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("data", "mime"), [
|
||||
(PNG, "image/png"),
|
||||
(b"\xff\xd8\xff\xe0\0example", "image/jpeg"),
|
||||
(b"GIF89a\0example", "image/gif"),
|
||||
(b"RIFF\0\0\0\0WEBPexample", "image/webp"),
|
||||
])
|
||||
def test_raster_preview_uses_content_signature(tmp_path: Path, data: bytes, mime: str) -> None:
|
||||
# Extension must not determine the rendered MIME type.
|
||||
image = tmp_path / "figure.bin"
|
||||
image.write_bytes(data)
|
||||
scope = default_workspace_scope(tmp_path, restrict_to_workspace=True)
|
||||
assert file_preview_availability_payload("figure.bin", scope=scope) == {"available": True}
|
||||
result = file_preview_payload("figure.bin", scope=scope)
|
||||
assert result["kind"] == "image"
|
||||
assert result["mime_type"] == mime
|
||||
assert base64.b64decode(result["data_url"].split(",", 1)[1]) == data
|
||||
assert result["size"] == len(data)
|
||||
|
||||
|
||||
def test_large_raster_is_rejected_without_truncating(tmp_path: Path, monkeypatch) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.file_preview.MAX_IMAGE_PREVIEW_BYTES", 32)
|
||||
(tmp_path / "large.png").write_bytes(PNG)
|
||||
scope = default_workspace_scope(tmp_path, restrict_to_workspace=True)
|
||||
for read in (file_preview_payload, file_preview_availability_payload):
|
||||
with pytest.raises(WebUIFilePreviewError) as error:
|
||||
read("large.png", scope=scope)
|
||||
assert error.value.status == 413
|
||||
|
||||
|
||||
@pytest.mark.parametrize("filename", ["page.html", "drawing.svg", "disguised.png"])
|
||||
def test_active_content_is_only_source(tmp_path: Path, filename: str) -> None:
|
||||
content = "<script>window.example = true</script>"
|
||||
(tmp_path / filename).write_text(content)
|
||||
result = file_preview_payload(
|
||||
filename, scope=default_workspace_scope(tmp_path, restrict_to_workspace=True),
|
||||
)
|
||||
assert result["kind"] == "text"
|
||||
assert result["content"] == content
|
||||
|
||||
|
||||
def test_text_truncation_is_unchanged(tmp_path: Path) -> None:
|
||||
(tmp_path / "notes.txt").write_text("abcdefghijklm")
|
||||
result = file_preview_payload(
|
||||
"notes.txt", scope=default_workspace_scope(tmp_path, restrict_to_workspace=True), max_bytes=5,
|
||||
)
|
||||
assert result["content"] == "abcde"
|
||||
assert result["truncated"] is True
|
||||
|
||||
|
||||
def test_raster_symlink_cannot_escape_workspace(tmp_path: Path) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
image = tmp_path / "outside.png"
|
||||
image.write_bytes(PNG)
|
||||
(workspace / "linked.png").symlink_to(image)
|
||||
with pytest.raises(WebUIFilePreviewError) as error:
|
||||
file_preview_payload(
|
||||
"linked.png", scope=default_workspace_scope(workspace, restrict_to_workspace=True),
|
||||
)
|
||||
assert error.value.status == 403
|
||||
|
||||
|
||||
def test_restricted_preview_allows_media_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
|
||||
+13
-4
@@ -64,6 +64,7 @@ import { displayTitle, sortSessions } from "@/lib/chat-groups";
|
||||
import { deriveTitle } from "@/lib/format";
|
||||
import { NanobotClient } from "@/lib/nanobot-client";
|
||||
import { ThreadMessageCache } from "@/lib/thread-message-cache";
|
||||
import { FilePreviewStore } from "@/hooks/useFilePreviewState";
|
||||
import { ClientProvider, useClient } from "@/providers/ClientProvider";
|
||||
import type {
|
||||
BootstrapResponse,
|
||||
@@ -1217,16 +1218,20 @@ function Shell({
|
||||
// Pane shells can unmount during navigation. Keep replay state for this app
|
||||
// session, pinning temporary chats because they cannot reload disk history.
|
||||
const retainedTemporaryChatIdsRef = useRef(new Set<string>());
|
||||
const [filePreviewStore] = useState(() => new FilePreviewStore());
|
||||
const [threadMessageCache] = useState(() => new ThreadMessageCache(
|
||||
(key) => retainedTemporaryChatIdsRef.current.has(key),
|
||||
));
|
||||
useEffect(() => {
|
||||
const retained = new Set(temporaryChatIds);
|
||||
for (const chatId of retainedTemporaryChatIdsRef.current) {
|
||||
if (!retained.has(chatId)) threadMessageCache.delete(chatId);
|
||||
if (!retained.has(chatId)) {
|
||||
threadMessageCache.delete(chatId);
|
||||
filePreviewStore.delete(`websocket:${chatId}`);
|
||||
}
|
||||
}
|
||||
retainedTemporaryChatIdsRef.current = retained;
|
||||
}, [temporaryChatIds, threadMessageCache]);
|
||||
}, [temporaryChatIds, threadMessageCache, filePreviewStore]);
|
||||
|
||||
const navigate = useCallback(
|
||||
(route: ShellRoute, options?: { replace?: boolean }) => {
|
||||
@@ -2195,6 +2200,7 @@ function Shell({
|
||||
}
|
||||
if (!wasOpen) return;
|
||||
wasOpen = false;
|
||||
filePreviewStore.clear();
|
||||
if (Object.keys(temporarySessionsRef.current).length === 0) return;
|
||||
temporarySessionsRef.current = {};
|
||||
setTemporarySessions({});
|
||||
@@ -2202,7 +2208,7 @@ function Shell({
|
||||
navigate(defaultShellRoute(), { replace: true });
|
||||
}
|
||||
});
|
||||
}, [client, navigate]);
|
||||
}, [client, navigate, filePreviewStore]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
@@ -2297,6 +2303,7 @@ function Shell({
|
||||
});
|
||||
return;
|
||||
}
|
||||
filePreviewStore.delete(item.key);
|
||||
}
|
||||
setPendingDelete(null);
|
||||
if (deletingActive) {
|
||||
@@ -2309,7 +2316,7 @@ function Shell({
|
||||
} catch (e) {
|
||||
console.error("Failed to delete session", e);
|
||||
}
|
||||
}, [pendingDelete, deleteChat, activeKey, activeTabState, navigate, topicSessions]);
|
||||
}, [pendingDelete, deleteChat, activeKey, activeTabState, navigate, topicSessions, filePreviewStore]);
|
||||
|
||||
const onRequestDeleteMany = useCallback(async (items: SidebarDeleteItem[]) => {
|
||||
const uniqueItems = Array.from(new Map(items.map((item) => [item.key, item])).values());
|
||||
@@ -2872,6 +2879,7 @@ function Shell({
|
||||
temporary={temporaryChatRequested}
|
||||
temporaryChatIds={temporaryChatIds}
|
||||
messageCache={threadMessageCache}
|
||||
filePreviewStore={filePreviewStore}
|
||||
temporaryChatEnabled={temporaryChatEnabled}
|
||||
onTemporaryChatEnabledChange={
|
||||
!activeKey ? onTemporaryChatEnabledChange : undefined
|
||||
@@ -2918,6 +2926,7 @@ function Shell({
|
||||
title={pane.title}
|
||||
temporaryChatIds={temporaryChatIds}
|
||||
messageCache={threadMessageCache}
|
||||
filePreviewStore={filePreviewStore}
|
||||
onToggleSidebar={toggleSidebar}
|
||||
onNewChat={onNewChat}
|
||||
onCreateChat={onCreateChat}
|
||||
|
||||
@@ -13,6 +13,7 @@ interface FilePreviewPanelProps {
|
||||
sessionKey: string;
|
||||
path: string;
|
||||
token: string;
|
||||
loadPreview?: (path: string) => Promise<FilePreviewPayload>;
|
||||
desktopWidth?: number;
|
||||
isClosing?: boolean;
|
||||
onResizeStart?: (event: ReactPointerEvent<HTMLButtonElement>) => void;
|
||||
@@ -28,6 +29,7 @@ export function FilePreviewPanel({
|
||||
sessionKey,
|
||||
path,
|
||||
token,
|
||||
loadPreview,
|
||||
desktopWidth = 544,
|
||||
isClosing = false,
|
||||
onResizeStart,
|
||||
@@ -38,6 +40,8 @@ export function FilePreviewPanel({
|
||||
const [entered, setEntered] = useState(false);
|
||||
const tokenRef = useRef(token);
|
||||
tokenRef.current = token;
|
||||
const loadPreviewRef = useRef(loadPreview);
|
||||
loadPreviewRef.current = loadPreview;
|
||||
|
||||
useEffect(() => {
|
||||
const frame = window.requestAnimationFrame(() => setEntered(true));
|
||||
@@ -47,7 +51,7 @@ export function FilePreviewPanel({
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setState({ status: "loading" });
|
||||
fetchFilePreview(tokenRef.current, sessionKey, path)
|
||||
(loadPreviewRef.current?.(path) ?? fetchFilePreview(tokenRef.current, sessionKey, path))
|
||||
.then((payload) => {
|
||||
if (!cancelled) setState({ status: "ready", payload });
|
||||
})
|
||||
@@ -102,9 +106,10 @@ export function FilePreviewPanel({
|
||||
style={{
|
||||
"--file-preview-width": `${desktopWidth}px`,
|
||||
"--file-preview-slot-width": !entered || isClosing ? "0px" : `${desktopWidth}px`,
|
||||
"--file-preview-mobile-width": !entered || isClosing ? "0px" : "100%",
|
||||
} as CSSProperties}
|
||||
className={cn(
|
||||
"absolute inset-y-0 right-0 z-30 w-[min(100vw,var(--file-preview-slot-width))] overflow-hidden",
|
||||
"absolute inset-y-0 right-0 z-30 w-[var(--file-preview-mobile-width)] overflow-hidden",
|
||||
"transition-[width] duration-300 ease-out will-change-[width]",
|
||||
"md:relative md:z-auto md:w-[var(--file-preview-slot-width)] md:min-w-0 md:shrink-0",
|
||||
isClosing && "pointer-events-none",
|
||||
@@ -114,7 +119,7 @@ export function FilePreviewPanel({
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"absolute inset-y-0 right-0 flex w-[min(100vw,var(--file-preview-width))] flex-col overflow-hidden pb-[env(safe-area-inset-bottom)] md:w-[var(--file-preview-width)] md:pb-0",
|
||||
"absolute inset-y-0 right-0 flex w-screen flex-col overflow-hidden pb-[env(safe-area-inset-bottom)] md:w-[var(--file-preview-width)] md:pb-0",
|
||||
"border-l border-border/70 bg-background shadow-2xl md:shadow-none",
|
||||
"transition-[opacity,transform] duration-300 ease-out will-change-transform",
|
||||
!entered || isClosing ? "translate-x-full opacity-0" : "translate-x-0 opacity-100",
|
||||
@@ -228,6 +233,15 @@ export function FilePreviewPanel({
|
||||
<p>{errorMessage}</p>
|
||||
</div>
|
||||
</div>
|
||||
) : state.payload.kind === "image" ? (
|
||||
<div className="flex min-h-full items-center justify-center p-4">
|
||||
<img
|
||||
src={state.payload.data_url}
|
||||
alt={fileName}
|
||||
className="max-h-full max-w-full object-contain"
|
||||
onError={() => setState({ status: "error", error: new Error("Invalid image") })}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="min-h-full">
|
||||
{state.payload.truncated ? (
|
||||
|
||||
@@ -75,15 +75,16 @@ export function FileReferenceChip({
|
||||
onKeyDown={interactive ? onKeyDown : undefined}
|
||||
className={cn(
|
||||
"inline-flex max-w-full items-baseline gap-[0.28em] font-medium leading-[inherit]",
|
||||
"text-sky-600 transition-colors hover:text-sky-700",
|
||||
"dark:text-sky-300 dark:hover:text-sky-200",
|
||||
interactive
|
||||
? "text-sky-600 transition-colors hover:text-sky-700 dark:text-sky-300 dark:hover:text-sky-200"
|
||||
: "text-muted-foreground",
|
||||
interactive && [
|
||||
"cursor-pointer rounded-compact",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400/45",
|
||||
],
|
||||
)}
|
||||
>
|
||||
<FileReferenceIcon kind={kind} />
|
||||
<FileReferenceIcon kind={kind} interactive={interactive} />
|
||||
<span
|
||||
data-sheen-text={active ? displayText : undefined}
|
||||
className={cn(
|
||||
@@ -95,7 +96,7 @@ export function FileReferenceChip({
|
||||
{display === "path" && directory ? (
|
||||
<>
|
||||
<span className="text-muted-foreground/65">{directory}</span>
|
||||
<span className="font-semibold text-sky-700 dark:text-sky-200">{name}</span>
|
||||
<span className={cn("font-semibold", interactive && "text-sky-700 dark:text-sky-200")}>{name}</span>
|
||||
</>
|
||||
) : (
|
||||
displayText
|
||||
@@ -193,7 +194,7 @@ function fileKindForPath(path: string): FileReferenceKind {
|
||||
}
|
||||
}
|
||||
|
||||
function FileReferenceIcon({ kind }: { kind: FileReferenceKind }) {
|
||||
function FileReferenceIcon({ kind, interactive }: { kind: FileReferenceKind; interactive: boolean }) {
|
||||
if (kind === "python") {
|
||||
return (
|
||||
<svg
|
||||
@@ -218,7 +219,7 @@ function FileReferenceIcon({ kind }: { kind: FileReferenceKind }) {
|
||||
return (
|
||||
<svg
|
||||
aria-hidden
|
||||
className="h-[0.92em] w-[0.92em] shrink-0 translate-y-[0.11em] text-sky-500 dark:text-sky-300"
|
||||
className={cn("h-[0.92em] w-[0.92em] shrink-0 translate-y-[0.11em]", interactive && "text-sky-500 dark:text-sky-300")}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
@@ -237,7 +238,7 @@ function FileReferenceIcon({ kind }: { kind: FileReferenceKind }) {
|
||||
return (
|
||||
<svg
|
||||
aria-hidden
|
||||
className="h-[0.92em] w-[0.92em] shrink-0 translate-y-[0.11em] text-sky-500 dark:text-sky-300"
|
||||
className={cn("h-[0.92em] w-[0.92em] shrink-0 translate-y-[0.11em]", interactive && "text-sky-500 dark:text-sky-300")}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
@@ -254,7 +255,7 @@ function FileReferenceIcon({ kind }: { kind: FileReferenceKind }) {
|
||||
return (
|
||||
<svg
|
||||
aria-hidden
|
||||
className="h-[0.96em] w-[0.96em] shrink-0 translate-y-[0.12em] text-sky-500 dark:text-sky-300"
|
||||
className={cn("h-[0.96em] w-[0.96em] shrink-0 translate-y-[0.12em]", interactive && "text-sky-500 dark:text-sky-300")}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
>
|
||||
|
||||
@@ -24,6 +24,7 @@ import { StreamErrorNotice } from "@/components/thread/StreamErrorNotice";
|
||||
import { ThreadViewport, type ThreadViewportHandle } from "@/components/thread/ThreadViewport";
|
||||
import { useNanobotStream, type SendAttachment, type SendOptions } from "@/hooks/useNanobotStream";
|
||||
import { useSessionHistory } from "@/hooks/useSessions";
|
||||
import { useFilePreviewState, type FilePreviewStore } from "@/hooks/useFilePreviewState";
|
||||
import {
|
||||
ApiError,
|
||||
fetchFilePreviewAvailability,
|
||||
@@ -46,6 +47,7 @@ import {
|
||||
import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client";
|
||||
import type {
|
||||
ChatSummary,
|
||||
FilePreviewPayload,
|
||||
RoundUsage,
|
||||
SettingsPayload,
|
||||
SlashCommand,
|
||||
@@ -383,9 +385,12 @@ function clampFilePreviewWidth(width: number, maxWidth: number): number {
|
||||
}
|
||||
|
||||
function maxFilePreviewWidth(containerWidth: number): number {
|
||||
return Math.max(
|
||||
FILE_PREVIEW_MIN_WIDTH,
|
||||
Math.min(FILE_PREVIEW_MAX_WIDTH, containerWidth - FILE_PREVIEW_MIN_MAIN_WIDTH),
|
||||
return Math.min(
|
||||
containerWidth > 0 ? containerWidth : FILE_PREVIEW_MIN_WIDTH,
|
||||
Math.max(
|
||||
FILE_PREVIEW_MIN_WIDTH,
|
||||
Math.min(FILE_PREVIEW_MAX_WIDTH, containerWidth - FILE_PREVIEW_MIN_MAIN_WIDTH),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -396,6 +401,7 @@ interface ThreadShellProps {
|
||||
temporary?: boolean;
|
||||
temporaryChatIds?: readonly string[];
|
||||
messageCache?: ThreadMessageCache;
|
||||
filePreviewStore?: FilePreviewStore;
|
||||
temporaryChatEnabled?: boolean;
|
||||
onTemporaryChatEnabledChange?: (enabled: boolean) => void;
|
||||
onToggleSidebar: () => void;
|
||||
@@ -611,6 +617,7 @@ export function ThreadShell({
|
||||
temporary = false,
|
||||
temporaryChatIds = [],
|
||||
messageCache,
|
||||
filePreviewStore,
|
||||
temporaryChatEnabled = false,
|
||||
onTemporaryChatEnabledChange,
|
||||
onToggleSidebar,
|
||||
@@ -647,6 +654,7 @@ export function ThreadShell({
|
||||
const { t } = useTranslation();
|
||||
const chatId = session?.chatId ?? null;
|
||||
const historyKey = temporary ? null : session?.key ?? null;
|
||||
const previewSessionKey = session?.key ?? null;
|
||||
const mentionSessions = useMemo(
|
||||
() => sessions.filter((candidate) => candidate.key !== historyKey),
|
||||
[historyKey, sessions],
|
||||
@@ -702,15 +710,21 @@ export function ThreadShell({
|
||||
} | null>(null);
|
||||
const [heroGreetingKey, setHeroGreetingKey] = useState(randomHeroGreetingKey);
|
||||
const [submittedViewportTurnId, setSubmittedViewportTurnId] = useState<string | null>(null);
|
||||
const [filePreviewPath, setFilePreviewPath] = useState<string | null>(null);
|
||||
const [filePreviewClosing, setFilePreviewClosing] = useState(false);
|
||||
const [filePreviewWidth, setFilePreviewWidth] = useState(FILE_PREVIEW_DEFAULT_WIDTH);
|
||||
const { state: previewState, setPath: setFilePreviewPath, setWidth: setFilePreviewWidth } =
|
||||
useFilePreviewState(previewSessionKey, filePreviewStore);
|
||||
const [closingPreview, setClosingPreview] = useState<{ key: string; path: string } | null>(null);
|
||||
const filePreviewClosing = closingPreview?.key === previewSessionKey;
|
||||
const filePreviewPath = previewState.path
|
||||
?? (filePreviewClosing ? closingPreview?.path ?? null : null);
|
||||
const [filePreviewMaxWidth, setFilePreviewMaxWidth] = useState(FILE_PREVIEW_MAX_WIDTH);
|
||||
const filePreviewWidth = clampFilePreviewWidth(previewState.width, filePreviewMaxWidth);
|
||||
const [quotedContext, setQuotedContext] = useState<string | null>(null);
|
||||
const [composerFocusSignal, setComposerFocusSignal] = useState(0);
|
||||
const shellRef = useRef<HTMLElement | null>(null);
|
||||
const composerSurfaceRef = useRef<HTMLDivElement | null>(null);
|
||||
const filePreviewWidthRef = useRef(FILE_PREVIEW_DEFAULT_WIDTH);
|
||||
const filePreviewCloseTimerRef = useRef<number | null>(null);
|
||||
const filePreviewResizeCleanupRef = useRef<(() => void) | null>(null);
|
||||
const pendingFirstRef = useRef<PendingFirstMessage | null>(null);
|
||||
const [pendingFirstTargetChatId, setPendingFirstTargetChatId] = useState<string | null>(null);
|
||||
const consumedPendingFirstMessageIdRef = useRef<string | null>(null);
|
||||
@@ -835,15 +849,15 @@ export function ThreadShell({
|
||||
}, [filePreviewWidth]);
|
||||
|
||||
useEffect(() => {
|
||||
filePreviewResizeCleanupRef.current?.();
|
||||
if (filePreviewCloseTimerRef.current !== null) {
|
||||
window.clearTimeout(filePreviewCloseTimerRef.current);
|
||||
filePreviewCloseTimerRef.current = null;
|
||||
}
|
||||
setFilePreviewClosing(false);
|
||||
setFilePreviewPath(null);
|
||||
setClosingPreview(null);
|
||||
setQuotedContext(null);
|
||||
setSubmittedViewportTurnId(null);
|
||||
}, [historyKey]);
|
||||
}, [previewSessionKey]);
|
||||
|
||||
useEffect(() => {
|
||||
const retained = new Set(temporaryChatIds);
|
||||
@@ -865,6 +879,7 @@ export function ThreadShell({
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
filePreviewResizeCleanupRef.current?.();
|
||||
if (filePreviewCloseTimerRef.current !== null) {
|
||||
window.clearTimeout(filePreviewCloseTimerRef.current);
|
||||
}
|
||||
@@ -917,11 +932,11 @@ export function ThreadShell({
|
||||
}, [chatId, messagesReady, rememberedViewportTurnId, turnActive]);
|
||||
const filePreviewAvailabilityCache = useMemo(
|
||||
() => new Map<string, FilePreviewAvailabilityCacheEntry>(),
|
||||
[historyKey],
|
||||
[previewSessionKey],
|
||||
);
|
||||
const filePreviewAvailabilityRevision = displayMessages.length;
|
||||
const resolveFilePreviewAvailability = useCallback((path: string) => {
|
||||
if (!historyKey) return Promise.resolve(false);
|
||||
if (!previewSessionKey) return Promise.resolve(false);
|
||||
const cached = filePreviewAvailabilityCache.get(path);
|
||||
if (
|
||||
cached
|
||||
@@ -929,13 +944,18 @@ export function ThreadShell({
|
||||
) {
|
||||
return cached.promise;
|
||||
}
|
||||
const pending = fetchFilePreviewAvailability(getToken(), historyKey, path).catch(
|
||||
const request = temporary
|
||||
? client.requestMutation<{ available: boolean }>("temporary_chat.file_preview", {
|
||||
chat_id: chatId, path, probe: true,
|
||||
}).then((result) => result.available)
|
||||
: fetchFilePreviewAvailability(getToken(), previewSessionKey, path);
|
||||
const pending = request.catch(
|
||||
(error: unknown) => {
|
||||
if (error instanceof ApiError) {
|
||||
if (error.status === 404 && /API route not found/i.test(error.message)) {
|
||||
return true;
|
||||
}
|
||||
if ([400, 403, 404, 415].includes(error.status)) return false;
|
||||
if ([400, 403, 404, 413, 415].includes(error.status)) return false;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
@@ -955,7 +975,10 @@ export function ThreadShell({
|
||||
filePreviewAvailabilityCache,
|
||||
filePreviewAvailabilityRevision,
|
||||
getToken,
|
||||
historyKey,
|
||||
previewSessionKey,
|
||||
temporary,
|
||||
client,
|
||||
chatId,
|
||||
]);
|
||||
|
||||
const showHeroComposer = displayMessages.length === 0 && !loading;
|
||||
@@ -1462,26 +1485,62 @@ export function ThreadShell({
|
||||
[chatId, send, withWorkspaceScope],
|
||||
);
|
||||
|
||||
const loadTemporaryFilePreview = useCallback((path: string) =>
|
||||
client.requestMutation<FilePreviewPayload>("temporary_chat.file_preview", {
|
||||
chat_id: chatId, path,
|
||||
}).catch((error: unknown) => {
|
||||
if (error instanceof Error && "status" in error && typeof error.status === "number") {
|
||||
throw new ApiError(error.status, error.message);
|
||||
}
|
||||
throw error;
|
||||
}), [client, chatId]);
|
||||
|
||||
const handleCloseFilePreview = useCallback(() => {
|
||||
if (!previewSessionKey || !filePreviewPath || filePreviewClosing) return;
|
||||
filePreviewResizeCleanupRef.current?.();
|
||||
setClosingPreview({ key: previewSessionKey, path: filePreviewPath });
|
||||
// Record the closed state immediately, even if navigation interrupts the animation.
|
||||
setFilePreviewPath(null);
|
||||
filePreviewCloseTimerRef.current = window.setTimeout(() => {
|
||||
filePreviewCloseTimerRef.current = null;
|
||||
setClosingPreview(null);
|
||||
}, FILE_PREVIEW_CLOSE_ANIMATION_MS);
|
||||
}, [previewSessionKey, filePreviewClosing, filePreviewPath, setFilePreviewPath]);
|
||||
|
||||
const handleOpenFilePreview = useCallback((path: string) => {
|
||||
if (path === filePreviewPath && !filePreviewClosing) {
|
||||
handleCloseFilePreview();
|
||||
return;
|
||||
}
|
||||
if (filePreviewCloseTimerRef.current !== null) {
|
||||
window.clearTimeout(filePreviewCloseTimerRef.current);
|
||||
filePreviewCloseTimerRef.current = null;
|
||||
}
|
||||
setFilePreviewClosing(false);
|
||||
setClosingPreview(null);
|
||||
setFilePreviewPath(path);
|
||||
}, []);
|
||||
}, [filePreviewPath, filePreviewClosing, handleCloseFilePreview, setFilePreviewPath]);
|
||||
|
||||
const handleCloseFilePreview = useCallback(() => {
|
||||
if (!filePreviewPath || filePreviewClosing) return;
|
||||
setFilePreviewClosing(true);
|
||||
filePreviewCloseTimerRef.current = window.setTimeout(() => {
|
||||
filePreviewCloseTimerRef.current = null;
|
||||
setFilePreviewPath(null);
|
||||
setFilePreviewClosing(false);
|
||||
}, FILE_PREVIEW_CLOSE_ANIMATION_MS);
|
||||
}, [filePreviewClosing, filePreviewPath]);
|
||||
// Markdown blocks can retain rendered links while their text is unchanged.
|
||||
// Keep their callback stable, but always act on the current pane/session state.
|
||||
const openFilePreviewRef = useRef(handleOpenFilePreview);
|
||||
openFilePreviewRef.current = handleOpenFilePreview;
|
||||
const openFilePreview = useCallback((path: string) => openFilePreviewRef.current(path), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!filePreviewPath || !headerActive) return;
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Escape" || event.defaultPrevented || event.isComposing) return;
|
||||
// Let a dialog/menu above the pane consume Escape without closing this preview.
|
||||
if (document.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"], [data-radix-popper-content-wrapper]')) return;
|
||||
event.preventDefault();
|
||||
handleCloseFilePreview();
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [filePreviewPath, headerActive, handleCloseFilePreview]);
|
||||
|
||||
const handleFilePreviewResizeStart = useCallback((event: ReactPointerEvent<HTMLButtonElement>) => {
|
||||
filePreviewResizeCleanupRef.current?.();
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const panel = event.currentTarget.closest<HTMLElement>("[data-file-preview-panel]");
|
||||
@@ -1512,7 +1571,7 @@ export function ThreadShell({
|
||||
moveEvent.preventDefault();
|
||||
applyWidth(moveEvent.clientX);
|
||||
};
|
||||
const handlePointerUp = () => {
|
||||
const stopResize = (commit: boolean) => {
|
||||
if (frame !== null) {
|
||||
window.cancelAnimationFrame(frame);
|
||||
frame = null;
|
||||
@@ -1520,32 +1579,36 @@ export function ThreadShell({
|
||||
panel?.style.setProperty("--file-preview-width", `${nextWidth}px`);
|
||||
panel?.style.setProperty("--file-preview-slot-width", `${nextWidth}px`);
|
||||
if (panel) panel.style.transition = originalPanelTransition;
|
||||
setFilePreviewWidth(nextWidth);
|
||||
if (commit) setFilePreviewWidth(nextWidth);
|
||||
document.body.style.cursor = originalBodyCursor;
|
||||
document.body.style.userSelect = originalBodyUserSelect;
|
||||
window.removeEventListener("pointermove", handlePointerMove);
|
||||
window.removeEventListener("pointerup", handlePointerUp);
|
||||
window.removeEventListener("pointercancel", handlePointerUp);
|
||||
filePreviewResizeCleanupRef.current = null;
|
||||
};
|
||||
const handlePointerUp = () => stopResize(true);
|
||||
filePreviewResizeCleanupRef.current = () => stopResize(false);
|
||||
|
||||
applyWidth(event.clientX);
|
||||
window.addEventListener("pointermove", handlePointerMove);
|
||||
window.addEventListener("pointerup", handlePointerUp);
|
||||
window.addEventListener("pointercancel", handlePointerUp);
|
||||
}, []);
|
||||
}, [setFilePreviewWidth]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!filePreviewPath) return;
|
||||
const clampToShell = () => {
|
||||
const shellWidth = shellRef.current?.getBoundingClientRect().width ?? window.innerWidth;
|
||||
const maxWidth = maxFilePreviewWidth(shellWidth);
|
||||
const nextWidth = clampFilePreviewWidth(filePreviewWidthRef.current, maxWidth);
|
||||
filePreviewWidthRef.current = nextWidth;
|
||||
setFilePreviewWidth(nextWidth);
|
||||
setFilePreviewMaxWidth(maxWidth);
|
||||
};
|
||||
clampToShell();
|
||||
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(clampToShell);
|
||||
if (shellRef.current) observer?.observe(shellRef.current);
|
||||
window.addEventListener("resize", clampToShell);
|
||||
return () => {
|
||||
observer?.disconnect();
|
||||
window.removeEventListener("resize", clampToShell);
|
||||
};
|
||||
}, [filePreviewPath]);
|
||||
@@ -1749,7 +1812,7 @@ export function ThreadShell({
|
||||
) : null}
|
||||
{headerPortalTarget === undefined ? threadHeader : null}
|
||||
<FilePreviewAvailabilityProvider
|
||||
resolve={historyKey ? resolveFilePreviewAvailability : undefined}
|
||||
resolve={previewSessionKey ? resolveFilePreviewAvailability : undefined}
|
||||
>
|
||||
<ThreadViewport
|
||||
ref={viewportRef}
|
||||
@@ -1775,7 +1838,7 @@ export function ThreadShell({
|
||||
onLoadOlder={loadOlder}
|
||||
traceDetailScope={historyKey}
|
||||
onLoadTraceDetails={messagesReady ? loadTraceDetails : undefined}
|
||||
onOpenFilePreview={historyKey ? handleOpenFilePreview : undefined}
|
||||
onOpenFilePreview={previewSessionKey ? openFilePreview : undefined}
|
||||
onForkFromMessage={onForkChat ? handleForkFromMessage : undefined}
|
||||
onQuoteSelection={session ? handleQuoteSelection : undefined}
|
||||
/>
|
||||
@@ -1794,11 +1857,13 @@ export function ThreadShell({
|
||||
</div>,
|
||||
composerPortalTarget,
|
||||
) : null}
|
||||
{filePreviewPath && historyKey ? (
|
||||
{filePreviewPath && previewSessionKey ? (
|
||||
<FilePreviewPanel
|
||||
sessionKey={historyKey}
|
||||
key={`${previewSessionKey}:${filePreviewPath}`}
|
||||
sessionKey={previewSessionKey}
|
||||
path={filePreviewPath}
|
||||
token={token}
|
||||
loadPreview={temporary ? loadTemporaryFilePreview : undefined}
|
||||
desktopWidth={filePreviewWidth}
|
||||
isClosing={filePreviewClosing}
|
||||
onResizeStart={handleFilePreviewResizeStart}
|
||||
|
||||
@@ -607,6 +607,11 @@
|
||||
.thread-workspace {
|
||||
container: thread-workspace / inline-size;
|
||||
}
|
||||
/* The full-width toolbar must not cover the preview breadcrumb or close button. */
|
||||
.thread-workspace:has([data-file-preview-panel]) > * {
|
||||
--thread-header-position: relative;
|
||||
--thread-prompt-inset: 1rem;
|
||||
}
|
||||
/* Keep room for the 49.5rem message column and controls in the side margin. */
|
||||
@container thread-workspace (max-width: 72rem) {
|
||||
.thread-workspace > * {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { useCallback, useState, useSyncExternalStore } from "react";
|
||||
|
||||
interface FilePreviewState {
|
||||
path: string | null;
|
||||
width: number;
|
||||
}
|
||||
|
||||
const EMPTY_PREVIEW: FilePreviewState = { path: null, width: 544 };
|
||||
|
||||
/** App-lifetime view state only. Never stores file contents or writes to browser storage. */
|
||||
export class FilePreviewStore {
|
||||
private states = new Map<string, FilePreviewState>();
|
||||
private listeners = new Set<() => void>();
|
||||
|
||||
subscribe = (listener: () => void) => {
|
||||
this.listeners.add(listener);
|
||||
return () => { this.listeners.delete(listener); };
|
||||
};
|
||||
|
||||
get(key: string | null): FilePreviewState {
|
||||
return key ? this.states.get(key) ?? EMPTY_PREVIEW : EMPTY_PREVIEW;
|
||||
}
|
||||
|
||||
update(key: string, patch: Partial<FilePreviewState>) {
|
||||
const previous = this.get(key);
|
||||
const next = { ...previous, ...patch };
|
||||
if (previous.path === next.path && previous.width === next.width) return;
|
||||
this.states.set(key, next);
|
||||
this.listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
delete(key: string) {
|
||||
if (this.states.delete(key)) this.listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.states.clear();
|
||||
this.listeners.forEach((listener) => listener());
|
||||
}
|
||||
}
|
||||
|
||||
export function useFilePreviewState(key: string | null, sharedStore?: FilePreviewStore) {
|
||||
const [localStore] = useState(() => new FilePreviewStore());
|
||||
const store = sharedStore ?? localStore;
|
||||
const snapshot = useCallback(() => store.get(key), [key, store]);
|
||||
const state = useSyncExternalStore(store.subscribe, snapshot, snapshot);
|
||||
const setPath = useCallback((path: string | null) => {
|
||||
if (key) store.update(key, { path });
|
||||
}, [key, store]);
|
||||
const setWidth = useCallback((width: number) => {
|
||||
if (key) store.update(key, { width });
|
||||
}, [key, store]);
|
||||
return { state, setPath, setWidth };
|
||||
}
|
||||
@@ -455,7 +455,7 @@ export async function fetchFilePreview(
|
||||
return request<FilePreviewPayload>(
|
||||
`${base}/api/sessions/${encodeURIComponent(key)}/file-preview?${query}`,
|
||||
token,
|
||||
undefined,
|
||||
{ cache: "no-store" },
|
||||
API_READ_TIMEOUT_MS,
|
||||
);
|
||||
}
|
||||
@@ -472,7 +472,7 @@ export async function fetchFilePreviewAvailability(
|
||||
const payload = await request<{ available?: boolean }>(
|
||||
`${base}/api/sessions/${encodeURIComponent(key)}/file-preview?${query}`,
|
||||
token,
|
||||
undefined,
|
||||
{ cache: "no-store" },
|
||||
API_READ_TIMEOUT_MS,
|
||||
);
|
||||
return payload.available !== false;
|
||||
|
||||
@@ -1607,16 +1607,18 @@ export interface WebuiThreadTraceDetailPayload {
|
||||
events: ThreadProjectionEvent[];
|
||||
}
|
||||
|
||||
export interface FilePreviewPayload {
|
||||
interface FilePreviewMetadata {
|
||||
path: string;
|
||||
display_path: string;
|
||||
project_path: string;
|
||||
language: string;
|
||||
content: string;
|
||||
size: number;
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
export type FilePreviewPayload = FilePreviewMetadata & (
|
||||
| { kind?: "text"; language: string; content: string; truncated: boolean }
|
||||
| { kind: "image"; mime_type: string; data_url: string }
|
||||
);
|
||||
|
||||
export type Outbound =
|
||||
| { type: "new_chat"; workspace_scope?: WorkspaceScopePayload }
|
||||
| { type: "new_temporary_chat" }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { act, render, screen } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
@@ -40,6 +40,36 @@ describe("FilePreviewPanel", () => {
|
||||
vi.mocked(fetchFilePreview).mockReset();
|
||||
});
|
||||
|
||||
it("renders a raster instead of source and reports failed image decoding", async () => {
|
||||
const dataUrl = "data:image/png;base64,example";
|
||||
vi.mocked(fetchFilePreview).mockResolvedValue({
|
||||
kind: "image", path: "/workspace/chart.png", display_path: "chart.png",
|
||||
project_path: "/workspace", size: 42, mime_type: "image/png", data_url: dataUrl,
|
||||
});
|
||||
render(<FilePreviewPanel sessionKey="websocket:a" path="chart.png" token="test" onClose={() => {}} />);
|
||||
const img = await screen.findByRole("img", { name: "chart.png" });
|
||||
expect(img).toHaveAttribute("src", dataUrl);
|
||||
expect(screen.queryByTestId("mock-code-block")).not.toBeInTheDocument();
|
||||
fireEvent.error(img);
|
||||
expect(await screen.findByText("Could not preview this file.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("ignores a late response after changing session", async () => {
|
||||
let resolveFirst!: (payload: import("@/lib/types").FilePreviewPayload) => void;
|
||||
vi.mocked(fetchFilePreview).mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve; }));
|
||||
const payload = {
|
||||
path: "/workspace/b.txt", display_path: "b.txt", project_path: "/workspace",
|
||||
language: "text", content: "session B", truncated: false, size: 9,
|
||||
};
|
||||
vi.mocked(fetchFilePreview).mockResolvedValueOnce(payload);
|
||||
const view = (key: string) => <FilePreviewPanel key={key} sessionKey={key} path="notes.txt" token="test" onClose={() => {}} />;
|
||||
const { rerender } = render(view("a"));
|
||||
rerender(view("b"));
|
||||
await screen.findByText("session B");
|
||||
await act(async () => resolveFirst({ ...payload, content: "session A" }));
|
||||
expect(screen.queryByText("session A")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows a compact breadcrumb with one file name and a visible close action", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onClose = vi.fn();
|
||||
|
||||
@@ -3,9 +3,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import App from "@/App";
|
||||
import { ThreadMessageCache } from "@/lib/thread-message-cache";
|
||||
import { FilePreviewStore } from "@/hooks/useFilePreviewState";
|
||||
import type { InboundEvent, Outbound } from "@/lib/types";
|
||||
import { canonicalThreadPayload } from "./thread-test-payload";
|
||||
|
||||
let groupedTopics = false;
|
||||
let withFiles = false;
|
||||
const previewFile = (path: string) => ({
|
||||
path: `/workspace/${path}`, display_path: path, project_path: "/workspace",
|
||||
language: "text", content: `Preview of ${path}`, size: 20, truncated: false,
|
||||
});
|
||||
|
||||
vi.mock("@/lib/bootstrap", async (importOriginal) => ({
|
||||
...await importOriginal<typeof import("@/lib/bootstrap")>(),
|
||||
@@ -49,6 +56,11 @@ class TestSocket {
|
||||
queueMicrotask(() => this.receive({ event: "attached", chat_id: chatId, temporary: true }));
|
||||
} else if (frame.type === "set_sidebar_state") {
|
||||
queueMicrotask(() => this.receive({ event: "sidebar_state_updated", state: frame.state }));
|
||||
} else if (frame.type === "webui_request" && frame.action === "temporary_chat.file_preview") {
|
||||
queueMicrotask(() => this.receive({
|
||||
event: "webui_response", request_id: frame.request_id, ok: true,
|
||||
result: frame.payload.probe ? { available: true } : previewFile(String(frame.payload.path)),
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -82,6 +94,7 @@ async function selectTopic(name: string) {
|
||||
describe("temporary chat navigation", () => {
|
||||
beforeEach(() => {
|
||||
groupedTopics = false;
|
||||
withFiles = false;
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
window.history.replaceState(null, "", "/");
|
||||
@@ -104,17 +117,122 @@ describe("temporary chat navigation", () => {
|
||||
},
|
||||
} } });
|
||||
}
|
||||
if (path.includes("/file-preview?")) {
|
||||
const query = new URL(path, "http://test").searchParams;
|
||||
return Response.json(query.has("probe") ? { available: true } : previewFile(query.get("path")!));
|
||||
}
|
||||
if (withFiles && path.includes("/webui-thread")) {
|
||||
return Response.json(canonicalThreadPayload({
|
||||
schemaVersion: 3,
|
||||
messages: [{
|
||||
id: "file-reply", role: "assistant", createdAt: 1,
|
||||
content: "Files: [notes.txt](notes.txt) and [second.txt](second.txt)",
|
||||
}],
|
||||
}));
|
||||
}
|
||||
return new Response(null, { status: 404 });
|
||||
}));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
if (vi.isFakeTimers()) vi.clearAllTimers();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it.each([false, true])("restores file previews after pane navigation (temporary=%s)", async (temporary) => {
|
||||
withFiles = true;
|
||||
groupedTopics = true;
|
||||
vi.stubGlobal("matchMedia", (query: string) => ({
|
||||
matches: query.includes("max-width: 767px"), media: query,
|
||||
addEventListener: vi.fn(), removeEventListener: vi.fn(),
|
||||
}));
|
||||
render(<App />);
|
||||
await screen.findByRole("button", { name: "Temporary chat" });
|
||||
act(() => TestSocket.current.open());
|
||||
if (temporary) {
|
||||
const chatId = await startTemporaryChat("Show example files");
|
||||
act(() => TestSocket.current.receive({
|
||||
event: "message", chat_id: chatId,
|
||||
text: "Files: [notes.txt](notes.txt) and [second.txt](second.txt)",
|
||||
}));
|
||||
} else {
|
||||
await selectTopic("Regular topic");
|
||||
}
|
||||
fireEvent.click(await screen.findByRole("button", { name: "notes.txt" }));
|
||||
await screen.findByText("Preview of notes.txt");
|
||||
await selectTopic("Second pane");
|
||||
expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument();
|
||||
fireEvent.click(await screen.findByRole("button", { name: "second.txt" }));
|
||||
await screen.findByText("Preview of second.txt");
|
||||
await selectTopic(temporary ? "Show example files" : "Regular topic");
|
||||
await screen.findByText("Preview of notes.txt");
|
||||
expect(screen.queryByText("Preview of second.txt")).not.toBeInTheDocument();
|
||||
|
||||
// Explicit close must stick even if switching interrupts the close animation.
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close file preview" }));
|
||||
await selectTopic("Second pane");
|
||||
await selectTopic(temporary ? "Show example files" : "Regular topic");
|
||||
expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument();
|
||||
|
||||
if (temporary) {
|
||||
const requests = vi.mocked(fetch).mock.calls.map(([url]) => String(url));
|
||||
expect(requests.some((url) => url.includes("00000000-"))).toBe(false);
|
||||
}
|
||||
for (const storage of [localStorage, sessionStorage]) {
|
||||
const values = Array.from({ length: storage.length }, (_, i) => storage.getItem(storage.key(i)!));
|
||||
expect(JSON.stringify(values)).not.toContain("/workspace/notes.txt");
|
||||
expect(JSON.stringify(values)).not.toContain("Preview of notes.txt");
|
||||
}
|
||||
});
|
||||
|
||||
it("toggles the current file, switches files, and only handles Escape below dialogs", async () => {
|
||||
withFiles = true;
|
||||
render(<App />);
|
||||
await screen.findByRole("button", { name: "Temporary chat" });
|
||||
act(() => TestSocket.current.open());
|
||||
await selectTopic("Regular topic");
|
||||
fireEvent.click(await screen.findByRole("button", { name: "notes.txt" }));
|
||||
await screen.findByText("Preview of notes.txt");
|
||||
fireEvent.click(screen.getByRole("button", { name: "second.txt" }));
|
||||
await screen.findByText("Preview of second.txt");
|
||||
fireEvent.click(screen.getByRole("button", { name: "second.txt" }));
|
||||
await waitFor(() => expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument());
|
||||
fireEvent.click(screen.getByRole("button", { name: "notes.txt" }));
|
||||
await screen.findByText("Preview of notes.txt");
|
||||
const dialog = document.createElement("div");
|
||||
dialog.setAttribute("role", "dialog");
|
||||
document.body.append(dialog);
|
||||
fireEvent.keyDown(window, { key: "Escape" });
|
||||
expect(screen.getByTestId("file-preview-panel")).toBeInTheDocument();
|
||||
dialog.remove();
|
||||
fireEvent.keyDown(window, { key: "Escape" });
|
||||
await waitFor(() => expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("forgets preview paths on temporary close and disconnect", async () => {
|
||||
const update = vi.spyOn(FilePreviewStore.prototype, "update");
|
||||
render(<App />);
|
||||
await screen.findByRole("button", { name: "Temporary chat" });
|
||||
act(() => TestSocket.current.open());
|
||||
const chatId = await startTemporaryChat("Show example files");
|
||||
act(() => TestSocket.current.receive({
|
||||
event: "message", chat_id: chatId, text: "[notes.txt](notes.txt)",
|
||||
}));
|
||||
fireEvent.click(await screen.findByRole("button", { name: "notes.txt" }));
|
||||
await screen.findByText("Preview of notes.txt");
|
||||
const store = update.mock.contexts.find((value) => value.get(`websocket:${chatId}`).path)!;
|
||||
expect(store.get(`websocket:${chatId}`).path).toBe("notes.txt");
|
||||
await selectTopic("Close temporary chat: Show example files");
|
||||
expect(store.get(`websocket:${chatId}`).path).toBeNull();
|
||||
act(() => store.update("websocket:regular", { path: "notes.txt" }));
|
||||
vi.useFakeTimers();
|
||||
act(() => TestSocket.current.close());
|
||||
expect(store.get("websocket:regular").path).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps messages when navigating to a regular workbench and back", async () => {
|
||||
render(<App />);
|
||||
await screen.findByRole("button", { name: "Temporary chat" });
|
||||
|
||||
Reference in new issue
Block a user