Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(cowork): attach documents, read them in the workspace, list files in a rail

Akarshan Biswas88cddef65089
diff --git a/docs/src/pages/docs/desktop/cowork.mdx b/docs/src/pages/docs/desktop/cowork.mdx
index 9b5c1ae64..ec783c6f3 100644
--- a/docs/src/pages/docs/desktop/cowork.mdx
+++ b/docs/src/pages/docs/desktop/cowork.mdx
@@ -84,13 +84,22 @@ list, and asks you to review it:
## Progress panels
-While the agent works, three panels track the run:
+While the agent works, four panels track the run:
- **Todos** — the canonical task list for the current job, with phases and
statuses the agent keeps current.
- **Tasks** — background [subagents](#subagents), their queue position and
status.
- **Diffs** — every change the agent made to an attached project folder.
+- **Files** — every file in the session: documents you attached to a question
+ and the artifacts the agent created, grouped by type. Click one to preview it.
+
+### Attaching documents
+
+Attach a PDF, DOCX, or other document with the composer's attach button. The
+file is copied into the session workspace, its text is extracted beside it, and
+the question names both paths, so the agent can read the contents with its file
+tools. The attachment appears as a chip on your message and in the Files panel.
## Subagents
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs
index 26a6920ed..2f69679cb 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs
@@ -19,6 +19,7 @@ const COMMANDS: &[&str] = &[
"sandbox_status",
"subagent_result_reserve",
"subagent_result_fill",
+ "attachment_import",
"execute_tool",
"execute_tool_streaming",
"start_monitor",
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts
index 94d8cf93a..026c04de6 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts
@@ -262,6 +262,33 @@ export async function subagentResultFill(
})
}
+/** An attachment copied into a session workspace. */
+export type ImportedAttachment = {
+ /** The copy inside the workspace, readable by the agent's file tools. */
+ path: string
+ /** The extracted-text sibling (`<name>.txt`), when text was supplied. */
+ textPath: string | null
+}
+
+/**
+ * Copy a user attachment into `sessionId`'s workspace, writing `text` beside
+ * it when given, so the agent can read a file picked from outside its roots.
+ * Same-named files are suffixed, never overwritten.
+ */
+export async function attachmentImport(
+ dataFolder: string,
+ sessionId: string,
+ source: string,
+ text?: string
+): Promise<ImportedAttachment> {
+ return await invoke('plugin:agent-tools|attachment_import', {
+ dataFolder,
+ sessionId,
+ source,
+ text: text ?? null,
+ })
+}
+
/**
* Function schemas for every built-in tool. Callers pick which subset to
* advertise; the schemas are never re-typed in TypeScript.
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml
index 6439accf1..1848bf042 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml
@@ -21,6 +21,7 @@ permissions = [
"allow-sandbox-status",
"allow-subagent-result-reserve",
"allow-subagent-result-fill",
+ "allow-attachment-import",
"allow-execute-tool",
"allow-execute-tool-streaming",
"allow-start-monitor",
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json
index 9b55f74ce..1e612d425 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json
@@ -643,10 +643,10 @@
"markdownDescription": "Denies the workspace_path command without any pre-configured scope."
},
{
- "description": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-stop-session-monitors`",
+ "description": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-stop-session-monitors`",
"type": "string",
"const": "default",
- "markdownDescription": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-stop-session-monitors`"
+ "markdownDescription": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-stop-session-monitors`"
}
]
}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
index 23010ed06..e44331516 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
@@ -426,6 +426,43 @@ pub async fn subagent_result_fill(
Ok(())
}
+/// An attachment imported into a session workspace: host paths, which are also
+/// the model-visible spelling since the workspace is the tools' root.
+#[derive(serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ImportedAttachment {
+ pub path: String,
+ pub text_path: Option<String>,
+}
+
+/// Copy a user attachment into the Cowork session workspace, with its extracted
+/// text beside it, so the agent's file tools can reach a file the picker found
+/// outside every root they may read. Host-side rather than a model tool: the
+/// source path is the user's, never the model's to name.
+#[tauri::command]
+pub async fn attachment_import(
+ data_folder: String,
+ session_id: String,
+ source: String,
+ text: Option<String>,
+) -> Result<ImportedAttachment, AgentToolsError> {
+ let workspace =
+ workspace::ensure_session_workspace(Path::new(&data_folder), &session_id).await?;
+ let imported = tokio::task::spawn_blocking(move || {
+ crate::tools::attachments::import_attachment(
+ &workspace,
+ Path::new(&source),
+ text.as_deref(),
+ )
+ })
+ .await
+ .map_err(|e| AgentToolsError::from(format!("attachment import failed: {e}")))??;
+ Ok(ImportedAttachment {
+ path: imported.path.to_string_lossy().into_owned(),
+ text_path: imported.text_path.map(|p| p.to_string_lossy().into_owned()),
+ })
+}
+
/// Live monitors per Cowork session, each with the IPC channel its updates are
/// forwarded over. Process-wide like `bash`'s background jobs: the Cowork loop
/// runs in the frontend, so nothing host-side scopes a run. The channel slot is
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs
index 49fe8a47e..64b841200 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs
@@ -53,6 +53,7 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
commands::sandbox_status,
commands::subagent_result_reserve,
commands::subagent_result_fill,
+ commands::attachment_import,
commands::execute_tool,
commands::execute_tool_streaming,
commands::start_monitor,
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/attachments.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/attachments.rs
new file mode 100644
index 000000000..eda787e86
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/attachments.rs
@@ -0,0 +1,187 @@
+//! User attachments imported into a Cowork session workspace.
+//!
+//! A document the user attaches to a question lives wherever the file picker
+//! found it, outside every root the filesystem tools may read. Copying it into
+//! the workspace is what puts it in the agent's reach; an extracted-text
+//! sibling is what makes a binary format (PDF, DOCX) readable by `read`, which
+//! refuses anything that is not UTF-8.
+
+use std::path::{Path, PathBuf};
+
+use super::spill::{open_excl, sanitize_stem, validated_subdir};
+
+/// Workspace subdirectory holding imported attachments.
+pub const ATTACHMENTS_DIR: &str = "attachments";
+
+/// Suffix of the extracted-text sibling written beside a binary document.
+pub const TEXT_SUFFIX: &str = ".txt";
+
+/// Refuse anything larger: the composer already caps attachments, so this is
+/// the backstop against a caller bypassing it, not the user-facing limit.
+pub const MAX_ATTACHMENT_BYTES: u64 = 256 * 1024 * 1024;
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct ImportedAttachment {
+ /// The copy inside the workspace.
+ pub path: PathBuf,
+ /// The extracted-text sibling, when text was supplied.
+ pub text_path: Option<PathBuf>,
+}
+
+/// Copy `source` into `<workspace>/attachments/`, writing `text` beside it as
+/// `<name>.txt` when given. Names are sanitized to one safe component and
+/// suffixed (`-2`, `-3`, ...) rather than overwritten, so two questions that
+/// attach different files of the same name keep both.
+pub fn import_attachment(
+ workspace: &Path,
+ source: &Path,
+ text: Option<&str>,
+) -> Result<ImportedAttachment, String> {
+ let meta = std::fs::metadata(source)
+ .map_err(|e| format!("cannot read attachment {}: {e}", source.display()))?;
+ if !meta.is_file() {
+ return Err(format!("attachment {} is not a file", source.display()));
+ }
+ if meta.len() > MAX_ATTACHMENT_BYTES {
+ return Err(format!(
+ "attachment {} is {} bytes, over the {} byte limit",
+ source.display(),
+ meta.len(),
+ MAX_ATTACHMENT_BYTES
+ ));
+ }
+ let dir = validated_subdir(workspace, ATTACHMENTS_DIR)
+ .ok_or_else(|| "could not create the attachments directory".to_string())?;
+ let base = source
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ let (stem, ext) = split_name(&base);
+ let stem = sanitize_stem(&stem);
+
+ for n in 1..100 {
+ let name = match (n, ext.as_str()) {
+ (1, "") => stem.clone(),
+ (1, ext) => format!("{stem}.{ext}"),
+ (n, "") => format!("{stem}-{n}"),
+ (n, ext) => format!("{stem}-{n}.{ext}"),
+ };
+ let path = dir.join(&name);
+ let text_path = text.map(|_| dir.join(format!("{name}{TEXT_SUFFIX}")));
+ // Both names are claimed together, so a stray `x.pdf.txt` cannot pair
+ // with the wrong `x.pdf`.
+ let mut file = match open_excl(&path) {
+ Ok(f) => f,
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
+ Err(e) => return Err(format!("cannot create {}: {e}", path.display())),
+ };
+ let text_file = match &text_path {
+ Some(tp) => match open_excl(tp) {
+ Ok(f) => Some(f),
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
+ let _ = std::fs::remove_file(&path);
+ continue;
+ }
+ Err(e) => {
+ let _ = std::fs::remove_file(&path);
+ return Err(format!("cannot create {}: {e}", tp.display()));
+ }
+ },
+ None => None,
+ };
+ let mut src = std::fs::File::open(source)
+ .map_err(|e| format!("cannot open attachment {}: {e}", source.display()))?;
+ std::io::copy(&mut src, &mut file)
+ .map_err(|e| format!("cannot copy attachment into {}: {e}", path.display()))?;
+ if let (Some(mut tf), Some(t)) = (text_file, text) {
+ use std::io::Write;
+ tf.write_all(t.as_bytes())
+ .map_err(|e| format!("cannot write extracted text: {e}"))?;
+ }
+ return Ok(ImportedAttachment { path, text_path });
+ }
+ Err(format!("too many attachments named {base}"))
+}
+
+/// `report.final.pdf` -> (`report.final`, `pdf`); a dotfile or a bare name has
+/// no extension.
+fn split_name(name: &str) -> (String, String) {
+ match name.rfind('.') {
+ Some(i) if i > 0 => (name[..i].to_string(), name[i + 1..].to_lowercase()),
+ _ => (name.to_string(), String::new()),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn tmp(tag: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "jan-attach-test-{tag}-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ #[test]
+ fn copies_the_file_and_writes_the_text_beside_it() {
+ let ws = tmp("copy");
+ let src_dir = tmp("copy-src");
+ let src = src_dir.join("Spec v2.pdf");
+ std::fs::write(&src, b"%PDF-1.4 binary").unwrap();
+
+ let got = import_attachment(&ws, &src, Some("extracted words")).unwrap();
+ assert_eq!(got.path, ws.join("attachments/Spec-v2.pdf"));
+ assert_eq!(got.text_path, Some(ws.join("attachments/Spec-v2.pdf.txt")));
+ assert_eq!(std::fs::read(&got.path).unwrap(), b"%PDF-1.4 binary");
+ assert_eq!(
+ std::fs::read_to_string(got.text_path.unwrap()).unwrap(),
+ "extracted words"
+ );
+ let _ = std::fs::remove_dir_all(&ws);
+ let _ = std::fs::remove_dir_all(&src_dir);
+ }
+
+ #[test]
+ fn a_second_file_of_the_same_name_is_suffixed_not_overwritten() {
+ let ws = tmp("dup");
+ let src_dir = tmp("dup-src");
+ let src = src_dir.join("notes.md");
+ std::fs::write(&src, "one").unwrap();
+ let first = import_attachment(&ws, &src, None).unwrap();
+ std::fs::write(&src, "two").unwrap();
+ let second = import_attachment(&ws, &src, Some("two")).unwrap();
+ assert_eq!(first.path, ws.join("attachments/notes.md"));
+ assert_eq!(first.text_path, None);
+ assert_eq!(second.path, ws.join("attachments/notes-2.md"));
+ assert_eq!(
+ second.text_path,
+ Some(ws.join("attachments/notes-2.md.txt"))
+ );
+ assert_eq!(std::fs::read_to_string(&first.path).unwrap(), "one");
+ assert_eq!(std::fs::read_to_string(&second.path).unwrap(), "two");
+ let _ = std::fs::remove_dir_all(&ws);
+ let _ = std::fs::remove_dir_all(&src_dir);
+ }
+
+ #[test]
+ fn refuses_a_directory_and_a_missing_file() {
+ let ws = tmp("refuse");
+ assert!(import_attachment(&ws, &ws, None).is_err());
+ assert!(import_attachment(&ws, &ws.join("nope.pdf"), None).is_err());
+ let _ = std::fs::remove_dir_all(&ws);
+ }
+
+ #[test]
+ fn splits_names_like_a_shell_would() {
+ assert_eq!(split_name("a.b.PDF"), ("a.b".into(), "pdf".into()));
+ assert_eq!(split_name("README"), ("README".into(), String::new()));
+ assert_eq!(split_name(".env"), (".env".into(), String::new()));
+ }
+}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
index d10cc9dcc..f21c0017c 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
@@ -6,6 +6,8 @@ use std::path::{Path, PathBuf};
/// Windows-only confinement backend for [`jail`]. Present on every platform so
/// the argv it builds stays unit-testable.
pub mod appcontainer;
+/// User attachments copied into a session workspace for the agent to read.
+pub mod attachments;
pub mod cmdscan;
pub mod gate;
pub mod handlers;
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rs
index 75b0d5503..6384afb7c 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rs
@@ -60,7 +60,7 @@ pub fn open_excl(path: &Path) -> std::io::Result<std::fs::File> {
/// `[A-Za-z0-9._-]` collapses to `-`, leading dots are stripped so the name
/// can never be a dotfile or a `..` component, and an unusable id falls back
/// to a generic stem rather than failing the write.
-fn sanitize_stem(id: &str) -> String {
+pub(crate) fn sanitize_stem(id: &str) -> String {
let mut stem: String = id
.chars()
.map(|c| {
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index 39c3575d2..21b7ffe31 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -121,7 +121,10 @@ type ChatInputProps = {
projectAssistantId?: string
onSubmit?: (
text: string,
- files?: Array<{ type: string; mediaType: string; url: string }>
+ files?: Array<{ type: 'file'; mediaType: string; url: string }>,
+ /** Document attachments, for surfaces that do not read them back out of
+ * the attachments store themselves. */
+ documents?: Attachment[]
) => void
onStop?: () => void
chatStatus?: ChatStatus
@@ -595,27 +598,34 @@ const ChatInput = memo(function ChatInput({
const imageFiles = attachments
.filter((att) => att.type === 'image' && att.dataUrl)
.map((att) => ({
- type: 'file',
+ type: 'file' as const,
mediaType: att.mimeType ?? 'image/jpeg',
url: att.dataUrl!,
}))
const audioFiles = attachments
.filter((att) => att.type === 'audio' && att.dataUrl)
.map((att) => ({
- type: 'file',
+ type: 'file' as const,
mediaType: att.audioFormat === 'mp3' ? 'audio/mpeg' : 'audio/wav',
url: att.dataUrl!,
}))
const videoFiles = attachments
.filter((att) => att.type === 'video' && att.dataUrl)
.map((att) => ({
- type: 'file',
+ type: 'file' as const,
mediaType: att.mimeType ?? 'video/mp4',
url: att.dataUrl!,
}))
const files = [...imageFiles, ...audioFiles, ...videoFiles]
+ const documents = attachments.filter(
+ (att) => att.type === 'document' && att.path
+ )
- onSubmit(effectivePrompt, files.length > 0 ? files : undefined)
+ onSubmit(
+ effectivePrompt,
+ files.length > 0 ? files : undefined,
+ documents.length > 0 ? documents : undefined
+ )
setPrompt('')
clearAttachmentsForThread(attachmentsKey)
} else {
diff --git a/web-app/src/containers/CoworkFilesChip.tsx b/web-app/src/containers/CoworkFilesChip.tsx
new file mode 100644
index 000000000..6a94d7d3c
--- /dev/null
+++ b/web-app/src/containers/CoworkFilesChip.tsx
@@ -0,0 +1,47 @@
+import { Files } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@/components/ui/tooltip'
+import { cn } from '@/lib/utils'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+
+/**
+ * Opens the files rail. Quiet until the session has a file to list -- an
+ * attachment or an artifact -- like the changes and plan chips beside it.
+ */
+export function CoworkFilesChip({
+ count,
+ open,
+ onToggle,
+}: {
+ count: number
+ open: boolean
+ onToggle: () => void
+}) {
+ const { t } = useTranslation()
+ if (count === 0) return null
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="xs"
+ aria-pressed={open}
+ aria-label={t('common:files.a11y', { count })}
+ onClick={onToggle}
+ className={cn('shrink-0', open && 'text-primary')}
+ >
+ <Files className="size-3.5 shrink-0" />
+ <span className="font-mono tabular-nums text-muted-foreground">
+ {count}
+ </span>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{t('common:files.title')}</TooltipContent>
+ </Tooltip>
+ )
+}
diff --git a/web-app/src/containers/CoworkFilesPanel.tsx b/web-app/src/containers/CoworkFilesPanel.tsx
new file mode 100644
index 000000000..71ec1b34b
--- /dev/null
+++ b/web-app/src/containers/CoworkFilesPanel.tsx
@@ -0,0 +1,171 @@
+import { useState, type ComponentType } from 'react'
+import { ChevronDown, Paperclip } from 'lucide-react'
+import { cn } from '@/lib/utils'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { CoworkSidePanel } from '@/containers/CoworkSidePanel'
+import {
+ ARTIFACT_GROUP_NAMES,
+ ARTIFACT_ICON,
+ type CoworkArtifact,
+} from '@/lib/coworkArtifacts'
+import type { CoworkAttachedFile } from '@/types/coworkSession'
+
+type Row = {
+ key: string
+ name: string
+ label: string
+ /** What the preview pane opens; absent when there is no copy to open. */
+ previewPath?: string
+ detail?: string
+}
+
+type Group = {
+ id: string
+ title: string
+ Icon: ComponentType<{ size?: number; className?: string }>
+ rows: Row[]
+}
+
+/**
+ * Every file the session touched, in two families: what the user attached and
+ * what the agent produced, the latter in the artifact library's groups. Each
+ * group folds independently; a row opens the preview rail in place.
+ */
+export function CoworkFilesPanel({
+ attachments,
+ artifacts,
+ onPreview,
+ onClose,
+}: {
+ attachments: CoworkAttachedFile[]
+ artifacts: CoworkArtifact[]
+ onPreview: (path: string) => void
+ onClose: () => void
+}): React.ReactElement {
+ const { t } = useTranslation()
+ const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set())
+
+ const groups: Group[] = []
+ if (attachments.length > 0) {
+ groups.push({
+ id: 'attachments',
+ title: t('common:files.attachments'),
+ Icon: Paperclip,
+ rows: attachments.map((f) => ({
+ key: `att:${f.path}`,
+ name: f.name,
+ label: (f.fileType ?? '').toUpperCase(),
+ previewPath: f.workspacePath,
+ detail: f.workspacePath ? undefined : t('common:files.notImported'),
+ })),
+ })
+ }
+ for (const group of ARTIFACT_GROUP_NAMES) {
+ const rows = artifacts.filter((a) => a.group === group)
+ if (rows.length === 0) continue
+ groups.push({
+ id: group,
+ title: t(`common:artifactGroup${group}`),
+ Icon: ARTIFACT_ICON[group],
+ rows: rows.map((a) => ({
+ key: `art:${a.path}`,
+ name: `${a.title}.${a.label.toLowerCase()}`,
+ label: a.label,
+ previewPath: a.path,
+ })),
+ })
+ }
+ const total = groups.reduce((sum, g) => sum + g.rows.length, 0)
+
+ const toggle = (id: string) =>
+ setCollapsed((current) => {
+ const next = new Set(current)
+ if (next.has(id)) next.delete(id)
+ else next.add(id)
+ return next
+ })
+
+ return (
+ <CoworkSidePanel
+ title={t('common:files.title')}
+ summary={
+ <span className="shrink-0 text-xs font-mono text-main-view-fg/60">
+ {total}
+ </span>
+ }
+ onClose={onClose}
+ >
+ <div className="h-full overflow-y-auto">
+ {groups.length === 0 ? (
+ <p className="px-4 py-8 text-center text-sm text-main-view-fg/50">
+ {t('common:files.empty')}
+ </p>
+ ) : (
+ <div className="divide-y">
+ {groups.map((group) => {
+ const open = !collapsed.has(group.id)
+ return (
+ <div key={group.id}>
+ <button
+ type="button"
+ onClick={() => toggle(group.id)}
+ aria-expanded={open}
+ className="flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-muted/50"
+ >
+ <ChevronDown
+ size={14}
+ className={cn(
+ 'shrink-0 text-main-view-fg/50 transition-transform',
+ !open && '-rotate-90'
+ )}
+ />
+ <group.Icon size={14} className="shrink-0 text-main-view-fg/60" />
+ <span className="min-w-0 flex-1 truncate text-xs font-medium">
+ {group.title}
+ </span>
+ <span className="shrink-0 font-mono text-xs text-main-view-fg/50">
+ {group.rows.length}
+ </span>
+ </button>
+ {open && (
+ <ul className="pb-1">
+ {group.rows.map((row) => (
+ <li key={row.key}>
+ <button
+ type="button"
+ disabled={!row.previewPath}
+ onClick={() =>
+ row.previewPath && onPreview(row.previewPath)
+ }
+ title={row.previewPath}
+ className={cn(
+ 'flex w-full items-center gap-2 py-1.5 pl-9 pr-3 text-left text-xs',
+ row.previewPath
+ ? 'hover:bg-muted/50'
+ : 'cursor-default text-main-view-fg/50'
+ )}
+ >
+ <span className="min-w-0 flex-1 truncate">
+ {row.name}
+ </span>
+ {row.detail ? (
+ <span className="shrink-0 italic">{row.detail}</span>
+ ) : (
+ <span className="shrink-0 font-mono text-main-view-fg/50">
+ {row.label}
+ </span>
+ )}
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )
+ })}
+ </div>
+ )}
+ </div>
+ </CoworkSidePanel>
+ )
+}
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index 1edde4832..e0af670b7 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -640,7 +640,7 @@ export const MessageItem = memo(
)}
{/* Message actions for assistant messages (non-tool) */}
- {message.role === 'assistant' && (
+ {message.role === 'assistant' && !hideActions && (
<div className="flex items-center gap-2 text-muted-foreground text-xs">
{!isStreaming && (
<span className="text-muted-foreground">
diff --git a/web-app/src/containers/__tests__/ChatInput.test.tsx b/web-app/src/containers/__tests__/ChatInput.test.tsx
index 01f27734d..5c89f56f6 100644
--- a/web-app/src/containers/__tests__/ChatInput.test.tsx
+++ b/web-app/src/containers/__tests__/ChatInput.test.tsx
@@ -398,7 +398,7 @@ describe('ChatInput', () => {
renderInput({ onSubmit })
fireEvent.keyDown(getTextarea(), { key: 'Enter' })
await waitFor(() =>
- expect(onSubmit).toHaveBeenCalledWith('hello world', undefined)
+ expect(onSubmit).toHaveBeenCalledWith('hello world', undefined, undefined)
)
expect(addToHistoryMock).toHaveBeenCalledWith('hello world')
expect(setPromptMock).toHaveBeenCalledWith('')
@@ -432,7 +432,7 @@ describe('ChatInput', () => {
) as HTMLButtonElement
fireEvent.click(btn)
await waitFor(() =>
- expect(onSubmit).toHaveBeenCalledWith('button submit', undefined)
+ expect(onSubmit).toHaveBeenCalledWith('button submit', undefined, undefined)
)
})
@@ -546,12 +546,28 @@ describe('ChatInput', () => {
mediaType: 'image/png',
url: 'data:image/png;base64,xxx',
}),
- ])
+ ]),
+ undefined
)
)
expect(clearAttachmentsMock).toHaveBeenCalled()
})
+ it('passes document attachments to onSubmit as the third argument', async () => {
+ promptState = 'read this'
+ attachmentsList = [
+ { type: 'document', name: 'spec.pdf', path: '/docs/spec.pdf', fileType: 'pdf' },
+ ]
+ const onSubmit = vi.fn()
+ renderInput({ onSubmit })
+ fireEvent.keyDown(getTextarea(), { key: 'Enter' })
+ await waitFor(() =>
+ expect(onSubmit).toHaveBeenCalledWith('read this', undefined, [
+ expect.objectContaining({ name: 'spec.pdf', path: '/docs/spec.pdf' }),
+ ])
+ )
+ })
+
it('shows the queued-message chips from the message queue', () => {
queueState['thread-1'] = [
{ id: 'q1', text: 'queued one', createdAt: 1 },
diff --git a/web-app/src/containers/__tests__/CoworkFilesPanel.test.tsx b/web-app/src/containers/__tests__/CoworkFilesPanel.test.tsx
new file mode 100644
index 000000000..e0ca8b213
--- /dev/null
+++ b/web-app/src/containers/__tests__/CoworkFilesPanel.test.tsx
@@ -0,0 +1,96 @@
+import { describe, it, expect, vi } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({
+ t: (k: string, opts?: Record<string, unknown>) =>
+ opts ? `${k} ${Object.values(opts).join(' ')}` : k,
+ }),
+}))
+
+import { CoworkFilesPanel } from '../CoworkFilesPanel'
+import { CoworkFilesChip } from '../CoworkFilesChip'
+import { artifactFor } from '@/lib/coworkArtifacts'
+
+const pdf = {
+ name: 'spec.pdf',
+ path: '/home/me/spec.pdf',
+ fileType: 'pdf',
+ workspacePath: '/ws/attachments/spec.pdf',
+}
+const lost = { name: 'gone.docx', path: '/home/me/gone.docx', fileType: 'docx' }
+const html = artifactFor('site/index.html')!
+const png = artifactFor('chart.png')!
+
+describe('CoworkFilesChip', () => {
+ it('renders nothing with no files, and the count otherwise', () => {
+ const { container } = render(
+ <CoworkFilesChip count={0} open={false} onToggle={vi.fn()} />
+ )
+ expect(container).toBeEmptyDOMElement()
+ render(<CoworkFilesChip count={3} open={true} onToggle={vi.fn()} />)
+ expect(screen.getByText('3')).toBeInTheDocument()
+ expect(screen.getByRole('button')).toHaveAttribute('aria-pressed', 'true')
+ })
+})
+
+describe('CoworkFilesPanel', () => {
+ it('shows the empty notice with nothing to list', () => {
+ render(
+ <CoworkFilesPanel
+ attachments={[]}
+ artifacts={[]}
+ onPreview={vi.fn()}
+ onClose={vi.fn()}
+ />
+ )
+ expect(screen.getByText('common:files.empty')).toBeInTheDocument()
+ })
+
+ it('groups attachments first, then artifacts by family', () => {
+ render(
+ <CoworkFilesPanel
+ attachments={[pdf]}
+ artifacts={[png, html]}
+ onPreview={vi.fn()}
+ onClose={vi.fn()}
+ />
+ )
+ const headers = screen
+ .getAllByRole('button', { expanded: true })
+ .map((b) => b.textContent)
+ expect(headers[0]).toContain('common:files.attachments')
+ expect(headers[1]).toContain('common:artifactGroupCode')
+ expect(headers[2]).toContain('common:artifactGroupImage')
+ expect(screen.getByText('spec.pdf')).toBeInTheDocument()
+ expect(screen.getByText('index.html')).toBeInTheDocument()
+ expect(screen.getByText('chart.png')).toBeInTheDocument()
+ })
+
+ it('previews a row by its workspace path, and folds a group', async () => {
+ const onPreview = vi.fn()
+ render(
+ <CoworkFilesPanel
+ attachments={[pdf, lost]}
+ artifacts={[html]}
+ onPreview={onPreview}
+ onClose={vi.fn()}
+ />
+ )
+ await userEvent.click(screen.getByText('spec.pdf'))
+ expect(onPreview).toHaveBeenCalledWith('/ws/attachments/spec.pdf')
+ await userEvent.click(screen.getByText('index.html'))
+ expect(onPreview).toHaveBeenCalledWith('site/index.html')
+
+ // Never imported: nothing to open, and the row says so.
+ expect(screen.getByText('gone.docx').closest('button')).toBeDisabled()
+ expect(screen.getByText('common:files.notImported')).toBeInTheDocument()
+
+ await userEvent.click(
+ screen.getByRole('button', { name: /common:files.attachments/ })
+ )
+ expect(screen.queryByText('spec.pdf')).not.toBeInTheDocument()
+ expect(screen.getByText('index.html')).toBeInTheDocument()
+ })
+})
diff --git a/web-app/src/containers/__tests__/MessageItem.test.tsx b/web-app/src/containers/__tests__/MessageItem.test.tsx
index 722a54197..99095b341 100644
--- a/web-app/src/containers/__tests__/MessageItem.test.tsx
+++ b/web-app/src/containers/__tests__/MessageItem.test.tsx
@@ -352,6 +352,20 @@ describe('MessageItem', () => {
expect(screen.queryByTestId('delete-btn')).not.toBeInTheDocument()
})
+ it('hideActions drops the whole assistant row, timestamp included', () => {
+ render(
+ <MessageItem
+ message={makeMsg() as any}
+ isFirstMessage
+ isLastMessage={false}
+ status={'ready' as any}
+ hideActions
+ />
+ )
+ expect(screen.queryByText('2024-01-01')).not.toBeInTheDocument()
+ expect(screen.queryByTestId('token-speed')).not.toBeInTheDocument()
+ })
+
it('streaming state hides edit/delete and marks token speed streaming', () => {
render(
<MessageItem
diff --git a/web-app/src/hooks/useCoworkRun.ts b/web-app/src/hooks/useCoworkRun.ts
index 99c94c50d..12e30bef7 100644
--- a/web-app/src/hooks/useCoworkRun.ts
+++ b/web-app/src/hooks/useCoworkRun.ts
@@ -1,11 +1,13 @@
import { create } from 'zustand'
import type {
+ CoworkMediaPart,
CoworkTurn,
SubagentRun,
Usage,
TodoList,
AskRequestPayload,
} from '@/types/coworkSession'
+import { userTurn } from '@/lib/coworkTurns'
import type { ModelLoadProgress } from '@/hooks/useAppState'
// The ask shapes live in the store-free types module; re-exported here because
@@ -173,7 +175,7 @@ type CoworkRunState = {
loadingModels: Record<string, boolean>
modelLoadProgress: Record<string, ModelLoadProgress>
- beginRun: (sid: string, runId: string, userText: string, images?: string[]) => void
+ beginRun: (sid: string, runId: string, userText: string, media?: CoworkMediaPart[]) => void
appendToken: (sid: string, text: string) => void
pushToolTurn: (sid: string, turn: CoworkTurn) => void
updateToolTurn: (sid: string, callId: string, patch: Partial<CoworkTurn>) => void
@@ -222,12 +224,12 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({
loadingModels: {},
modelLoadProgress: {},
- beginRun: (sid, runId, userText, images) =>
+ beginRun: (sid, runId, userText, media) =>
set((s) => ({
runId: { ...s.runId, [sid]: runId },
liveTurns: {
...s.liveTurns,
- [sid]: [{ role: 'user', content: userText, images }],
+ [sid]: [userTurn(userText, media)],
},
subagents: { ...s.subagents, [sid]: [] },
pendingAsks: { ...s.pendingAsks, [sid]: [] },
diff --git a/web-app/src/lib/__tests__/agentTools.test.ts b/web-app/src/lib/__tests__/agentTools.test.ts
index 515a73017..583653987 100644
--- a/web-app/src/lib/__tests__/agentTools.test.ts
+++ b/web-app/src/lib/__tests__/agentTools.test.ts
@@ -21,6 +21,7 @@ vi.mock('@janhq/tauri-plugin-agent-tools-api', () => ({
memoryRead: (...args: unknown[]) => memoryRead(...args),
subagentResultReserve: (...args: unknown[]) => subagentResultReserve(...args),
subagentResultFill: (...args: unknown[]) => subagentResultFill(...args),
+ attachmentImport: vi.fn(),
}))
vi.mock('@/hooks/useServiceHub', () => ({
diff --git a/web-app/src/lib/__tests__/coworkAttachments.test.ts b/web-app/src/lib/__tests__/coworkAttachments.test.ts
new file mode 100644
index 000000000..bd4cab546
--- /dev/null
+++ b/web-app/src/lib/__tests__/coworkAttachments.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, it, vi } from 'vitest'
+import {
+ importAttachedFiles,
+ withAttachedFiles,
+} from '@/lib/coworkAttachments'
+import type { CoworkAttachedFile } from '@/types/coworkSession'
+
+const pdf: CoworkAttachedFile = {
+ name: 'spec.pdf',
+ path: '/home/me/spec.pdf',
+ fileType: 'pdf',
+ size: 10,
+}
+
+describe('importAttachedFiles', () => {
+ it('parses then imports each file, recording the workspace copies', async () => {
+ const parse = vi.fn().mockResolvedValue('the words')
+ const importFile = vi.fn().mockResolvedValue({
+ path: '/ws/attachments/spec.pdf',
+ textPath: '/ws/attachments/spec.pdf.txt',
+ })
+ const out = await importAttachedFiles([pdf], { parse, importFile })
+ expect(parse).toHaveBeenCalledWith('/home/me/spec.pdf', 'pdf')
+ expect(importFile).toHaveBeenCalledWith('/home/me/spec.pdf', 'the words')
+ expect(out).toEqual([
+ {
+ ...pdf,
+ workspacePath: '/ws/attachments/spec.pdf',
+ textPath: '/ws/attachments/spec.pdf.txt',
+ },
+ ])
+ })
+
+ it('imports without text when the parser has nothing to say', async () => {
+ const parse = vi.fn().mockResolvedValue('')
+ const importFile = vi
+ .fn()
+ .mockResolvedValue({ path: '/ws/attachments/a.bin', textPath: null })
+ const out = await importAttachedFiles(
+ [{ name: 'a.bin', path: '/x/a.bin' }],
+ { parse, importFile }
+ )
+ expect(importFile).toHaveBeenCalledWith('/x/a.bin', undefined)
+ expect(out[0]).toEqual({
+ name: 'a.bin',
+ path: '/x/a.bin',
+ workspacePath: '/ws/attachments/a.bin',
+ })
+ })
+
+ it('skips a file already in the workspace (a re-ask)', async () => {
+ const parse = vi.fn()
+ const importFile = vi.fn()
+ const done = { ...pdf, workspacePath: '/ws/attachments/spec.pdf' }
+ const out = await importAttachedFiles([done], { parse, importFile })
+ expect(parse).not.toHaveBeenCalled()
+ expect(importFile).not.toHaveBeenCalled()
+ expect(out).toEqual([done])
+ })
+
+ it('keeps a file whose import failed, unimported, so the prompt can say so', async () => {
+ const parse = vi.fn().mockRejectedValue(new Error('no parser'))
+ const importFile = vi.fn().mockResolvedValue(null)
+ const out = await importAttachedFiles([pdf], { parse, importFile })
+ expect(importFile).toHaveBeenCalledWith('/home/me/spec.pdf', undefined)
+ expect(out).toEqual([pdf])
+ })
+})
+
+describe('withAttachedFiles', () => {
+ it('returns the question untouched with nothing attached', () => {
+ expect(withAttachedFiles('hi', undefined)).toBe('hi')
+ expect(withAttachedFiles('hi', [])).toBe('hi')
+ })
+
+ it('names the copy and its extracted text, and flags a failed import', () => {
+ const text = withAttachedFiles('summarize', [
+ {
+ ...pdf,
+ workspacePath: '/ws/attachments/spec.pdf',
+ textPath: '/ws/attachments/spec.pdf.txt',
+ },
+ { name: 'raw.bin', path: '/x/raw.bin', workspacePath: '/ws/attachments/raw.bin' },
+ { name: 'gone.pdf', path: '/x/gone.pdf' },
+ ])
+ expect(text.startsWith('summarize\n\n')).toBe(true)
+ expect(text).toContain('- spec.pdf: /ws/attachments/spec.pdf (extracted text: /ws/attachments/spec.pdf.txt)')
+ expect(text).toContain('- raw.bin: /ws/attachments/raw.bin')
+ expect(text).toContain('- gone.pdf: could not be copied into the workspace')
+ expect(text).not.toContain('[ATTACHED_FILES]')
+ })
+})
diff --git a/web-app/src/lib/__tests__/coworkFiles.test.ts b/web-app/src/lib/__tests__/coworkFiles.test.ts
new file mode 100644
index 000000000..0bbead4a1
--- /dev/null
+++ b/web-app/src/lib/__tests__/coworkFiles.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest'
+import { sessionAttachments } from '@/lib/coworkFiles'
+import type { CoworkTurn } from '@/types/coworkSession'
+
+describe('sessionAttachments', () => {
+ it('collects documents off user turns, skipping everything else', () => {
+ const turns: CoworkTurn[] = [
+ { role: 'user', content: 'a', files: [{ name: 'a.pdf', path: '/a.pdf' }] },
+ { role: 'assistant', content: 'ok' },
+ { role: 'tool', content: '', name: 'write', args: { path: 'x.md' } },
+ { role: 'user', content: 'b', files: [{ name: 'b.csv', path: '/b.csv' }] },
+ { role: 'user', content: 'c' },
+ ]
+ expect(sessionAttachments(turns).map((f) => f.name)).toEqual(['a.pdf', 'b.csv'])
+ })
+
+ it('keeps one entry per source path, preferring the later record', () => {
+ const turns: CoworkTurn[] = [
+ { role: 'user', content: 'a', files: [{ name: 'a.pdf', path: '/a.pdf' }] },
+ {
+ role: 'user',
+ content: 'again',
+ files: [{ name: 'a.pdf', path: '/a.pdf', workspacePath: '/ws/attachments/a.pdf' }],
+ },
+ ]
+ expect(sessionAttachments(turns)).toEqual([
+ { name: 'a.pdf', path: '/a.pdf', workspacePath: '/ws/attachments/a.pdf' },
+ ])
+ })
+
+ it('is empty with no turns', () => {
+ expect(sessionAttachments(undefined)).toEqual([])
+ expect(sessionAttachments([])).toEqual([])
+ })
+})
diff --git a/web-app/src/lib/__tests__/coworkTurns.test.ts b/web-app/src/lib/__tests__/coworkTurns.test.ts
index a415bad86..ed598169c 100644
--- a/web-app/src/lib/__tests__/coworkTurns.test.ts
+++ b/web-app/src/lib/__tests__/coworkTurns.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { coworkTurnsToUIMessages } from '@/lib/coworkTurns'
+import { coworkTurnsToUIMessages, userTurn } from '@/lib/coworkTurns'
import type { CoworkTurn } from '@/hooks/useCoworkSessions'
/* eslint-disable @typescript-eslint/no-explicit-any */
@@ -181,4 +181,45 @@ describe('coworkTurnsToUIMessages', () => {
const live = coworkTurnsToUIMessages(turns, 'l')
expect(committed[0].id).not.toBe(live[0].id)
})
+
+ describe('user attachments', () => {
+ const png = { type: 'file' as const, mediaType: 'image/png', url: 'data:image/png;base64,AA' }
+ const pdf = { name: 'spec.pdf', path: '/docs/spec.pdf', fileType: 'pdf', size: 1234 }
+
+ it('userTurn keeps media and files beside the question', () => {
+ expect(userTurn('read this', [png], [pdf])).toEqual({
+ role: 'user',
+ content: 'read this',
+ media: [png],
+ files: [pdf],
+ })
+ })
+
+ it('userTurn omits empty attachment lists', () => {
+ expect(userTurn('plain')).toEqual({ role: 'user', content: 'plain' })
+ expect(userTurn('plain', [], [])).toEqual({ role: 'user', content: 'plain' })
+ })
+
+ it('renders attached media as file parts after the text', () => {
+ const parts = partsOf(coworkTurnsToUIMessages([userTurn('look', [png])]))
+ expect(parts).toEqual([{ type: 'text', text: 'look' }, png])
+ })
+
+ it('renders attached documents as the [ATTACHED_FILES] block MessageItem reads', () => {
+ const parts = partsOf(coworkTurnsToUIMessages([userTurn('summarize', undefined, [pdf])]))
+ expect(parts).toHaveLength(1)
+ const text = parts[0].text as string
+ expect(text.startsWith('summarize')).toBe(true)
+ expect(text).toContain('[ATTACHED_FILES]')
+ expect(text).toContain('name: spec.pdf')
+ expect(text).toContain('type: pdf')
+ expect(text).toContain('size: 1234')
+ })
+
+ it('leaves a turn with no attachments as a bare text part', () => {
+ expect(partsOf(coworkTurnsToUIMessages([userTurn('hi')]))).toEqual([
+ { type: 'text', text: 'hi' },
+ ])
+ })
+ })
})
diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.ts
index bc6990256..b02475824 100644
--- a/web-app/src/lib/agentTools.ts
+++ b/web-app/src/lib/agentTools.ts
@@ -8,6 +8,7 @@ import {
memoryRead,
subagentResultReserve,
subagentResultFill,
+ attachmentImport,
startMonitor,
stopMonitor,
listMonitors,
@@ -393,6 +394,26 @@ export async function fillSubagentResult(
}
}
+/**
+ * Copy a user attachment into the session workspace, with its extracted text
+ * beside it. `null` when it could not be copied, so the caller can tell the
+ * agent instead of naming a path that is not there.
+ */
+export async function importAttachment(
+ sessionId: string,
+ source: string,
+ text?: string
+): Promise<{ path: string; textPath: string | null } | null> {
+ try {
+ const dataFolder = await getServiceHub().app().getJanDataFolder()
+ if (!dataFolder) return null
+ return await attachmentImport(dataFolder, sessionId, source, text)
+ } catch (e) {
+ console.warn('[agentTools] Failed to import attachment:', messageOf(e))
+ return null
+ }
+}
+
/**
* Delete a thread's sandbox. Best-effort: a failure here leaves a directory
* behind for the next startup sweep to collect, which is not worth surfacing
diff --git a/web-app/src/lib/coworkAttachments.ts b/web-app/src/lib/coworkAttachments.ts
new file mode 100644
index 000000000..49d4a5dea
--- /dev/null
+++ b/web-app/src/lib/coworkAttachments.ts
@@ -0,0 +1,68 @@
+import type { CoworkAttachedFile } from '@/types/coworkSession'
+
+/**
+ * Attached documents reach the agent as files in its workspace, not as
+ * retrieval results: the file picker hands us a path outside every root the
+ * file tools may read, so the file is copied in, and a binary format gets an
+ * extracted-text sibling because `read` refuses non-UTF-8 content.
+ */
+export type AttachmentImportDeps = {
+ /** Text extracted from the document, or '' when no parser can read it. */
+ parse: (path: string, fileType?: string) => Promise<string>
+ /** The workspace copy, or null when it could not be made. */
+ importFile: (
+ path: string,
+ text?: string
+ ) => Promise<{ path: string; textPath: string | null } | null>
+}
+
+/**
+ * Import every file not already in the workspace. A file that fails to import
+ * is kept as it was, so the wire text can tell the agent rather than have it
+ * hunt for a path that does not exist.
+ */
+export async function importAttachedFiles(
+ files: CoworkAttachedFile[],
+ deps: AttachmentImportDeps
+): Promise<CoworkAttachedFile[]> {
+ const out: CoworkAttachedFile[] = []
+ for (const file of files) {
+ if (file.workspacePath) {
+ out.push(file)
+ continue
+ }
+ const text = await deps.parse(file.path, file.fileType).catch(() => '')
+ const imported = await deps.importFile(file.path, text || undefined)
+ if (!imported) {
+ out.push(file)
+ continue
+ }
+ const next: CoworkAttachedFile = { ...file, workspacePath: imported.path }
+ if (imported.textPath) next.textPath = imported.textPath
+ out.push(next)
+ }
+ return out
+}
+
+/** The question as the model sees it: the text, then where each attachment is. */
+export function withAttachedFiles(
+ text: string,
+ files: CoworkAttachedFile[] | undefined
+): string {
+ if (!files?.length) return text
+ const lines = files.map((f) => {
+ if (!f.workspacePath) {
+ return `- ${f.name}: could not be copied into the workspace`
+ }
+ const extracted = f.textPath ? ` (extracted text: ${f.textPath})` : ''
+ return `- ${f.name}: ${f.workspacePath}${extracted}`
+ })
+ return [
+ text,
+ '',
+ 'The user attached these files, copied into your workspace. Read the',
+ 'extracted text where one is listed; the original is beside it for tools',
+ 'that need the file itself.',
+ ...lines,
+ ].join('\n')
+}
diff --git a/web-app/src/lib/coworkFiles.ts b/web-app/src/lib/coworkFiles.ts
new file mode 100644
index 000000000..e1129a1cc
--- /dev/null
+++ b/web-app/src/lib/coworkFiles.ts
@@ -0,0 +1,19 @@
+import type { CoworkAttachedFile, CoworkTurn } from '@/types/coworkSession'
+
+/**
+ * Every document the user attached across the session, in the order they were
+ * attached and deduplicated by source path: the same file attached to two
+ * questions is one file. Later turns win, so a copy imported on a re-ask
+ * supersedes the record of the failed first attempt.
+ */
+export function sessionAttachments(
+ turns: CoworkTurn[] | undefined
+): CoworkAttachedFile[] {
+ if (!turns?.length) return []
+ const byPath = new Map<string, CoworkAttachedFile>()
+ for (const turn of turns) {
+ if (turn.role !== 'user' || !turn.files?.length) continue
+ for (const file of turn.files) byPath.set(file.path, file)
+ }
+ return [...byPath.values()]
+}
diff --git a/web-app/src/lib/coworkTransport.ts b/web-app/src/lib/coworkTransport.ts
index 9ed1b5f7c..3521cd4b1 100644
--- a/web-app/src/lib/coworkTransport.ts
+++ b/web-app/src/lib/coworkTransport.ts
@@ -1,4 +1,4 @@
-import type { Tool, UIMessage } from 'ai'
+import type { Tool } from 'ai'
import { CustomChatTransport } from '@/lib/custom-chat-transport'
import { COWORK_SLOT_ID } from '@/constants/models'
import {
@@ -88,11 +88,12 @@ export class CoworkChatTransport extends CustomChatTransport {
/**
* Cowork's own prompt replaces the chat one wholesale — the agent-tools and
* web-search blurbs are written for a chat that occasionally reaches for a
- * tool, not for a run whose whole purpose is tool use. The attached-files
- * instruction is kept: a pasted document is otherwise never explained.
+ * tool, not for a run whose whole purpose is tool use. Attached documents
+ * need no instruction here either: they are copied into the workspace and
+ * named in the question itself (`withAttachedFiles`).
*/
- protected override buildSystemPrompt(messages: UIMessage[]): string {
- const base = buildCoworkSystemPrompt({
+ protected override buildSystemPrompt(): string {
+ return buildCoworkSystemPrompt({
workspacePath: this.config.workspacePath,
readOnlyFolder: this.config.readOnlyFolder,
planMode: this.config.planMode,
@@ -102,8 +103,6 @@ export class CoworkChatTransport extends CustomChatTransport {
memoryCatalog: this.memoryCatalog,
environment: this.environment,
})
- const files = this.buildFilesSystemInstruction(messages)
- return files.trim().length > 0 ? `${base}\n\n${files}` : base
}
/**
diff --git a/web-app/src/lib/coworkTurns.ts b/web-app/src/lib/coworkTurns.ts
index ca2c8ef3c..b6b38fde1 100644
--- a/web-app/src/lib/coworkTurns.ts
+++ b/web-app/src/lib/coworkTurns.ts
@@ -1,6 +1,11 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { UIMessage } from 'ai'
-import type { CoworkTurn } from '@/types/coworkSession'
+import type {
+ CoworkAttachedFile,
+ CoworkMediaPart,
+ CoworkTurn,
+} from '@/types/coworkSession'
+import { injectFilesIntoPrompt } from '@/lib/fileMetadata'
import { reasoningPartsFromText } from '@/lib/messages'
import { partialToolInput } from '@/lib/partialJson'
@@ -18,6 +23,38 @@ import { partialToolInput } from '@/lib/partialJson'
* real coloured diff by `AgentToolWidget`, keyed on `toolCallId`. Folding it into
* the output text would also corrupt the output the widget parses.
*/
+/** The transcript row for a question, with whatever was attached to it. */
+export function userTurn(
+ text: string,
+ media?: CoworkMediaPart[],
+ files?: CoworkAttachedFile[]
+): CoworkTurn {
+ const turn: CoworkTurn = { role: 'user', content: text }
+ if (media?.length) turn.media = media
+ if (files?.length) turn.files = files
+ return turn
+}
+
+/**
+ * Attached documents ride in the text as an `[ATTACHED_FILES]` block, which is
+ * what `MessageItem` already parses into chips for the chat surface; media
+ * follow as `file` parts, which it renders as thumbnails.
+ */
+function userMessageParts(turn: CoworkTurn): unknown[] {
+ const text = turn.files?.length
+ ? injectFilesIntoPrompt(
+ turn.content,
+ turn.files.map((f) => ({
+ id: f.path,
+ name: f.name,
+ type: f.fileType,
+ size: f.size,
+ }))
+ )
+ : turn.content
+ return [{ type: 'text', text }, ...(turn.media ?? [])]
+}
+
export function coworkTurnsToUIMessages(
turns: CoworkTurn[],
idPrefix = 'code'
@@ -47,7 +84,7 @@ export function coworkTurnsToUIMessages(
messages.push({
id: `${idPrefix}-user-${i}`,
role: 'user',
- parts: [{ type: 'text', text: turn.content }],
+ parts: userMessageParts(turn),
} as any)
return
}
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index 09829e0fa..c445c69e3 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -612,7 +612,12 @@
"fileTooLargeDescription": "{{fileName}} exceeds the {{maxFileSizeMB}}MB limit"
},
"files": {
- "chunksCount": "{{count}} chunks"
+ "chunksCount": "{{count}} chunks",
+ "title": "Files",
+ "empty": "Files you attach and files the agent creates will show up here.",
+ "a11y": "Files: {{count}}",
+ "attachments": "Attachments",
+ "notImported": "not in workspace"
},
"llamacppBusyOnExit": {
"title": "llama.cpp is still busy",
diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsx
index 934e3018a..55a93f118 100644
--- a/web-app/src/routes/cowork.tsx
+++ b/web-app/src/routes/cowork.tsx
@@ -31,12 +31,24 @@ import {
useCoworkSessions,
ensureCurrentSession,
} from '@/hooks/useCoworkSessions'
-import type { AskAnswer, CoworkTurn, Usage } from '@/types/coworkSession'
+import type {
+ AskAnswer,
+ CoworkAttachedFile,
+ CoworkMediaPart,
+ CoworkTurn,
+ Usage,
+} from '@/types/coworkSession'
+import type { Attachment } from '@/types/attachment'
import DropdownModelProvider from '@/containers/DropdownModelProvider'
import { useModelProvider } from '@/hooks/useModelProvider'
import { MessageItem } from '@/containers/MessageItem'
import SkillSelector from '@/containers/SkillSelector'
-import { coworkTurnsToUIMessages } from '@/lib/coworkTurns'
+import { coworkTurnsToUIMessages, userTurn } from '@/lib/coworkTurns'
+import { extractFilesFromPrompt } from '@/lib/fileMetadata'
+import {
+ importAttachedFiles,
+ withAttachedFiles,
+} from '@/lib/coworkAttachments'
import { useToolCallRuntime, withToolTiming } from '@/hooks/useToolCallRuntime'
import { PromptProgress } from '@/components/PromptProgress'
import { useAppState } from '@/hooks/useAppState'
@@ -51,13 +63,16 @@ import { CoworkPlanToggle } from '@/containers/CoworkPlanToggle'
import { CoworkEmptyState } from '@/containers/CoworkEmptyState'
import { usePrompt } from '@/hooks/usePrompt'
import { awaitsModel } from '@/lib/agentActivity'
-import { artifactsFromParts } from '@/lib/coworkArtifacts'
+import { artifactsFromParts, artifactsFromTurns } from '@/lib/coworkArtifacts'
+import { sessionAttachments } from '@/lib/coworkFiles'
import { CoworkArtifactCard } from '@/containers/CoworkArtifactCard'
import { CoworkPreviewPanel } from '@/containers/CoworkPreviewPanel'
import { CoworkDiffPanel } from '@/containers/CoworkDiffPanel'
import { CoworkTodoPanel } from '@/containers/CoworkTodoPanel'
import { CoworkTasksPanel } from '@/containers/CoworkTasksPanel'
import { CoworkChangesChip } from '@/containers/CoworkChangesChip'
+import { CoworkFilesChip } from '@/containers/CoworkFilesChip'
+import { CoworkFilesPanel } from '@/containers/CoworkFilesPanel'
import { CoworkTodoChip } from '@/containers/CoworkTodoChip'
import { CoworkTasksChip } from '@/containers/CoworkTasksChip'
import { collectCodeFileDiffs } from '@/lib/coworkDiffs'
@@ -74,6 +89,7 @@ import {
getSandboxStatus,
sandboxEnforces,
fillSubagentResult,
+ importAttachment,
reserveSubagentResult,
stopAgentSessionMonitors,
} from '@/lib/agentTools'
@@ -165,6 +181,7 @@ function CoworkPage() {
const [rail, setRail] = useState<
| { kind: 'preview'; path: string }
| { kind: 'diff' }
+ | { kind: 'files' }
| { kind: 'todos' }
| { kind: 'tasks' }
| null
@@ -290,6 +307,14 @@ function CoworkPage() {
() => collectCodeFileDiffs(displayedTurns, subagents),
[displayedTurns, subagents]
)
+ const attachments = useMemo(
+ () => sessionAttachments(displayedTurns),
+ [displayedTurns]
+ )
+ const artifacts = useMemo(
+ () => artifactsFromTurns(displayedTurns, workspacePath),
+ [displayedTurns, workspacePath]
+ )
const awaitingModel = useMemo(
() => awaitsModel(running, displayedTurns),
@@ -306,7 +331,15 @@ function CoworkPage() {
* re-runs the committed history rather than re-sending the question, which
* would leave the model reading it twice.
*/
- const runRequest = async (text: string | null) => {
+ type CoworkAttachments = {
+ media?: CoworkMediaPart[]
+ files?: CoworkAttachedFile[]
+ }
+
+ const runRequest = async (
+ text: string | null,
+ attachments?: CoworkAttachments
+ ) => {
if (running) return
const sid = ensureCurrentSession()
const store = useCoworkSessions.getState()
@@ -331,12 +364,16 @@ function CoworkPage() {
setStoppedBy(null)
setRunError(undefined)
setLiveUsage(null)
- liveTurnsRef.current = text ? [{ role: 'user', content: text }] : []
+ liveTurnsRef.current = text
+ ? [userTurn(text, attachments?.media, attachments?.files)]
+ : []
setLiveTurns(liveTurnsRef.current)
// Marks the session running in the store (and resets its subagent lanes),
// so surfaces outside this component — the sidebar's per-session spinner
// and its empty-session filter — can see a run this component owns.
- useCoworkRun.getState().beginRun(sid, crypto.randomUUID(), text ?? '')
+ useCoworkRun
+ .getState()
+ .beginRun(sid, crypto.randomUUID(), text ?? '', attachments?.media)
setRunSid(sid)
setRunning(true)
@@ -354,6 +391,20 @@ function CoworkPage() {
}
}
+ // Documents go into the workspace before the question is sent, so the
+ // paths the question names exist by the time the agent reads them. The
+ // row was shown first: parsing a large PDF takes a moment.
+ let files = attachments?.files
+ if (text && files?.length) {
+ files = await importAttachedFiles(files, {
+ parse: async (path, fileType) =>
+ (await serviceHub.rag().parseDocument?.(path, fileType)) ?? '',
+ importFile: (path, parsed) => importAttachment(sid, path, parsed),
+ })
+ liveTurnsRef.current = [userTurn(text, attachments?.media, files)]
+ setLiveTurns(liveTurnsRef.current)
+ }
+
// Warm the sandbox probe: the transport's prompt and tool set read it
// synchronously via sandboxEnforces().
await getSandboxStatus()
@@ -443,7 +494,10 @@ function CoworkPage() {
{
id: `${sid}-user-${baseMessages.length}`,
role: 'user',
- parts: [{ type: 'text', text }],
+ parts: [
+ { type: 'text', text: withAttachedFiles(text, files) },
+ ...(attachments?.media ?? []),
+ ],
} as any,
]
: [...baseMessages]
@@ -787,7 +841,11 @@ function CoworkPage() {
}
}
- const handleSubmit = (text: string) => {
+ const handleSubmit = (
+ text: string,
+ files?: CoworkMediaPart[],
+ documents?: Attachment[]
+ ) => {
// Slash commands are client-side actions; they never reach the agent.
if (text.trim().startsWith('/')) {
runSlashCommand(text, {
@@ -800,7 +858,17 @@ function CoworkPage() {
})
return
}
- void runRequest(text)
+ void runRequest(text, {
+ media: files,
+ files: documents
+ ?.filter((d): d is Attachment & { path: string } => !!d.path)
+ .map((d) => ({
+ name: d.name,
+ path: d.path,
+ fileType: d.fileType,
+ size: d.size,
+ })),
+ })
}
// Slash-command menu: the input text lives in the shared usePrompt store, so
@@ -959,13 +1027,19 @@ function CoworkPage() {
*/
const handleEditQuestion = useCallback(
(messageId: string, newText: string) => {
- if (running || !session?.id || !newText.trim()) return
+ // The rendered text carries the [ATTACHED_FILES] chips block; the
+ // question itself is what precedes it.
+ const text = extractFilesFromPrompt(newText).cleanPrompt
+ if (running || !session?.id || !text.trim()) return
const index = questionTurnIndex(messageId)
if (index < 0) return
+ // The attachments stay with the question: a re-ask without them would
+ // silently ask something else.
+ const { media, files } = displayedTurns[index]
useCoworkSessions.getState().dropFromTurn(session.id, index)
- void runRequestRef.current(newText)
+ void runRequestRef.current(text, { media, files })
},
- [running, session?.id, questionTurnIndex]
+ [running, session?.id, questionTurnIndex, displayedTurns]
)
/** Ask a question again unchanged, from a point partway up the transcript. */
@@ -1072,6 +1146,10 @@ function CoworkPage() {
? handleRetryQuestion
: undefined
}
+ // A system note (a subagent finishing) splits one agent
+ // turn into two assistant messages; the first is not
+ // an answer, so it gets no timestamp or actions row.
+ hideActions={uiMessages[i + 1]?.role === 'system'}
onDelete={
message.role === 'user'
? handleDeleteQuestion
@@ -1236,6 +1314,15 @@ function CoworkPage() {
)
}
/>
+ <CoworkFilesChip
+ count={attachments.length + artifacts.length}
+ open={rail?.kind === 'files'}
+ onToggle={() =>
+ setRail((r) =>
+ r?.kind === 'files' ? null : { kind: 'files' }
+ )
+ }
+ />
<div className="ml-auto flex items-center">
<SkillSelector folder={folder} />
</div>
@@ -1257,6 +1344,14 @@ function CoworkPage() {
{rail?.kind === 'diff' && (
<CoworkDiffPanel files={fileDiffs} onClose={() => setRail(null)} />
)}
+ {rail?.kind === 'files' && (
+ <CoworkFilesPanel
+ attachments={attachments}
+ artifacts={artifacts}
+ onPreview={showPreview}
+ onClose={() => setRail(null)}
+ />
+ )}
{rail?.kind === 'todos' && (
<CoworkTodoPanel
todos={session?.todos}
diff --git a/web-app/src/types/coworkSession.ts b/web-app/src/types/coworkSession.ts
index 3ff06f0cf..80c6d4104 100644
--- a/web-app/src/types/coworkSession.ts
+++ b/web-app/src/types/coworkSession.ts
@@ -23,8 +23,11 @@ export type CoworkTurn = {
* `<think>` reasoning stays inside `content` (that is what the model sent)
* and is split out at render time instead. */
reasoning?: string
- /** User-row only: data URLs of images attached via paste/file picker. */
- images?: string[]
+ /** User-row only: images/audio/video attached to the question, as the
+ * `file` parts the model received. */
+ media?: CoworkMediaPart[]
+ /** User-row only: documents attached to the question. */
+ files?: CoworkAttachedFile[]
callId?: string
name?: string
args?: unknown
@@ -37,6 +40,26 @@ export type CoworkTurn = {
status?: 'running' | 'done'
}
+/** A pasted or picked image/audio/video, shaped as an AI SDK `file` part. */
+export type CoworkMediaPart = {
+ type: 'file'
+ mediaType: string
+ url: string
+}
+
+/** A document the user attached to a question. `path` is where it was picked
+ * from; the session does not copy it. */
+export type CoworkAttachedFile = {
+ name: string
+ path: string
+ fileType?: string
+ size?: number
+ /** The copy inside the session workspace, once imported for the agent. */
+ workspacePath?: string
+ /** Extracted text written beside the copy, for formats `read` cannot open. */
+ textPath?: string
+}
+
/** Mirrors the Rust `Usage` struct (events.rs). */
export type Usage = {
prompt_tokens?: number