This commit is contained in:
Timothy Jaeryang Baek committed 2026-07-06 18:11:59 -05:00
1 parent e9dc12049b
commit cf13e63b58
6 files changed
+394 -2

No files matched your search

@@ -3,11 +3,14 @@
import { get } from 'svelte/store';
import MarkdownRenderer from '$lib/components/markdown/MarkdownRenderer.svelte';
import OutputEditView from './OutputEditView.svelte';
import ChatFilePreview from './ChatFilePreview.svelte';
import ConsecutiveActivityGroup from './ConsecutiveActivityGroup.svelte';
import ReasoningCollapsible from './ReasoningCollapsible.svelte';
import ToolCallCollapsible from './ToolCallCollapsible.svelte';
import { currentWorkspace, openFileTab } from '$lib/stores';
import { ttsConfigured, ttsEnabled } from '$lib/stores/audio';
import { tooltip } from '$lib/tooltip';
import { fileIconName } from '$lib/utils/fileIcon';
import Icon from '../Icon.svelte';
import { t } from '$lib/i18n';
@@ -49,6 +52,7 @@
let editedOutput = $state<any[] | null>(null);
let copied = $state(false);
let showUsageTooltip = $state(false);
let collapsedFiles = $state<Record<string, boolean>>({});
let textareaEl: HTMLTextAreaElement;
async function startEdit() {
@@ -138,6 +142,17 @@
return parts[parts.length - 1];
}
function resolvedFilePath(file: any): string {
const path = String(file?.full_path || file?.path || '');
if (!path || path.startsWith('/')) return path;
const workspace = file?.workspace || get(currentWorkspace)?.path || '';
return workspace ? `${workspace.replace(/\/$/, '')}/${path.replace(/^\/+/, '')}` : path;
}
function toggleFile(key: string) {
collapsedFiles = { ...collapsedFiles, [key]: !collapsedFiles[key] };
}
/** Human-readable label for a tool call */
function toolLabel(name: string, args: any): string {
const _t = $t;
@@ -159,6 +174,8 @@
return _t('chat.tool.createFile', { path: shortPath(args.path) });
case 'write_file':
return _t('chat.tool.writeFile', { path: shortPath(args.path) });
case 'display_file':
return `Display ${shortPath(args.path)}`;
case 'list_directory':
return args.recursive
? _t('chat.tool.listDirectoryRecursive', { path: shortPath(args.path) })
@@ -234,7 +251,13 @@
item: any;
}
type DisplayItem = ActivityGroup | MessageItem | ArtifactItem | ImageItem;
interface FileItem {
type: 'file_item';
item: any;
index: number;
}
type DisplayItem = ActivityGroup | MessageItem | ArtifactItem | ImageItem | FileItem;
const outputText = $derived.by((): string => {
return (output || [])
@@ -313,7 +336,7 @@
}
};
for (const item of output) {
for (const [index, item] of output.entries()) {
if (item.type === 'function_call') {
ensureGroup();
currentGroup!.entries.push(item);
@@ -335,6 +358,9 @@
} else if (item.type === 'image') {
flushGroup();
items.push({ type: 'image_item', item });
} else if (item.type === 'file') {
flushGroup();
items.push({ type: 'file_item', item, index });
}
// function_call_output items are handled via outputMap, skip standalone render
}
@@ -469,6 +495,53 @@
</a>
{/each}
</div>
{:else if displayItem.type === 'file_item'}
{@const file = displayItem.item}
{@const filePath = resolvedFilePath(file)}
{@const fileKey = filePath || file.path || `file-${displayItem.index}`}
{@const collapsed = Boolean(collapsedFiles[fileKey])}
<div
class="my-2 w-full max-w-2xl overflow-hidden rounded-md border border-gray-200 bg-white dark:border-white/8 dark:bg-gray-950/20"
>
<div
class="flex h-8 items-center {collapsed
? ''
: 'border-b border-gray-100 dark:border-white/8'}"
>
<button
type="button"
class="flex h-full min-w-0 flex-1 items-center gap-2 px-2.5 text-left"
onclick={() => toggleFile(fileKey)}
aria-expanded={!collapsed}
>
<div
class="flex size-5 shrink-0 items-center justify-center text-gray-500 dark:text-gray-400"
>
<Icon name={fileIconName(file.name || file.path || '', 'file')} size={14} />
</div>
<div
class="min-w-0 flex-1 truncate text-xs font-medium text-gray-800 dark:text-gray-100"
>
{file.name || shortPath(file.path)}
</div>
</button>
<button
type="button"
class="mr-1 flex size-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200"
onclick={(event) => {
event.stopPropagation();
if (filePath) openFileTab(filePath);
}}
aria-label={$t('directory.open', { name: file.name || shortPath(file.path) })}
use:tooltip={'Open as tab'}
>
<Icon name="external-link" size={13} />
</button>
</div>
{#if !collapsed}
<ChatFilePreview {file} {filePath} />
{/if}
</div>
{:else if displayItem.type === 'activity_group'}
{#if displayItem.entries.length === 1}
{@const item = displayItem.entries[0]}
@@ -0,0 +1,196 @@
<script lang="ts">
import { readFile } from '$lib/apis/files';
import MarkdownRenderer from '$lib/components/markdown/MarkdownRenderer.svelte';
import CsvTable from '$lib/components/preview/CsvTable.svelte';
import HtmlPreview from '$lib/components/preview/HtmlPreview.svelte';
import ImagePreview from '$lib/components/preview/ImagePreview.svelte';
import JsonTreeView from '$lib/components/preview/JsonTreeView.svelte';
import OfficePreview from '$lib/components/preview/OfficePreview.svelte';
import PDFViewer from '$lib/components/preview/PDFViewer.svelte';
import SvgPreview from '$lib/components/preview/SvgPreview.svelte';
interface Props {
file: any;
filePath: string;
}
let { file, filePath }: Props = $props();
const MAX_TEXT_PREVIEW_BYTES = 200_000;
let loading = $state(false);
let error = $state('');
let content = $state('');
let jsonData = $state<unknown>(null);
const kind = $derived(file?.kind || 'binary');
const name = $derived(file?.name || filePath.split('/').pop() || '');
const viewUrl = $derived(`/api/workspace/files/view?path=${encodeURIComponent(filePath)}`);
const shouldReadText = $derived(
['markdown', 'text', 'json', 'csv', 'html', 'svg'].includes(kind) &&
(typeof file?.size !== 'number' || file.size <= MAX_TEXT_PREVIEW_BYTES)
);
$effect(() => {
let cancelled = false;
const path = filePath;
async function load() {
content = '';
jsonData = null;
error = '';
if (!path || !shouldReadText) return;
loading = true;
try {
const res = await readFile(path);
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.detail || `Error ${res.status}`);
}
const data = await res.json();
if (cancelled) return;
content = data.content || '';
if (kind === 'json') {
try {
jsonData = JSON.parse(content);
} catch {
jsonData = null;
}
}
} catch (e: any) {
if (!cancelled) error = e.message || 'Failed to load preview';
} finally {
if (!cancelled) loading = false;
}
}
void load();
return () => {
cancelled = true;
};
});
</script>
{#if loading}
<div class="preview-state">Loading...</div>
{:else if error}
<div class="preview-state">{error}</div>
{:else if kind === 'image'}
<div class="preview-box image-box">
<ImagePreview src={viewUrl} alt={name} />
</div>
{:else if kind === 'pdf'}
<div class="preview-box tall">
<PDFViewer src={viewUrl} />
</div>
{:else if kind === 'office'}
<div class="preview-box tall">
<OfficePreview src={viewUrl} fileName={name} />
</div>
{:else if kind === 'html' && content}
<div class="preview-box tall">
<HtmlPreview {content} {filePath} />
</div>
{:else if kind === 'svg' && content}
<div class="preview-box tall">
<SvgPreview {content} />
</div>
{:else if kind === 'markdown' && content}
<div class="text-preview">
<MarkdownRenderer {content} />
</div>
{:else if kind === 'json' && jsonData !== null}
<div class="text-preview mono-preview">
<JsonTreeView data={jsonData} />
</div>
{:else if kind === 'csv' && content}
<div class="preview-box">
<CsvTable {content} separator={name.endsWith('.tsv') ? '\t' : ','} />
</div>
{:else if kind === 'text' && content}
<pre class="text-preview mono-preview">{content}</pre>
{:else if kind === 'audio'}
<div class="media-preview">
<audio controls preload="metadata" src={viewUrl}></audio>
</div>
{:else if kind === 'video'}
<div class="media-preview">
<!-- svelte-ignore a11y_media_has_caption -->
<video controls preload="metadata" src={viewUrl}></video>
</div>
{/if}
<style>
@reference "../../../app.css";
.preview-box {
height: 18rem;
max-height: 52vh;
min-height: 10rem;
overflow: hidden;
background: white;
}
:global(.dark) .preview-box {
background: black;
}
.preview-box.tall {
height: 24rem;
}
.image-box {
height: 22rem;
}
.text-preview {
max-height: 22rem;
overflow: auto;
padding: 0.875rem 1rem;
background: white;
}
:global(.dark) .text-preview {
background: rgba(0, 0, 0, 0.25);
}
.mono-preview {
margin: 0;
white-space: pre-wrap;
word-break: break-word;
font-family: var(--font-mono);
font-size: 0.75rem;
line-height: 1.35;
color: var(--color-gray-800);
}
:global(.dark) .mono-preview {
color: var(--color-gray-200);
}
.media-preview {
padding: 0.75rem 1rem;
background: white;
}
:global(.dark) .media-preview {
background: rgba(0, 0, 0, 0.25);
}
.media-preview audio,
.media-preview video {
width: 100%;
max-height: 22rem;
}
.preview-state {
padding: 0.75rem 1rem;
font-size: 0.75rem;
color: var(--color-gray-500);
}
:global(.dark) .preview-state {
color: var(--color-gray-400);
}
</style>
@@ -39,6 +39,7 @@
import Spinner from '$lib/components/common/Spinner.svelte';
import { t } from '$lib/i18n';
import { TAB_DRAG_MIME } from '$lib/constants';
import { tooltip } from '$lib/tooltip';
// Keep screen awake during voice mode conversations
let voiceWakeLock: WakeLockSentinel | null = null;
@@ -1029,6 +1030,8 @@
{#if slashCommandIds.includes('compact')}
<button
type="button"
aria-label="Compact: shorten older messages so this chat can keep going."
use:tooltip={{ content: 'Shorten older messages so this chat can keep going.', placement: 'right' }}
class="slash-command-row flex items-center gap-2 w-full h-6 px-2 rounded-xl text-xs text-left transition-colors duration-75
{slashCommandIds[selectedSlashCommandIndex] === 'compact'
? 'app-interactive-active'
@@ -1075,6 +1078,11 @@
{#if slashCommandIds.includes('plan')}
<button
type="button"
aria-label="Plan: work out a plan first, then wait before changing files."
use:tooltip={{
content: 'Work out a plan first, then wait before changing files.',
placement: 'right'
}}
class="slash-command-row flex items-center gap-2 w-full h-6 px-2 rounded-xl text-xs text-left transition-colors duration-75
{slashCommandIds[selectedSlashCommandIndex] === 'plan' ? 'app-interactive-active' : ''}"
onmousedown={(e) => e.preventDefault()}
@@ -1111,6 +1119,11 @@
{#if slashCommandIds.includes('status')}
<button
type="button"
aria-label="Status: check what is running in this chat."
use:tooltip={{
content: 'Check what is running in this chat.',
placement: 'right'
}}
class="slash-command-row flex items-center gap-2 w-full h-6 px-2 rounded-xl text-xs text-left transition-colors duration-75
{slashCommandIds[selectedSlashCommandIndex] === 'status' ? 'app-interactive-active' : ''}"
onmousedown={(e) => e.preventDefault()}
@@ -1145,6 +1158,11 @@
{#if slashCommandIds.includes('skills:list')}
<button
type="button"
aria-label="List skills: see the skills available in this workspace."
use:tooltip={{
content: 'See the skills available in this workspace.',
placement: 'right'
}}
class="slash-command-row flex items-center gap-2 w-full h-6 px-2 rounded-xl text-xs text-left transition-colors duration-75
{slashCommandIds[selectedSlashCommandIndex] === 'skills:list'
? 'app-interactive-active'
@@ -1167,6 +1185,11 @@
{#if slashCommandIds.includes('skills:create')}
<button
type="button"
aria-label="Create skill: teach Computer a reusable workflow."
use:tooltip={{
content: 'Teach Computer a reusable workflow.',
placement: 'right'
}}
class="slash-command-row flex items-center gap-2 w-full h-6 px-2 rounded-xl text-xs text-left transition-colors duration-75
{slashCommandIds[selectedSlashCommandIndex] === 'skills:create'
? 'app-interactive-active'
+15
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import asyncio
import json
import logging
from pathlib import Path
from typing import List, Optional
@@ -691,6 +692,20 @@ async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, requ
{"chat_id": chat_id, "message_id": message_id, "output": artifact_item},
)
if call["name"] == "display_file":
try:
file_item = json.loads(result)
except (json.JSONDecodeError, TypeError):
file_item = None
if isinstance(file_item, dict) and file_item.get("type") == "file":
output.append(file_item)
from cptr.socket.main import emit_to_user
await emit_to_user(
user_id,
{"chat_id": chat_id, "message_id": message_id, "output": file_item},
)
image_item = build_image_item(call["name"], result)
if image_item:
output.append(image_item)
+10
View File
@@ -2058,6 +2058,16 @@ async def run_chat_task(
await emit(output=artifact_item)
_sync_state()
if tc["name"] == "display_file":
try:
file_item = json.loads(result)
except (json.JSONDecodeError, TypeError):
file_item = None
if isinstance(file_item, dict) and file_item.get("type") == "file":
output_items.append(file_item)
await emit(output=file_item)
_sync_state()
image_item = build_image_item(tc["name"], result)
if image_item:
output_items.append(image_item)
+75
View File
@@ -14,6 +14,7 @@ from __future__ import annotations
import asyncio
import inspect
import json
import mimetypes
import os
import time
import uuid
@@ -233,6 +234,37 @@ def _human_size(size: int) -> str:
return f"{size:.1f}TB"
def _file_kind(path: Path, mime_type: str) -> str:
ext = path.suffix.lower()
if mime_type.startswith("image/"):
return "image"
if mime_type.startswith("audio/"):
return "audio"
if mime_type.startswith("video/"):
return "video"
if mime_type == "application/pdf":
return "pdf"
if ext in {".md", ".markdown", ".mdx"}:
return "markdown"
if ext in {".json", ".jsonc", ".json5"}:
return "json"
if ext in {".csv", ".tsv"}:
return "csv"
if ext in {".html", ".htm"}:
return "html"
if ext == ".svg":
return "svg"
if ext in {".txt", ".log", ".diff", ".patch"} or mime_type.startswith("text/"):
return "text"
if ext in {".docx", ".xlsx", ".xls", ".pptx"}:
return "office"
if ext in {".sqlite", ".sqlite3", ".db", ".db3"}:
return "sqlite"
if ext in {".zip", ".tar", ".gz", ".tgz", ".rar", ".7z"}:
return "archive"
return "binary"
def _truncate_output(text: str, max_chars: int = 80_000) -> str:
"""Truncate long output, keeping head and tail."""
if len(text) <= max_chars:
@@ -816,6 +848,48 @@ async def write_file(path: str, content: str, *, workspace: str) -> str:
return f"Wrote {len(content)} bytes to {path}"
async def display_file(path: str, *, workspace: str) -> str:
"""Display an existing real file from the computer in chat.
Use only for files you have just created or verified with file tools.
:param path: Path relative to workspace root.
"""
if not path:
return "Error: path is required."
try:
full = _resolve_path(path, workspace)
except ValueError as exc:
return f"Error: {exc}"
if _is_dotenv(full):
return _DOTENV_ERROR
if not full.exists():
return f"Error: file not found: {path}"
if not full.is_file():
return f"Error: not a file: {path}"
stat = await asyncio.to_thread(full.stat)
mime_type = mimetypes.guess_type(str(full))[0] or "application/octet-stream"
ws = Path(workspace).resolve()
try:
display_path = str(full.relative_to(ws))
except ValueError:
display_path = str(full)
return json.dumps(
{
"type": "file",
"path": display_path,
"full_path": str(full),
"workspace": str(ws),
"name": full.name,
"size": stat.st_size,
"mime_type": mime_type,
"kind": _file_kind(full, mime_type),
},
ensure_ascii=False,
)
async def edit_file(
path: str,
target: str,
@@ -1959,6 +2033,7 @@ TOOLS: dict[str, dict] = {
"view_skill": {"fn": view_skill, "auto": True},
# Write / mutate (require approval unless auto_approve_all)
"create_file": {"fn": create_file, "auto": False},
"display_file": {"fn": display_file, "auto": False},
"edit_file": {"fn": edit_file, "auto": False},
"multi_edit_file": {"fn": multi_edit_file, "auto": False},
"write_file": {"fn": write_file, "auto": False},