Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cowork): network toggle, send retry, chat bash-only, cross-surface memory
Akarshan Biswasedd85fad4deb
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs b/src-tauri/plugins/tauri-plugin-agent-tools/build.rsindex 1b15e3e6a..d1acf5749 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs@@ -13,6 +13,7 @@ const COMMANDS: &[&str] = &["memory_list","memory_read","memory_write",+ "memory_catalog","memory_delete","tool_schemas","sandbox_status",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.tsindex 248e447cf..45328a64d 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@@ -1,5 +1,6 @@import { invoke, Channel } from '@tauri-apps/api/core'import {+ MemoryCatalogEntry,SkillMeta,ToolOutputChunk,ToolResult,@@ -8,6 +9,7 @@ import {} from './types'export {+ MemoryCatalogEntry,SkillMeta,ToolOutputChunk,ToolResult,@@ -194,6 +196,20 @@ export async function memoryWrite(})}+/**+ * Name + summary + mtime for every memory note, name-sorted. The recall+ * surface: prompt injections list notes from this without reading each body.+ */+export async function memoryCatalog(+ dataFolder: string,+ project?: string+): Promise<MemoryCatalogEntry[]> {+ return await invoke('plugin:agent-tools|memory_catalog', {+ dataFolder,+ project,+ })+}+/** Delete a memory note. Idempotent: a missing note resolves successfully. */export async function memoryDelete(dataFolder: string,diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.tsindex 7870887df..8269c2b34 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts+++ b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts@@ -25,6 +25,17 @@ export interface ToolSchema {}}+/**+ * One memory-catalog row: enough to advertise a note without its body.+ * `mtimeMs` is Unix millis (0 when the filesystem withholds it), so callers can+ * keep the newest notes when they cannot keep them all.+ */+export interface MemoryCatalogEntry {+ name: string+ summary: string+ mtimeMs: number+}+/** Which sandbox namespace an id belongs to. */export type WorkspaceScope = 'thread' | 'session'diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.tomlindex c3ce9d576..c834123cd 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml@@ -15,6 +15,7 @@ permissions = ["allow-memory-list","allow-memory-read","allow-memory-write",+ "allow-memory-catalog","allow-memory-delete","allow-tool-schemas","allow-sandbox-status",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.jsonindex 5a7831121..3712b1ffb 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@@ -318,6 +318,18 @@"const": "deny-execute-tool-streaming","markdownDescription": "Denies the execute_tool_streaming command without any pre-configured scope."},+ {+ "description": "Enables the memory_catalog command without any pre-configured scope.",+ "type": "string",+ "const": "allow-memory-catalog",+ "markdownDescription": "Enables the memory_catalog command without any pre-configured scope."+ },+ {+ "description": "Denies the memory_catalog command without any pre-configured scope.",+ "type": "string",+ "const": "deny-memory-catalog",+ "markdownDescription": "Denies the memory_catalog command without any pre-configured scope."+ },{"description": "Enables the memory_delete command without any pre-configured scope.","type": "string",@@ -523,10 +535,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-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`",+ "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-execute-tool`\n- `allow-execute-tool-streaming`","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-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`"+ "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-execute-tool`\n- `allow-execute-tool-streaming`"}]}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex d93065e59..55325ab37 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -257,6 +257,22 @@ pub async fn memory_write(.map_err(Into::into)}+/// Name + summary + mtime for every memory note, name-sorted. This is the+/// recall surface: both desktop chat's digest and Cowork's prompt catalog are+/// built from it, so neither re-reads the store per note just to list it.+#[tauri::command]+pub async fn memory_catalog(+ data_folder: String,+ project: Option<String>,+) -> Result<Vec<memory::CatalogEntry>, AgentToolsError> {+ let store = resolve_store(&data_folder, project.as_deref());+ // `catalog` is sync std::fs by design (the CLI calls it from sync context);+ // keep its directory walk off the async runtime's thread here.+ tokio::task::spawn_blocking(move || memory::catalog(&store))+ .await+ .map_err(|e| AgentToolsError::from(format!("memory catalog failed: {e}")))+}+/// Delete a memory note. Idempotent: a missing note is Ok.#[tauri::command]pub async fn memory_delete(@@ -1258,6 +1274,11 @@ mod tests {memory_read(df.clone(), None, "prefs".into()).await.unwrap(),"body");+ let entries = memory_catalog(df.clone(), None).await.unwrap();+ assert_eq!(entries.len(), 1);+ assert_eq!(entries[0].name, "prefs");+ assert_eq!(entries[0].summary, "body");+ assert!(entries[0].mtime_ms > 0);memory_delete(df.clone(), None, "prefs".into()).await.unwrap();diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rsindex 31f5ca9b6..6cb74c8f7 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs@@ -47,6 +47,7 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {commands::memory_list,commands::memory_read,commands::memory_write,+ commands::memory_catalog,commands::memory_delete,commands::tool_schemas,commands::sandbox_status,diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/memory.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/memory.rsindex c363b98af..e65a248d9 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/memory.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/memory.rs@@ -72,17 +72,39 @@ fn describe(content: &str) -> String {.unwrap_or_default()}+/// One catalog row: enough to advertise a note without shipping its body.+///+/// `mtime_ms` (Unix millis, 0 when the filesystem withholds it) lets callers+/// rank notes by recency - the desktop's chat digest and Cowork's catalog cap+/// both keep the newest notes when they cannot keep them all.+#[derive(Debug, Clone, PartialEq, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct CatalogEntry {+ pub name: String,+ pub summary: String,+ pub mtime_ms: u64,+}++fn mtime_ms(path: &Path) -> u64 {+ std::fs::metadata(path)+ .and_then(|m| m.modified())+ .ok()+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())+ .map(|d| d.as_millis() as u64)+ .unwrap_or(0)+}+/// Memory notes worth advertising in the system prompt: name + summary line, in-/// sorted order, skipping notes with neither a name nor a summary. This is the-/// progressive-disclosure catalog - the model calls `memory_read` to load a+/// name-sorted order, skipping notes with neither a name nor a summary. This is+/// the progressive-disclosure catalog - the model calls `memory_read` to load a/// note on demand. Sync (std::fs) so the sync `context::load_memory_catalog`/// can call it directly; the async `memory_*` tools share the same store.-pub fn catalog(store: &Path) -> Vec<(String, String)> {+pub fn catalog(store: &Path) -> Vec<CatalogEntry> {let dir = memory_dir(store);let Ok(rd) = std::fs::read_dir(&dir) else {return Vec::new();};- let mut notes: Vec<(String, String)> = rd+ let mut notes: Vec<CatalogEntry> = rd.filter_map(|e| e.ok()).filter_map(|e| {let path = e.path();@@ -93,18 +115,22 @@ pub fn catalog(store: &Path) -> Vec<(String, String)> {let body = std::fs::read_to_string(&path).ok();match (name, body) {(Some(name), Some(body)) => {- let description = describe(&body);- if name.is_empty() && description.is_empty() {+ let summary = describe(&body);+ if name.is_empty() && summary.is_empty() {None} else {- Some((name.to_string(), description))+ Some(CatalogEntry {+ name: name.to_string(),+ summary,+ mtime_ms: mtime_ms(&path),+ })}}_ => None,}}).collect();- notes.sort_by(|a, b| a.0.cmp(&b.0));+ notes.sort_by(|a, b| a.name.cmp(&b.name));notes}@@ -201,13 +227,21 @@ mod tests {std::fs::write(memory_dir(&root).join("notes.txt"), "ignored").unwrap();let notes = catalog(&root);+ let named: Vec<(&str, &str)> = notes+ .iter()+ .map(|n| (n.name.as_str(), n.summary.as_str()))+ .collect();assert_eq!(- notes,+ named,vec![- ("decisions".to_string(), "We use Yarn not npm.".to_string()),- ("prefs".to_string(), "Keep it minimal.".to_string()),+ ("decisions", "We use Yarn not npm."),+ ("prefs", "Keep it minimal."),]);+ assert!(+ notes.iter().all(|n| n.mtime_ms > 0),+ "freshly written notes carry a real mtime: {notes:?}"+ );let _ = std::fs::remove_dir_all(&root);}@@ -218,7 +252,10 @@ mod tests {std::fs::write(memory_dir(&root).join("empty.md"), " \n# Only headings\n").unwrap();// A curated note is worth advertising by name even if it has no prose.- assert_eq!(catalog(&root), vec![("empty".to_string(), String::new())]);+ let notes = catalog(&root);+ assert_eq!(notes.len(), 1);+ assert_eq!(notes[0].name, "empty");+ assert_eq!(notes[0].summary, "");let _ = std::fs::remove_dir_all(&root);}diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rsindex c5bc7958d..774b8d3d8 100644--- a/src-tauri/src/core/agent/context.rs+++ b/src-tauri/src/core/agent/context.rs@@ -234,7 +234,8 @@ pub(crate) fn load_memory_catalog(project_root: &Path) -> Option<String> {}let list = entries.iter()- .map(|(name, description)| {+ .map(|entry| {+ let (name, description) = (&entry.name, &entry.summary);if description.is_empty() {format!("- `{name}` - no summary")} else {diff --git a/web-app/src/constants/localStorage.ts b/web-app/src/constants/localStorage.tsindex 51d7c66d8..63235c94b 100644--- a/web-app/src/constants/localStorage.ts+++ b/web-app/src/constants/localStorage.ts@@ -11,7 +11,7 @@ export const localStorageKey = {settingLocalApiServer: 'setting-local-api-server',settingProxyConfig: 'setting-proxy-config',settingWebSearch: 'setting-web-search',- settingAgentTools: 'setting-agent-tools',+ settingCowork: 'setting-cowork',settingHardware: 'setting-hardware',settingVulkan: 'setting-vulkan',productAnalyticPrompt: 'productAnalyticPrompt',diff --git a/web-app/src/constants/routes.ts b/web-app/src/constants/routes.tsindex 61fcf97c8..97487db4b 100644--- a/web-app/src/constants/routes.ts+++ b/web-app/src/constants/routes.ts@@ -20,7 +20,7 @@ export const route = {mcp_servers: '/settings/mcp-servers',https_proxy: '/settings/https-proxy',web_search: '/settings/web-search',- agent_tools: '/settings/agent-tools',+ cowork: '/settings/cowork',hardware: '/settings/hardware',assistant: '/settings/assistant',claude_code: '/settings/claude-code',diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex a46c7f92e..39c3575d2 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -40,7 +40,6 @@ import { generateId } from 'ai'import { useMessageQueue } from '@/stores/message-queue-store'import { QueuedMessageChip } from '@/containers/QueuedMessageBubble'import { SamplerPopover } from '@/containers/SamplerPopover'-import { BotIcon } from 'lucide-react'import { useTranslation } from '@/i18n/react-i18next-compat'import { useGeneralSetting } from '@/hooks/useGeneralSetting'import { useModelProvider } from '@/hooks/useModelProvider'@@ -229,7 +228,6 @@ const ChatInput = memo(function ChatInput({const effectiveAgentMode = isAgentMode && !projectId// Gate for the controls that shape which tools the model is offered.const showToolControls = ownsToolSet && !effectiveAgentMode- const toggleAgentMode = useAgentMode((state) => state.toggleAgentMode)const webSearchEnabled = useWebSearchConfig((s) => s.webSearchEnabled)const setWebSearchEnabled = useWebSearchConfig((s) => s.setWebSearchEnabled)@@ -379,10 +377,6 @@ const ChatInput = memo(function ChatInput({[workingDir])- const handleAgentToggle = useCallback(() => {- toggleAgentMode(agentModeKey)- }, [agentModeKey, toggleAgentMode])-// Get current thread messages for token countingconst threadMessages = useMessages(useShallow((state) =>@@ -2439,37 +2433,6 @@ const ChatInput = memo(function ChatInput({</Tooltip>))}- {/* Agent mode toggle hidden — kept as dead code for future use */}- {false && !projectId && isAgentMode && (- <Tooltip>- <TooltipTrigger asChild>- <Button- variant={isAgentMode ? "default" : "ghost"}- size="icon-xs"- onClick={currentThreadId ? handleAgentToggle : undefined}- className={cn(- isAgentMode && 'text-primary bg-primary/10 hover:bg-primary/10 items-center',- !currentThreadId && 'cursor-default pointer-events-none'- )}- >- <BotIcon- className={cn(- 'text-muted-foreground -mt-0.5',- isAgentMode && 'text-primary'- )}- />- </Button>- </TooltipTrigger>- <TooltipContent>- <p>- {isAgentMode- ? 'Agent mode active'- : 'Enable agent mode'}- </p>- </TooltipContent>- </Tooltip>- )}-{!effectiveAgentMode && selectedModel?.capabilities?.includes('tools') && (<Tooltip><TooltipTrigger asChild>diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsxindex 1f0084102..4a998b3c6 100644--- a/web-app/src/containers/MessageItem.tsx+++ b/web-app/src/containers/MessageItem.tsx@@ -23,6 +23,7 @@ import {type PartEntry,} from './message/types'import { CopyButton } from './CopyButton'+import { RememberButton } from './RememberButton'import { useTranslation } from '@/i18n/react-i18next-compat'import { formatDate } from '@/utils/formatDate'import { useModelProvider } from '@/hooks/useModelProvider'@@ -714,6 +715,7 @@ export const MessageItem = memo(>{versionNav}<CopyButton text={getFullTextContent()} />+ <RememberButton text={getFullTextContent()} />{onEdit && !isStreaming && (<EditMessageDialogdiff --git a/web-app/src/containers/RememberButton.tsx b/web-app/src/containers/RememberButton.tsxnew file mode 100644index 000000000..d04e78c48--- /dev/null+++ b/web-app/src/containers/RememberButton.tsx@@ -0,0 +1,53 @@+import { useState } from 'react'+import { toast } from 'sonner'+import { Button } from '@/components/ui/button'+import { IconBookmark, IconBookmarkFilled } from '@tabler/icons-react'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { useThreads } from '@/hooks/useThreads'+import { rememberNote } from '@/lib/agentWorkspace'++/**+ * Chat's only write path into the shared agent memory: user-driven, one click+ * per assistant message. The note is named after the thread title and its full+ * text lands in the store both surfaces recall from. No silent model writes on+ * a surface that advertises no memory tools.+ */+export const RememberButton = ({ text }: { text: string }) => {+ const { t } = useTranslation()+ const [saving, setSaving] = useState(false)+ const [saved, setSaved] = useState(false)++ // The store lives behind the Tauri plugin; a web build has nowhere to write.+ if (!IS_TAURI || !text.trim()) return null++ const handleRemember = async () => {+ if (saving) return+ setSaving(true)+ try {+ const title = useThreads.getState().getCurrentThread()?.title ?? ''+ const name = await rememberNote(title, text)+ setSaved(true)+ setTimeout(() => setSaved(false), 2000)+ toast.success(t('chat:actions.rememberSaved', { name }))+ } catch {+ toast.error(t('chat:actions.rememberFailed'))+ } finally {+ setSaving(false)+ }+ }++ return (+ <Button+ variant="ghost"+ size="icon-xs"+ onClick={handleRemember}+ title={t('chat:actions.remember')}+ >+ {saved ? (+ <IconBookmarkFilled size={16} className="text-primary" />+ ) : (+ <IconBookmark size={16} />+ )}+ </Button>+ )+}diff --git a/web-app/src/containers/SettingsMenu.tsx b/web-app/src/containers/SettingsMenu.tsxindex f2c1d0d0c..16ab61338 100644--- a/web-app/src/containers/SettingsMenu.tsx+++ b/web-app/src/containers/SettingsMenu.tsx@@ -200,8 +200,8 @@ const SettingsMenu = () => {icon: IconWorldSearch,},{- title: 'common:agent_tools',- route: route.settings.agent_tools,+ title: 'common:cowork',+ route: route.settings.cowork,icon: IconFolderCode,},{diff --git a/web-app/src/hooks/__tests__/useAgentToolsConfig.test.ts b/web-app/src/hooks/__tests__/useAgentToolsConfig.test.tsdeleted file mode 100644index 9c68743c0..000000000--- a/web-app/src/hooks/__tests__/useAgentToolsConfig.test.ts+++ /dev/null@@ -1,48 +0,0 @@-import { describe, it, expect, vi, beforeEach } from 'vitest'--// The store persists via backendStorage; stub the persist layer so the import-// is inert and no disk I/O happens in tests.-vi.mock('@/constants/localStorage', () => ({- localStorageKey: { settingAgentTools: 'setting-agent-tools' },-}))-vi.mock('zustand/middleware', () => ({- persist: (fn: any) => fn,- createJSONStorage: () => ({- getItem: vi.fn(),- setItem: vi.fn(),- removeItem: vi.fn(),- }),-}))--import { useAgentToolsConfig } from '../useAgentToolsConfig'--describe('useAgentToolsConfig', () => {- beforeEach(() => {- useAgentToolsConfig.setState({- agentToolsEnabled: false,- bashNetworkEnabled: false,- })- })-- it('defaults both toggles off', () => {- expect(useAgentToolsConfig.getState().agentToolsEnabled).toBe(false)- expect(useAgentToolsConfig.getState().bashNetworkEnabled).toBe(false)- })-- it('toggles the agent tools switch on and off', () => {- useAgentToolsConfig.getState().setAgentToolsEnabled(true)- expect(useAgentToolsConfig.getState().agentToolsEnabled).toBe(true)-- useAgentToolsConfig.getState().setAgentToolsEnabled(false)- expect(useAgentToolsConfig.getState().agentToolsEnabled).toBe(false)- })-- it('keeps bash network and agent tools switches independent', () => {- useAgentToolsConfig.getState().setAgentToolsEnabled(true)- expect(useAgentToolsConfig.getState().bashNetworkEnabled).toBe(false)-- useAgentToolsConfig.getState().setBashNetworkEnabled(true)- expect(useAgentToolsConfig.getState().bashNetworkEnabled).toBe(true)- expect(useAgentToolsConfig.getState().agentToolsEnabled).toBe(true)- })-})diff --git a/web-app/src/hooks/__tests__/useCoworkConfig.test.ts b/web-app/src/hooks/__tests__/useCoworkConfig.test.tsnew file mode 100644index 000000000..4ac40ced3--- /dev/null+++ b/web-app/src/hooks/__tests__/useCoworkConfig.test.ts@@ -0,0 +1,62 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++// Real zustand persist, fake disk: an in-memory record standing in for the+// Rust settings store behind backendStorage, so the tests verify the flush+// path (key name and payload) up to the storage boundary.+const disk = vi.hoisted(() => new Map<string, string>())+vi.mock('@/lib/backendStorage', () => ({+ backendStorage: {+ getItem: async (name: string) => disk.get(name) ?? null,+ setItem: async (name: string, value: string) => {+ disk.set(name, value)+ },+ removeItem: async (name: string) => {+ disk.delete(name)+ },+ },+}))++import { useCoworkConfig } from '../useCoworkConfig'++describe('useCoworkConfig', () => {+ beforeEach(() => {+ disk.clear()+ useCoworkConfig.setState({ networkEnabled: true })+ })++ // On by default: an agent surface without package installs or curl is+ // crippled for the work it exists to do.+ it('defaults the sandbox network on', () => {+ expect(useCoworkConfig.getState().networkEnabled).toBe(true)+ })++ it('toggles the network switch off and back on', () => {+ useCoworkConfig.getState().setNetworkEnabled(false)+ expect(useCoworkConfig.getState().networkEnabled).toBe(false)+ useCoworkConfig.getState().setNetworkEnabled(true)+ expect(useCoworkConfig.getState().networkEnabled).toBe(true)+ })++ // Pins the on-disk contract: every toggle lands under `setting-cowork` in+ // the backend settings store.+ it('flushes a toggle to the backend store', async () => {+ useCoworkConfig.getState().setNetworkEnabled(false)+ // persist's storage is async; give the write a turn to land.+ await vi.waitFor(() => {+ expect(JSON.parse(disk.get('setting-cowork') ?? '{}').state).toEqual({+ networkEnabled: false,+ })+ })+ })++ // A record already on disk wins over the in-memory default on hydration —+ // which is how a toggle survives an app restart.+ it('hydrates from an existing on-disk record', async () => {+ disk.set(+ 'setting-cowork',+ JSON.stringify({ state: { networkEnabled: false }, version: 0 })+ )+ await useCoworkConfig.persist.rehydrate()+ expect(useCoworkConfig.getState().networkEnabled).toBe(false)+ })+})diff --git a/web-app/src/hooks/useAgentToolsConfig.ts b/web-app/src/hooks/useAgentToolsConfig.tsdeleted file mode 100644index 070fbbeba..000000000--- a/web-app/src/hooks/useAgentToolsConfig.ts+++ /dev/null@@ -1,36 +0,0 @@-import { create } from 'zustand'-import { persist, createJSONStorage } from 'zustand/middleware'-import { localStorageKey } from '@/constants/localStorage'-import { backendStorage } from '@/lib/backendStorage'--type AgentToolsConfigState = {- agentToolsEnabled: boolean- setAgentToolsEnabled: (value: boolean) => void- /** Open the sandboxed shell's network namespace. */- bashNetworkEnabled: boolean- setBashNetworkEnabled: (value: boolean) => void-}--/**- * Off by default: the toolset gives the model filesystem reach (inside the- * isolated agent workspace) and a persistent memory, so it is opt-in.- *- * `bashNetworkEnabled` is separately off, because it is the one setting that- * lets a command reach off the machine. With it off, the sandbox confines a- * command to the workspace *and* keeps it from sending anything anywhere.- */-export const useAgentToolsConfig = create<AgentToolsConfigState>()(- persist(- (set) => ({- agentToolsEnabled: false,- setAgentToolsEnabled: (agentToolsEnabled) => set({ agentToolsEnabled }),- bashNetworkEnabled: false,- setBashNetworkEnabled: (bashNetworkEnabled) => set({ bashNetworkEnabled }),- }),- {- name: localStorageKey.settingAgentTools,- storage: createJSONStorage(() => backendStorage),- skipHydration: true,- }- )-)diff --git a/web-app/src/hooks/useCoworkConfig.ts b/web-app/src/hooks/useCoworkConfig.tsnew file mode 100644index 000000000..e1de65081--- /dev/null+++ b/web-app/src/hooks/useCoworkConfig.ts@@ -0,0 +1,30 @@+import { create } from 'zustand'+import { persist, createJSONStorage } from 'zustand/middleware'+import { localStorageKey } from '@/constants/localStorage'+import { backendStorage } from '@/lib/backendStorage'++type CoworkConfigState = {+ /**+ * Open the sandboxed shell's network namespace for Cowork runs. On by+ * default: an agent surface without package installs or curl is crippled+ * for the work it exists to do, and the OS sandbox still confines the+ * filesystem either way. Chat's shell is unaffected — its network is closed+ * unconditionally.+ */+ networkEnabled: boolean+ setNetworkEnabled: (value: boolean) => void+}++export const useCoworkConfig = create<CoworkConfigState>()(+ persist(+ (set) => ({+ networkEnabled: true,+ setNetworkEnabled: (networkEnabled) => set({ networkEnabled }),+ }),+ {+ name: localStorageKey.settingCowork,+ storage: createJSONStorage(() => backendStorage),+ skipHydration: true,+ }+ )+)diff --git a/web-app/src/lib/__tests__/agentTools.test.ts b/web-app/src/lib/__tests__/agentTools.test.tsindex d8f7996c3..512c620d8 100644--- a/web-app/src/lib/__tests__/agentTools.test.ts+++ b/web-app/src/lib/__tests__/agentTools.test.ts@@ -5,6 +5,8 @@ const executeTool = vi.fn()const threadWorkspaceDelete = vi.fn()const threadWorkspaceSweep = vi.fn()const sandboxStatus = vi.fn()+const memoryCatalog = vi.fn()+const memoryRead = vi.fn()const getJanDataFolder = vi.fn()vi.mock('@janhq/tauri-plugin-agent-tools-api', () => ({@@ -13,6 +15,8 @@ vi.mock('@janhq/tauri-plugin-agent-tools-api', () => ({threadWorkspaceDelete: (...args: unknown[]) => threadWorkspaceDelete(...args),threadWorkspaceSweep: (...args: unknown[]) => threadWorkspaceSweep(...args),sandboxStatus: () => sandboxStatus(),+ memoryCatalog: (...args: unknown[]) => memoryCatalog(...args),+ memoryRead: (...args: unknown[]) => memoryRead(...args),}))vi.mock('@/hooks/useServiceHub', () => ({@@ -34,9 +38,19 @@ describe('agentTools', () => {sandboxStatus.mockReset().mockResolvedValue({ backend: 'bubblewrap', enforces: true })+ memoryCatalog.mockReset().mockResolvedValue([])+ memoryRead.mockReset().mockResolvedValue('')getJanDataFolder.mockReset().mockResolvedValue('/data')})+ // The chat surface offers the sandboxed shell alone; everything else is+ // Cowork's. A chat set that grew a write tool would hand the main interface+ // an agent toolset it no longer advertises a workspace for.+ it('restricts the chat subset to bash', async () => {+ const { CHAT_AGENT_TOOL_NAMES } = await import('../agentTools')+ expect([...CHAT_AGENT_TOOL_NAMES]).toEqual(['bash'])+ })+it('advertises the workspace tools including writes and bash', async () => {const { AGENT_TOOL_NAMES } = await import('../agentTools')for (const name of ['read', 'ls', 'find', 'grep', 'bash']) {@@ -120,11 +134,10 @@ describe('agentTools', () => {expect(sandboxEnforces()).toBe(false)})- it('passes the network setting through to the plugin', async () => {+ // Chat's shell runs with the network closed; no global setting can open it.+ it('keeps the sandbox network closed unless the caller opens it', async () => {executeTool.mockResolvedValue({ content: '', diff: null, isError: false })- const { useAgentToolsConfig } = await import('@/hooks/useAgentToolsConfig')const { executeAgentTool } = await import('../agentTools')-await executeAgentTool('bash', { command: 'ls' }, 'thread-1')expect(executeTool).toHaveBeenLastCalledWith('/data',@@ -137,9 +150,20 @@ describe('agentTools', () => {undefined,'thread')+ })- useAgentToolsConfig.getState().setBashNetworkEnabled(true)- await executeAgentTool('bash', { command: 'ls' }, 'thread-1')+ // Cowork opens the sandbox network per call.+ it('opens the network when the caller asks', async () => {+ executeTool.mockResolvedValue({ content: '', diff: null, isError: false })+ const { executeAgentTool } = await import('../agentTools')+ await executeAgentTool(+ 'bash',+ { command: 'ls' },+ 'thread-1',+ undefined,+ 'thread',+ true+ )expect(executeTool).toHaveBeenLastCalledWith('/data','thread-1',@@ -151,7 +175,6 @@ describe('agentTools', () => {undefined,'thread')- useAgentToolsConfig.getState().setBashNetworkEnabled(false)})it('caches the schemas so every turn does not re-cross IPC', async () => {@@ -266,6 +289,91 @@ describe('agentTools', () => {)})+ // ---- shared memory recall ----------------------------------------------++ const note = (name: string, mtimeMs: number, summary = `${name} summary`) => ({+ name,+ summary,+ mtimeMs,+ })++ it('caps the prompt catalog at the newest notes, then name-sorts it', async () => {+ const { getMemoryCatalog, MEMORY_CATALOG_MAX_NOTES } = await import(+ '../agentTools'+ )+ const notes = Array.from({ length: MEMORY_CATALOG_MAX_NOTES + 5 }, (_, i) =>+ note(`n${String(i).padStart(3, '0')}`, i)+ )+ memoryCatalog.mockResolvedValue(notes)+ const catalog = await getMemoryCatalog()+ expect(catalog).toHaveLength(MEMORY_CATALOG_MAX_NOTES)+ // The 5 oldest (lowest mtime) fell off, and the survivors are name-sorted+ // so the prompt block is stable when nothing changed.+ const names = catalog.map((n) => n.name)+ expect(names).toEqual([...names].sort())+ expect(names).not.toContain('n000')+ expect(names).not.toContain('n004')+ expect(names).toContain('n005')+ })++ it('builds a whole-note digest, newest first, under the byte budget', async () => {+ const { refreshMemoryDigest, memoryDigestNow, MEMORY_DIGEST_BUDGET } =+ await import('../agentTools')+ expect(memoryDigestNow()).toBe('')+ memoryCatalog.mockResolvedValue([+ note('old', 1),+ note('huge', 3),+ note('new', 2),+ ])+ const bodies: Record<string, string> = {+ old: 'user prefers tabs',+ huge: 'x'.repeat(MEMORY_DIGEST_BUDGET + 1),+ new: 'project targets Node 22',+ }+ memoryRead.mockImplementation(async (_df: string, name: string) => bodies[name])+ const digest = await refreshMemoryDigest()+ // Whole notes only: the oversized note is absent, not truncated.+ expect(digest).not.toContain('xxx')+ expect(digest).toContain('## new\nproject targets Node 22')+ expect(digest).toContain('## old\nuser prefers tabs')+ // Newest first.+ expect(digest.indexOf('## new')).toBeLessThan(digest.indexOf('## old'))+ expect(digest.length).toBeLessThanOrEqual(MEMORY_DIGEST_BUDGET)+ expect(memoryDigestNow()).toBe(digest)+ })++ it('serves the snapshot from cache until a write invalidates it', async () => {+ const { getMemoryCatalog, invalidateMemory } = await import('../agentTools')+ memoryCatalog.mockResolvedValue([note('a', 1)])+ await getMemoryCatalog()+ await getMemoryCatalog()+ expect(memoryCatalog).toHaveBeenCalledTimes(1)+ invalidateMemory()+ await getMemoryCatalog()+ expect(memoryCatalog).toHaveBeenCalledTimes(2)+ })++ // Cowork's memory_write goes through executeAgentTool, so a note the model+ // records mid-session must reach the next run/send without a restart.+ it('invalidates the snapshot when the memory_write tool succeeds', async () => {+ executeTool.mockResolvedValue({ content: 'ok', diff: null, isError: false })+ const { executeAgentTool, getMemoryCatalog } = await import('../agentTools')+ memoryCatalog.mockResolvedValue([])+ await getMemoryCatalog()+ await executeAgentTool('memory_write', { name: 'a', content: 'b' }, 't1')+ await getMemoryCatalog()+ expect(memoryCatalog).toHaveBeenCalledTimes(2)+ })++ it('degrades to empty recall when the store is unreachable', async () => {+ memoryCatalog.mockRejectedValue(new Error('no backend'))+ const { getMemoryCatalog, refreshMemoryDigest } = await import(+ '../agentTools'+ )+ await expect(getMemoryCatalog()).resolves.toEqual([])+ await expect(refreshMemoryDigest()).resolves.toBe('')+ })+it('deletes one thread sandbox on cleanup', async () => {const { cleanupThreadWorkspace } = await import('../agentTools')await cleanupThreadWorkspace('thread-1')diff --git a/web-app/src/lib/__tests__/agentWorkspace.test.ts b/web-app/src/lib/__tests__/agentWorkspace.test.tsindex a387a4e6f..a83f6e612 100644--- a/web-app/src/lib/__tests__/agentWorkspace.test.ts+++ b/web-app/src/lib/__tests__/agentWorkspace.test.ts@@ -10,6 +10,15 @@ const api = {memoryRead: vi.fn(),memoryWrite: vi.fn(),memoryDelete: vi.fn(),+ // agentWorkspace pulls in agentTools (for invalidateMemory), whose own+ // imports from this module must exist on the mock even though these tests+ // never call them.+ memoryCatalog: vi.fn(),+ toolSchemas: vi.fn(),+ executeTool: vi.fn(),+ sandboxStatus: vi.fn(),+ threadWorkspaceDelete: vi.fn(),+ threadWorkspaceSweep: vi.fn(),}const getJanDataFolder = vi.fn()const revealItemInDir = vi.fn()@@ -68,6 +77,41 @@ describe('agentWorkspace', () => {expect(api.memoryDelete).toHaveBeenCalledWith('/data', 'prefs')})+ // ---- the chat Remember action --------------------------------------------++ it('slugs a thread title into a filesystem-safe note name', async () => {+ const { slugifyMemoryName } = await import('../agentWorkspace')+ expect(slugifyMemoryName('How to set up CUDA 12?')).toBe(+ 'how-to-set-up-cuda-12'+ )+ expect(slugifyMemoryName(' --- ')).toBe('memory')+ expect(slugifyMemoryName('')).toBe('memory')+ expect(slugifyMemoryName('a'.repeat(100))).toHaveLength(60)+ })++ it('remembers under the thread title, deduplicating taken names', async () => {+ api.memoryList.mockResolvedValue(['chat-notes', 'chat-notes-2'])+ const ws = await import('../agentWorkspace')+ await expect(ws.rememberNote('Chat Notes', 'the fact')).resolves.toBe(+ 'chat-notes-3'+ )+ // Suffixing, never overwriting: memory_write replaces by name, and the+ // existing notes are not this action's to replace.+ expect(api.memoryWrite).toHaveBeenCalledWith(+ '/data',+ 'chat-notes-3',+ 'the fact'+ )+ })++ it('uses the plain slug when the name is free', async () => {+ api.memoryList.mockResolvedValue([])+ const ws = await import('../agentWorkspace')+ await expect(ws.rememberNote('Fresh Topic', 'body')).resolves.toBe(+ 'fresh-topic'+ )+ })+/// Unlike a tool call, a failed edit has a user waiting on it, so these throw/// instead of resolving to an error value the page would have to sniff for.it('propagates failures to the caller', async () => {diff --git a/web-app/src/lib/__tests__/coworkDispatch.test.ts b/web-app/src/lib/__tests__/coworkDispatch.test.tsindex ffeb294de..b94a117c2 100644--- a/web-app/src/lib/__tests__/coworkDispatch.test.ts+++ b/web-app/src/lib/__tests__/coworkDispatch.test.ts@@ -9,6 +9,11 @@ vi.mock('@/lib/webSearchTool', () => ({executeWebTool,}))+const coworkConfig = vi.hoisted(() => ({ networkEnabled: true }))+vi.mock('@/hooks/useCoworkConfig', () => ({+ useCoworkConfig: { getState: () => coworkConfig },+}))+import { dispatchCoworkTool } from '../coworkDispatch'import type { PendingToolCall } from '../coworkRunner'@@ -46,8 +51,37 @@ describe('dispatchCoworkTool', () => {{ path: 'a' },'s1',null,- 'session'+ 'session',+ true+ )+ })++ // Cowork's shell network follows the Cowork setting (on by default), read+ // per call so a Settings toggle applies to the next command.+ it('passes the cowork network setting through per call', async () => {+ await dispatchCoworkTool(call('bash', { command: 'curl x' }), ctx())+ expect(executeAgentTool).toHaveBeenCalledWith(+ 'bash',+ { command: 'curl x' },+ 's1',+ null,+ 'session',+ true)+ coworkConfig.networkEnabled = false+ try {+ await dispatchCoworkTool(call('bash', { command: 'curl x' }), ctx())+ expect(executeAgentTool).toHaveBeenLastCalledWith(+ 'bash',+ { command: 'curl x' },+ 's1',+ null,+ 'session',+ false+ )+ } finally {+ coworkConfig.networkEnabled = true+ }})it('routes the client-only tools to their handlers', async () => {@@ -81,7 +115,8 @@ describe('dispatchCoworkTool', () => {{},'s1','/repo',- 'session'+ 'session',+ true)})diff --git a/web-app/src/lib/__tests__/coworkPrompt.test.ts b/web-app/src/lib/__tests__/coworkPrompt.test.tsindex 135df99f3..9dccaf932 100644--- a/web-app/src/lib/__tests__/coworkPrompt.test.ts+++ b/web-app/src/lib/__tests__/coworkPrompt.test.ts@@ -12,6 +12,7 @@ const opts = (over = {}) => ({webSearch: false,bashAvailable: true,subagentNames: [],+ memoryCatalog: [],...over,})@@ -49,6 +50,27 @@ describe('buildCoworkSystemPrompt', () => {expect(p).toContain('Exit plan mode')})+ // Progressive disclosure: one line per note, `memory_read` for the rest. An+ // empty store adds nothing, so the prompt prefix is unchanged for users who+ // never recorded a memory.+ it('lists memory notes with summaries only when the store has any', () => {+ const p = buildCoworkSystemPrompt(+ opts({+ memoryCatalog: [+ { name: 'decisions', summary: 'We use Yarn not npm.' },+ { name: 'empty-note', summary: '' },+ ],+ })+ )+ expect(p).toContain('# Available Memories')+ expect(p).toContain('- `decisions` - We use Yarn not npm.')+ expect(p).toContain('- `empty-note` - no summary')+ expect(p).toContain('memory_read')+ expect(buildCoworkSystemPrompt(opts())).not.toContain(+ '# Available Memories'+ )+ })+it('describes subagents only when some are available and not planning', () => {expect(buildCoworkSystemPrompt(opts({ subagentNames: ['researcher'] }))@@ -86,10 +108,12 @@ describe('buildSubagentSystemPrompt', () => {expect(out).toContain('cannot dispatch')})- it('never leaks plan mode or a subagent roster into a child', () => {+ it('never leaks plan mode, a subagent roster, or memory into a child', () => {const out = buildSubagentSystemPrompt('p', opts)expect(out).not.toContain('PLAN MODE')expect(out).not.toContain('# Subagents')+ // A child runs one stated errand; recall is the dispatcher's job.+ expect(out).not.toContain('# Available Memories')})// A child whose allowlist dropped the web tools must not be told it has them.diff --git a/web-app/src/lib/__tests__/coworkRunner.test.ts b/web-app/src/lib/__tests__/coworkRunner.test.tsindex 1d32f3f2c..b149334d6 100644--- a/web-app/src/lib/__tests__/coworkRunner.test.ts+++ b/web-app/src/lib/__tests__/coworkRunner.test.ts@@ -8,6 +8,7 @@ import {abortRun,answerAsk,isAbortLike,+ isRetryableSendError,isRunning,__testing,type PendingToolCall,@@ -317,6 +318,136 @@ describe('isAbortLike', () => {})})+// The failure a long turn invites: while tools run locally no bytes flow, the+// peer reclaims the idle keep-alive connection, and the next step's request is+// written into a socket that is already gone. Mirrors the Rust agent's+// send_with_one_retry — retrying is safe precisely because nothing was+// received.+describe('dropped-connection retry', () => {+ it('retries a dropped send once and the step succeeds', async () => {+ let first = true+ const d = deps([textStep('done')])+ const send = d.sendStep.getMockImplementation()!+ d.sendStep.mockImplementation(async (...args) => {+ if (first) {+ first = false+ throw new Error('connection reset by peer (os error 104)')+ }+ return send(...(args as []))+ })+ const out = await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: new AbortController().signal,+ })+ expect(out.stoppedBy).toBe('done')+ expect(d.sendStep).toHaveBeenCalledTimes(2)+ })++ it('retries exactly once, then reports the failure', async () => {+ const d = {+ ...deps([[]]),+ sendStep: vi.fn(async () => {+ throw new Error('connection reset by peer')+ }),+ }+ const out = await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: new AbortController().signal,+ })+ expect(out.stoppedBy).toBe('error')+ expect(out.errorText).toContain('connection reset')+ expect(d.sendStep).toHaveBeenCalledTimes(2)+ })++ // An error chunk before any delta is the same dropped connection, surfaced+ // through the stream instead of a rejection — streamText reports transport+ // failures this way.+ it('retries an error chunk that arrived before anything streamed', async () => {+ const d = deps([+ [+ {+ type: 'error',+ errorText: 'connection closed before message completed',+ } as UIMessageChunk,+ ],+ textStep('done'),+ ])+ const out = await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: new AbortController().signal,+ })+ expect(out.stoppedBy).toBe('done')+ expect(d.sendStep).toHaveBeenCalledTimes(2)+ })++ // Tokens already reached the UI; replaying the request would duplicate them.+ it('never retries once something has streamed', async () => {+ const d = deps([+ [+ ...textStep('partial'),+ {+ type: 'error',+ errorText: 'connection reset by peer',+ } as UIMessageChunk,+ ],+ ])+ const out = await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: new AbortController().signal,+ })+ expect(out.stoppedBy).toBe('error')+ expect(d.sendStep).toHaveBeenCalledTimes(1)+ })++ it('does not retry a timeout: retrying one doubles the wait', async () => {+ const d = {+ ...deps([[]]),+ sendStep: vi.fn(async () => {+ throw new Error('error sending request: operation timed out')+ }),+ }+ const out = await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: new AbortController().signal,+ })+ expect(out.stoppedBy).toBe('error')+ expect(d.sendStep).toHaveBeenCalledTimes(1)+ })+})++describe('isRetryableSendError', () => {+ it('recognises the stale keep-alive family and failed connects', () => {+ for (const msg of [+ 'connection closed before message completed',+ 'Connection reset by peer (os error 104)',+ 'broken pipe',+ 'connection aborted',+ 'unexpected EOF during handshake',+ 'connection refused',+ 'error sending request for url (http://x/v1/chat/completions)',+ 'TypeError: Failed to fetch',+ ]) {+ expect(isRetryableSendError(msg), msg).toBe(true)+ }+ })++ it('refuses timeouts, upstream rejections and plain errors', () => {+ for (const msg of [+ 'error sending request: operation timed out',+ 'Request timeout',+ '400 Bad Request: model not found',+ 'boom',+ ]) {+ expect(isRetryableSendError(msg), msg).toBe(false)+ }+ })+})+describe('runTurn failure paths', () => {const throwingDeps = (error: unknown) => ({...deps([[]]),diff --git a/web-app/src/lib/__tests__/coworkTransport.test.ts b/web-app/src/lib/__tests__/coworkTransport.test.tsindex 4e1ffa813..4d52831cb 100644--- a/web-app/src/lib/__tests__/coworkTransport.test.ts+++ b/web-app/src/lib/__tests__/coworkTransport.test.ts@@ -1,10 +1,13 @@import { describe, it, expect, vi, beforeEach } from 'vitest'-const { sandboxEnforces, buildCoworkTools } = vi.hoisted(() => ({- sandboxEnforces: vi.fn(() => true),- buildCoworkTools: vi.fn(),-}))-vi.mock('@/lib/agentTools', () => ({ sandboxEnforces }))+const { sandboxEnforces, buildCoworkTools, getMemoryCatalog } = vi.hoisted(+ () => ({+ sandboxEnforces: vi.fn(() => true),+ buildCoworkTools: vi.fn(),+ getMemoryCatalog: vi.fn(async () => [] as unknown[]),+ })+)+vi.mock('@/lib/agentTools', () => ({ sandboxEnforces, getMemoryCatalog }))vi.mock('@/lib/coworkTools', async (orig) => ({...(await orig<typeof import('../coworkTools')>()),buildCoworkTools,@@ -78,6 +81,24 @@ describe('CoworkChatTransport', () => {)})+ // Memory moves independently of the tool config: a note written during one+ // run must reach the next run's prompt even when the tool set is reused, and+ // must not move mid-run, which would discard the prompt prefix.+ it('re-snapshots the memory catalog at run boundaries, not mid-run', async () => {+ getMemoryCatalog.mockReset()+ getMemoryCatalog.mockResolvedValue([])+ const t = new CoworkChatTransport('s1', config())+ await t.refreshTools()+ await t.refreshTools()+ expect(getMemoryCatalog).toHaveBeenCalledTimes(1)++ t.unfreezeTools()+ await t.refreshTools()+ expect(getMemoryCatalog).toHaveBeenCalledTimes(2)+ // Same config, so the tool set was reused -- the catalog still refreshed.+ expect(buildCoworkTools).toHaveBeenCalledTimes(1)+ })+it('rebuilds when the sandbox appears, since bash joins the set', async () => {sandboxEnforces.mockReturnValue(false)const t = new CoworkChatTransport('s1', config())diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.tsindex 7b001e55a..c81ec8127 100644--- a/web-app/src/lib/agentTools.ts+++ b/web-app/src/lib/agentTools.ts@@ -4,12 +4,14 @@ import {sandboxStatus,threadWorkspaceDelete,threadWorkspaceSweep,+ memoryCatalog,+ memoryRead,+ type MemoryCatalogEntry,type SandboxStatus,type ToolSchema,type WorkspaceScope,} from '@janhq/tauri-plugin-agent-tools-api'import { getServiceHub } from '@/hooks/useServiceHub'-import { useAgentToolsConfig } from '@/hooks/useAgentToolsConfig'/*** The built-in agent tools the desktop can dispatch.@@ -41,6 +43,13 @@ export const AGENT_TOOL_NAMES = new Set(['screenshot',])+/**+ * The subset the main chat surface advertises and dispatches: the sandboxed+ * shell alone, with no network. The full toolset above is Cowork's — chat is a+ * conversation that occasionally runs a command, not an agent surface.+ */+export const CHAT_AGENT_TOOL_NAMES = new Set(['bash'])+/*** Tools that only run under an enforcing OS sandbox. They stay in* `AGENT_TOOL_NAMES` -- the desktop still owns dispatching them -- but are held@@ -107,6 +116,94 @@ export async function getAgentToolSchemas(): Promise<ToolSchema[]> {return schemaCache}+export type { MemoryCatalogEntry }++/**+ * Injection caps for the shared memory store. The *store* is unbounded; what+ * every conversation pays for is not: Cowork's catalog lists at most the 50+ * most recently modified notes, and chat's digest carries at most 2 KiB of+ * whole notes. Beyond that, the settings page is the pruning tool.+ */+export const MEMORY_CATALOG_MAX_NOTES = 50+export const MEMORY_DIGEST_BUDGET = 2048++type MemorySnapshot = { catalog: MemoryCatalogEntry[]; digest: string }++let memoryCache: Promise<MemorySnapshot> | null = null+let digestNow = ''++/**+ * Drop the cached snapshot so the next run/send re-reads the store. Called from+ * every in-app write path (the `memory_write` tool, the settings editors, the+ * chat Remember action); an edit made outside the app is picked up on restart.+ */+export function invalidateMemory(): void {+ memoryCache = null+}++async function loadMemorySnapshot(): Promise<MemorySnapshot> {+ const dataFolder = await getServiceHub().app().getJanDataFolder()+ if (!dataFolder) return { catalog: [], digest: '' }+ const newestFirst = (await memoryCatalog(dataFolder)).sort(+ (a, b) => b.mtimeMs - a.mtimeMs+ )+ const catalog = newestFirst.slice(0, MEMORY_CATALOG_MAX_NOTES)++ // The digest is self-contained: whole notes only, newest first, under a+ // strict budget. A note that does not fit is simply absent -- chat has no+ // memory_read to dereference a truncated one with.+ let remaining = MEMORY_DIGEST_BUDGET+ const parts: string[] = []+ for (const entry of newestFirst) {+ if (remaining <= 0) break+ const body = (await memoryRead(dataFolder, entry.name).catch(() => ''))+ .trim()+ if (!body) continue+ const block = `## ${entry.name}\n${body}`+ // The joiner counts too, or the assembled digest could exceed the budget.+ const cost = block.length + (parts.length > 0 ? 2 : 0)+ if (cost > remaining) continue+ parts.push(block)+ remaining -= cost+ }+ return { catalog, digest: parts.join('\n\n') }+}++function getMemorySnapshot(): Promise<MemorySnapshot> {+ memoryCache ??= loadMemorySnapshot()+ .catch((e) => {+ console.warn('[agentTools] Failed to load memory:', messageOf(e))+ return { catalog: [], digest: '' }+ })+ .then((snapshot) => {+ digestNow = snapshot.digest+ return snapshot+ })+ return memoryCache+}++/**+ * The memory catalog for prompt injection: the newest notes, capped, then+ * name-sorted so the block is stable when nothing changed.+ */+export async function getMemoryCatalog(): Promise<MemoryCatalogEntry[]> {+ const { catalog } = await getMemorySnapshot()+ return [...catalog].sort((a, b) => a.name.localeCompare(b.name))+}++/** Ensure the digest is loaded; chat awaits this before building its prompt. */+export async function refreshMemoryDigest(): Promise<string> {+ return (await getMemorySnapshot()).digest+}++/**+ * Synchronous view of the digest, for the sync prompt builder. `''` until+ * `refreshMemoryDigest` resolves, which `sendMessages` awaits first.+ */+export function memoryDigestNow(): string {+ return digestNow+}+type AgentToolResult = {content?: unknownerror?: string@@ -128,10 +225,8 @@ const messageOf = (e: unknown): string =>* the desktop has no project picker yet, so the plugin uses the permanent store* in the Jan data folder.*- * `bash` additionally runs under an OS sandbox, whose network access follows the- * `bashNetworkEnabled` setting. It is read here, per call, rather than captured- * once, so toggling it takes effect on the next command instead of the next- * restart.+ * `bash` additionally runs under an OS sandbox whose network access is closed+ * unless the caller opens it. Chat never does; Cowork passes its own setting.*/export async function executeAgentTool(toolName: string,@@ -149,7 +244,9 @@ export async function executeAgentTool(* where the thread sweep's keep-list can never mention them — and the sweep* would delete the only copy of the agent's work.*/- scope: WorkspaceScope = 'thread'+ scope: WorkspaceScope = 'thread',+ /** Opens the sandboxed shell's network namespace. Closed by default. */+ allowNetwork = false): Promise<AgentToolResult> {try {const dataFolder = await getServiceHub().app().getJanDataFolder()@@ -165,11 +262,14 @@ export async function executeAgentTool(args,undefined,undefined,- useAgentToolsConfig.getState().bashNetworkEnabled,+ allowNetwork,readOnlyProject ?? undefined,scope)if (result.isError) return { error: result.content }+ // The store changed, so the recall injections must not keep serving the+ // snapshot taken before this note existed.+ if (toolName === 'memory_write') invalidateMemory()return { content: result.content, diff: result.diff ?? undefined }} catch (e) {return { error: messageOf(e) }diff --git a/web-app/src/lib/agentWorkspace.ts b/web-app/src/lib/agentWorkspace.tsindex 61419ced2..83ae86655 100644--- a/web-app/src/lib/agentWorkspace.ts+++ b/web-app/src/lib/agentWorkspace.ts@@ -6,6 +6,7 @@ import {memoryDelete,} from '@janhq/tauri-plugin-agent-tools-api'import { getServiceHub } from '@/hooks/useServiceHub'+import { invalidateMemory } from '@/lib/agentTools'import * as skillStore from '@/lib/skillStore'import type { SkillMeta } from '@/lib/skillStore'@@ -51,10 +52,45 @@ export async function readMemory(name: string): Promise<string> {export async function writeMemory(name: string, content: string): Promise<void> {await memoryWrite(await dataFolder(), name, content)+ invalidateMemory()}export async function deleteMemory(name: string): Promise<void> {await memoryDelete(await dataFolder(), name)+ invalidateMemory()+}++/**+ * A filesystem-safe note name from a thread title. The store's names are file+ * stems, so everything but `[a-z0-9-]` collapses to hyphens; an unusable title+ * falls back to a generic stem rather than failing the save.+ */+export function slugifyMemoryName(title: string): string {+ const slug = title+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 60)+ .replace(/-+$/, '')+ return slug || 'memory'+}++/**+ * The chat surface's "Remember" action: save `content` as a note named after+ * the thread title. `memory_write` replaces a note by name, and this is a new+ * fact rather than a curated topic, so an existing name gets a `-2`, `-3`, ...+ * suffix instead of silently overwriting it. Returns the name written.+ */+export async function rememberNote(+ title: string,+ content: string+): Promise<string> {+ const base = slugifyMemoryName(title)+ const taken = new Set(await listMemories())+ let name = base+ for (let n = 2; taken.has(name); n++) name = `${base}-${n}`+ await writeMemory(name, content)+ return name}/** Open the store in the OS file manager. */diff --git a/web-app/src/lib/coworkDispatch.ts b/web-app/src/lib/coworkDispatch.tsindex 8230849eb..faf48c4d8 100644--- a/web-app/src/lib/coworkDispatch.ts+++ b/web-app/src/lib/coworkDispatch.ts@@ -1,4 +1,5 @@import { executeAgentTool } from '@/lib/agentTools'+import { useCoworkConfig } from '@/hooks/useCoworkConfig'import {ASK_TOOL_NAME,PLAN_DENIED_TOOLS,@@ -85,13 +86,16 @@ export async function dispatchCoworkTool(// `'session'`, not the default `'thread'`: a Cowork session id lives in its// own namespace, and the thread sweep would otherwise delete this sandbox- // because no chat thread claims it.+ // because no chat thread claims it. The network flag follows Cowork's own+ // setting (on by default), read per call so a toggle in Settings applies to+ // the next command; chat's shell stays network-closed regardless.const result = await executeAgentTool(toolName,call.input,ctx.sessionId,ctx.readOnlyFolder,- 'session'+ 'session',+ useCoworkConfig.getState().networkEnabled)if (result.error) return { output: result.error, isError: true }return {diff --git a/web-app/src/lib/coworkPrompt.ts b/web-app/src/lib/coworkPrompt.tsindex 5c655c24b..3d5a8372b 100644--- a/web-app/src/lib/coworkPrompt.ts+++ b/web-app/src/lib/coworkPrompt.ts@@ -52,6 +52,30 @@ export type CoworkPromptOptions = {subagentNames: string[]/** Whether `web_search`/`web_fetch` are advertised this run. */webSearch: boolean+ /**+ * Progressive-disclosure recall: one line per note, dereferenced on demand+ * with `memory_read`. Snapshotted at the run boundary alongside the frozen+ * tool set, so the prompt prefix is stable for the run.+ */+ memoryCatalog: { name: string; summary: string }[]+}++/** Mirrors the Rust CLI's `load_memory_catalog` block, one wording for both. */+function memoryBlock(catalog: { name: string; summary: string }[]): string {+ const list = catalog+ .map(({ name, summary }) =>+ summary ? `- \`${name}\` - ${summary}` : `- \`${name}\` - no summary`+ )+ .join('\n')+ return [+ '# Available Memories',+ '',+ 'Durable facts recorded in earlier sessions. Read a note in full with',+ '`memory_read` when it is relevant to the current task, and record new',+ 'durable facts (not session state) with `memory_write`.',+ '',+ list,+ ].join('\n')}/** Marker text matches chat's, so the same renderer turns it into source chips. */@@ -99,6 +123,7 @@ function workspaceBlock(opts: CoworkPromptOptions): string {export function buildCoworkSystemPrompt(opts: CoworkPromptOptions): string {const blocks = [IDENTITY, GUIDELINES, workspaceBlock(opts)]+ if (opts.memoryCatalog.length > 0) blocks.push(memoryBlock(opts.memoryCatalog))if (opts.webSearch) blocks.push(WEB_BLOCK)if (opts.subagentNames.length > 0 && !opts.planMode) {blocks.push(@@ -127,11 +152,13 @@ export function buildCoworkSystemPrompt(opts: CoworkPromptOptions): string {*/export function buildSubagentSystemPrompt(definitionPrompt: string,- opts: Omit<CoworkPromptOptions, 'planMode' | 'subagentNames'>+ // No memory catalog: a child runs one stated errand, so recall is the+ // dispatching agent's job -- it reads the note and states what matters.+ opts: Omit<CoworkPromptOptions, 'planMode' | 'subagentNames' | 'memoryCatalog'>): string {return [definitionPrompt.trim(),- workspaceBlock({ ...opts, planMode: false, subagentNames: [] }),+ workspaceBlock({ ...opts, planMode: false, subagentNames: [], memoryCatalog: [] }),...(opts.webSearch ? [WEB_BLOCK] : []),['# Scope',diff --git a/web-app/src/lib/coworkRunner.ts b/web-app/src/lib/coworkRunner.tsindex 7be0bc3dd..e5d99fb51 100644--- a/web-app/src/lib/coworkRunner.ts+++ b/web-app/src/lib/coworkRunner.ts@@ -116,6 +116,41 @@ export function isAbortLike(e: unknown, signal?: AbortSignal): boolean {)}+/**+ * True when a failed send can be retried safely: the connection died before any+ * response arrived, so nothing has been streamed and no upstream side effect is+ * implied. Port of the Rust agent's `is_retryable_send_error` — the failure a+ * long turn invites is a keep-alive connection the peer (or its load balancer)+ * reclaimed while tools ran locally, reported on the *next* request. Matched on+ * text because the tauri http plugin and the AI SDK both surface transport+ * failures as message strings. Timeouts are excluded on purpose: retrying one+ * doubles the wait.+ */+export function isRetryableSendError(message: string): boolean {+ const msg = message.toLowerCase()+ if (msg.includes('timed out') || msg.includes('timeout')) return false+ const markers = [+ // hyper reports a pooled connection the peer had already closed as the+ // first of these; the rest are the io errors an RST mid-request produces.+ 'connection closed before message completed',+ 'connection reset',+ 'broken pipe',+ 'connection aborted',+ 'unexpected eof',+ // A refused or failed connect: reqwest via the tauri http plugin, and the+ // browser fetch in the web build.+ 'connection refused',+ 'error sending request',+ 'failed to fetch',+ 'fetch failed',+ ]+ return markers.some((m) => msg.includes(m))+}++/** Long enough for a load balancer that just recycled a backend to finish,+ * short enough that the user does not read it as a hang. */+const SEND_RETRY_DELAY_MS = 250+/** Settle a pending `ask`. Returns false when the request is already gone. */export function answerAsk(sid: string,@@ -345,25 +380,79 @@ export async function runTurn(opts: {// stream is handed over, and the transport rewrites what it is given// (trimming, compaction) without expecting it to move underneath.let result: StepResult- try {- const stream = await deps.sendStep([...messages], signal)- result = await consumeStep(stream, deps.sink)- } catch (e) {- // A transport failure is an outcome, not an exception: throwing here left- // the caller with no steps, no usage and nothing to render but the raw- // message, and a user-initiated stop arrived down this same path.- return {- messages,- steps: step,- usage,- sessionTokens: spend.spent,- stoppedBy: isAbortLike(e, signal) ? 'aborted' : 'error',- errorText: isAbortLike(e, signal)- ? undefined- : e instanceof Error- ? e.message- : String(e),+ let retried = false+ for (;;) {+ // Any sink activity means bytes reached the UI; replaying the request+ // would duplicate them, so a retry is only safe while this stays false.+ let received = false+ const sink: StreamSink = {+ onText: (d) => {+ received = true+ deps.sink.onText(d)+ },+ onToolStart: (id, name) => {+ received = true+ deps.sink.onToolStart(id, name)+ },+ onToolArgsDelta: (id, d) => {+ received = true+ deps.sink.onToolArgsDelta(id, d)+ },+ onToolCall: (c) => {+ received = true+ deps.sink.onToolCall(c)+ },+ }+ try {+ const stream = await deps.sendStep([...messages], signal)+ result = await consumeStep(stream, sink)+ } catch (e) {+ if (isAbortLike(e, signal)) {+ return {+ messages,+ steps: step,+ usage,+ sessionTokens: spend.spent,+ stoppedBy: 'aborted',+ }+ }+ const errorText = e instanceof Error ? e.message : String(e)+ if (!retried && !received && isRetryableSendError(errorText)) {+ retried = true+ console.warn(`[coworkRunner] ${errorText} — retrying once`)+ await new Promise((r) => setTimeout(r, SEND_RETRY_DELAY_MS))+ continue+ }+ // A transport failure is an outcome, not an exception: throwing here+ // left the caller with no steps, no usage and nothing to render but+ // the raw message, and a user-initiated stop arrived down this path.+ return {+ messages,+ steps: step,+ usage,+ sessionTokens: spend.spent,+ stoppedBy: 'error',+ errorText,+ }+ }+ // A dropped connection can also surface as an error chunk — streamText+ // reports transport failures through the stream — so an error that+ // arrived before anything else gets the same single retry.+ if (+ !retried &&+ !received &&+ result.usage === null &&+ !result.aborted &&+ !signal.aborted &&+ result.errorText !== undefined &&+ isRetryableSendError(result.errorText)+ ) {+ retried = true+ console.warn(`[coworkRunner] ${result.errorText} — retrying once`)+ await new Promise((r) => setTimeout(r, SEND_RETRY_DELAY_MS))+ continue}+ break}step += 1if (result.usage) {diff --git a/web-app/src/lib/coworkTransport.ts b/web-app/src/lib/coworkTransport.tsindex 97f8d2583..23c551887 100644--- a/web-app/src/lib/coworkTransport.ts+++ b/web-app/src/lib/coworkTransport.ts@@ -1,7 +1,11 @@import type { Tool, UIMessage } from 'ai'import { CustomChatTransport } from '@/lib/custom-chat-transport'import { COWORK_SLOT_ID } from '@/constants/models'-import { sandboxEnforces } from '@/lib/agentTools'+import {+ getMemoryCatalog,+ sandboxEnforces,+ type MemoryCatalogEntry,+} from '@/lib/agentTools'import {buildCoworkTools,coworkToolSignature,@@ -36,6 +40,12 @@ export class CoworkChatTransport extends CustomChatTransport {* pay for a rebuild at every run boundary. */private builtTools: Record<string, Tool> | null = nullprivate builtSig = ''+ /**+ * The memory catalog advertised this run. Snapshotted with the tool freeze,+ * for the same reason: a mid-run change to the prompt prefix discards the KV+ * cache on every step. A note written mid-run appears at the next run.+ */+ private memoryCatalog: MemoryCatalogEntry[] = []constructor(sessionId: string, config: CoworkRunConfig) {super(undefined, sessionId)@@ -82,6 +92,7 @@ export class CoworkChatTransport extends CustomChatTransport {bashAvailable: sandboxEnforces(),subagentNames: this.config.allowSubagents ? this.config.subagentNames : [],webSearch: this.config.webSearch,+ memoryCatalog: this.memoryCatalog,})const files = this.buildFilesSystemInstruction(messages)return files.trim().length > 0 ? `${base}\n\n${files}` : base@@ -104,6 +115,9 @@ export class CoworkChatTransport extends CustomChatTransport {this.tools = this.frozenToolsreturn}+ // Run boundary: re-snapshot the catalog even when the tool set is reused,+ // since memory moves independently of the tool config.+ this.memoryCatalog = await getMemoryCatalog()const sig = coworkToolSignature(this.config, sandboxEnforces())// Between runs, skip the rebuild when nothing that shapes the set changed.if (this.builtTools && this.builtSig === sig) {diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.tsindex 556b66fc9..bb0cf03eb 100644--- a/web-app/src/lib/custom-chat-transport.ts+++ b/web-app/src/lib/custom-chat-transport.ts@@ -27,8 +27,13 @@ import {WEB_FETCH_DESCRIPTION,WEB_FETCH_INPUT_SCHEMA,} from '@/lib/webSearchTool'-import { useAgentToolsConfig } from '@/hooks/useAgentToolsConfig'-import { getAgentToolSchemas, sandboxEnforces } from '@/lib/agentTools'+import {+ CHAT_AGENT_TOOL_NAMES,+ getAgentToolSchemas,+ memoryDigestNow,+ refreshMemoryDigest,+ sandboxEnforces,+} from '@/lib/agentTools'import { useAppState } from '@/hooks/useAppState'import { unloadLlamaModel, getLoadedModels } from '@janhq/tauri-plugin-llamacpp-api'import { engineFailure } from '@/lib/engineError'@@ -881,6 +886,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {const raw =[this.systemMessage,+ this.buildMemorySystemInstruction(),this.buildFilesSystemInstruction(messages),this.buildWebSearchSystemInstruction(),this.buildAgentToolsSystemInstruction(),@@ -904,6 +910,10 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {}async refreshTools(abortSignal?: AbortSignal) {+ // Resolve the memory digest before the prompt is built: the builder is+ // sync, so it reads the snapshot this await guarantees. Error-safe and+ // cached inside agentTools, so this is one IPC round-trip per store change.+ await refreshMemoryDigest()if (!this.serviceHub) {this.tools = {}return@@ -1063,20 +1073,20 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {} as Tool}- // Built-in agent tools (filesystem reads plus skills/memory), provided by- // the agent-tools plugin. Schemas come from Rust so they are never- // re-typed here.- if (useAgentToolsConfig.getState().agentToolsEnabled) {- try {- for (const schema of await getAgentToolSchemas()) {- toolsRecord[schema.function.name] = {- description: schema.function.description,- inputSchema: jsonSchema(schema.function.parameters),- } as Tool- }- } catch (error) {- console.warn('Failed to load agent tools:', error)+ // The main chat offers exactly one built-in agent tool: the sandboxed+ // shell, with no network. The full toolset lives in Cowork. Schemas come+ // from Rust so they are never re-typed here, and `getAgentToolSchemas`+ // already withholds bash when no sandbox backend can confine it.+ try {+ for (const schema of await getAgentToolSchemas()) {+ if (!CHAT_AGENT_TOOL_NAMES.has(schema.function.name)) continue+ toolsRecord[schema.function.name] = {+ description: schema.function.description,+ inputSchema: jsonSchema(schema.function.parameters),+ } as Tool}+ } catch (error) {+ console.warn('Failed to load agent tools:', error)}}@@ -1749,38 +1759,42 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {}/**- * Static instruction describing the isolated agent workspace the built-in- * tools operate in. Only added when the toolset is enabled so it doesn't- * affect prompt caching for users who keep it off.+ * Static instruction for the one built-in tool chat offers: the sandboxed+ * shell. Empty when no sandbox backend enforces, because bash is then+ * withheld too — stating limits for a tool that is not offered would only+ * confuse the model, and an empty string keeps the prompt prefix stable.+ */+ /**+ * A self-contained digest of the newest memory notes. Chat advertises no+ * memory tools, so a catalog it cannot dereference would be useless; whole+ * notes under a strict budget are what fit a conversation surface. Empty when+ * no note fits, keeping the prompt prefix unchanged for users without memory.*/+ buildMemorySystemInstruction(): string {+ const digest = memoryDigestNow()+ if (!digest) return ''+ return [+ '# Background Memory',+ 'Notes the user previously chose to keep, from earlier conversations.',+ 'They may be stale; prefer what this conversation itself establishes.',+ '',+ digest,+ ].join('\n')+ }+buildAgentToolsSystemInstruction(): string {- if (!useAgentToolsConfig.getState().agentToolsEnabled) return ''- const parts = [- '# Workspace',- 'read, ls, find, grep, write and edit operate on an isolated agent',- "workspace, not the user's whole filesystem. Paths are relative to that",- 'workspace root and cannot escape it. The workspace is scratch space for',- 'this conversation only and is deleted with it, so do not keep anything',- 'there that should last. Use memory_write to persist facts worth remembering',- 'across conversations, and memory_list/memory_read to recall them. Skills',- 'are reusable instructions: list and read them before a task they cover,',- 'and record a repeatable procedure with skill_write.',- ]+ if (!sandboxEnforces()) return ''// Stating the limits up front is cheaper than letting the model discover- // them by having a command refused. Only when bash is actually offered.- if (sandboxEnforces()) {- parts.push(- 'bash runs commands in that workspace under an OS sandbox: it starts',- 'there, can only write there, and cannot read files in the',- "user's home directory."- )- parts.push(- useAgentToolsConfig.getState().bashNetworkEnabled- ? 'It has network access.'- : 'It has no network access, so commands that download or upload will fail.'- )- }- return parts.join(' ')+ // them by having a command refused.+ return [+ '# Shell',+ 'bash runs commands in an isolated scratch workspace under an OS',+ 'sandbox: it starts there, can only write there, and cannot read files',+ "in the user's home directory. The workspace belongs to this",+ 'conversation alone and is deleted with it, so do not keep anything',+ 'there that should last. It has no network access, so commands that',+ 'download or upload will fail.',+ ].join(' ')}mapUserInlineAttachments(messages: UIMessage[]): UIMessage[] {diff --git a/web-app/src/lib/hydrateStores.ts b/web-app/src/lib/hydrateStores.tsindex e470a8b48..38a10c50f 100644--- a/web-app/src/lib/hydrateStores.ts+++ b/web-app/src/lib/hydrateStores.ts@@ -21,7 +21,7 @@ import { useDefaultEmbeddingModel } from '@/hooks/useDefaultEmbeddingModel'import { useAgentMode } from '@/hooks/useAgentMode'import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'import { useCoworkSessions } from '@/hooks/useCoworkSessions'-import { useAgentToolsConfig } from '@/hooks/useAgentToolsConfig'+import { useCoworkConfig } from '@/hooks/useCoworkConfig'/*** Stores persisted through `backendStorage` set `skipHydration: true` so they@@ -54,7 +54,7 @@ const secondaryStores = [useAgentMode,useWebSearchConfig,useCoworkSessions,- useAgentToolsConfig,+ useCoworkConfig,] as constexport async function hydrateBackendStores(): Promise<void> {diff --git a/web-app/src/locales/en/chat.json b/web-app/src/locales/en/chat.jsonindex c9f69f518..548d43d74 100644--- a/web-app/src/locales/en/chat.json+++ b/web-app/src/locales/en/chat.json@@ -15,7 +15,10 @@},"actions": {"regenerate": "Regenerate response",- "continue": "Continue generating"+ "continue": "Continue generating",+ "remember": "Remember this",+ "rememberSaved": "Saved to memory as \"{{name}}\"",+ "rememberFailed": "Could not save to memory"},"done": "Done","webSources": "{{count}} source(s)",diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex 543574269..2b4a3849e 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -16,7 +16,6 @@"claude_code": "Claude Code","https_proxy": "HTTPS Proxy","web_search": "Web Search",- "agent_tools": "Agent Tools","browse": "Browse","starting": "Starting...","activeSuffix": " (Active)",diff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.jsonindex 04612e494..99070cff2 100644--- a/web-app/src/locales/en/settings.json+++ b/web-app/src/locales/en/settings.json@@ -204,17 +204,15 @@"endpointDesc": "Required. The base URL of your {{provider}} instance, with the JSON API enabled.","endpointPlaceholder": "https://searx.example.com"},- "agentTools": {- "title": "Agent Tools",- "description": "Give models a private scratch workspace for each conversation, plus memories and skills kept permanently in your Jan data folder.",- "enable": "Enable Agent Tools",- "enableDesc": "Advertise the built-in workspace, memory and skill tools to models that support tool use. Tools that need approval stay unavailable.",+ "cowork": {+ "title": "Cowork",+ "description": "Configure the Cowork agent surface: its sandboxed shell, plus the memories and skills kept permanently in your Jan data folder.","shell": "Shell Commands","shellChecking": "Checking for a sandbox...",- "shellSandboxed": "Commands run confined by {{backend}}: they can only write inside the conversation workspace, and files in your home folder are not readable.",+ "shellSandboxed": "Commands run confined by {{backend}}: they can only write inside the session workspace, and files in your home folder are not readable.","shellUnavailable": "No sandbox is available on this system, so the bash tool is not offered. Commands are never run unconfined.","network": "Allow Network Access",- "networkDesc": "Let commands reach the network. Needed for things like installing packages or fetching a repository. Off by default, so a command cannot send anything off your machine.",+ "networkDesc": "Let Cowork commands reach the network, for things like installing packages or fetching a repository. On by default. The main chat's shell never has network access.","openFolder": "Open Folder","memories": "Memories","noMemories": "No memories yet. Models add them with the memory_write tool as they learn things worth keeping.",diff --git a/web-app/src/routeTree.gen.ts b/web-app/src/routeTree.gen.tsindex 6c52f6e05..804429e34 100644--- a/web-app/src/routeTree.gen.ts+++ b/web-app/src/routeTree.gen.ts@@ -29,7 +29,7 @@ import { Route as SettingsExtensionsRouteImport } from './routes/settings/extensimport { Route as SettingsClaudeCodeRouteImport } from './routes/settings/claude-code'import { Route as SettingsAttachmentsRouteImport } from './routes/settings/attachments'import { Route as SettingsAssistantRouteImport } from './routes/settings/assistant'-import { Route as SettingsAgentToolsRouteImport } from './routes/settings/agent-tools'+import { Route as SettingsCoworkRouteImport } from './routes/settings/cowork'import { Route as ProjectProjectIdRouteImport } from './routes/project/$projectId'import { Route as LocalApiServerLogsRouteImport } from './routes/local-api-server/logs'import { Route as HubModelIdRouteImport } from './routes/hub/$modelId'@@ -136,9 +136,9 @@ const SettingsAssistantRoute = SettingsAssistantRouteImport.update({path: '/settings/assistant',getParentRoute: () => rootRouteImport,} as any)-const SettingsAgentToolsRoute = SettingsAgentToolsRouteImport.update({- id: '/settings/agent-tools',- path: '/settings/agent-tools',+const SettingsCoworkRoute = SettingsCoworkRouteImport.update({+ id: '/settings/cowork',+ path: '/settings/cowork',getParentRoute: () => rootRouteImport,} as any)const ProjectProjectIdRoute = ProjectProjectIdRouteImport.update({@@ -177,7 +177,7 @@ export interface FileRoutesByFullPath {'/hub/$modelId': typeof HubModelIdRoute'/local-api-server/logs': typeof LocalApiServerLogsRoute'/project/$projectId': typeof ProjectProjectIdRoute- '/settings/agent-tools': typeof SettingsAgentToolsRoute+ '/settings/cowork': typeof SettingsCoworkRoute'/settings/assistant': typeof SettingsAssistantRoute'/settings/attachments': typeof SettingsAttachmentsRoute'/settings/claude-code': typeof SettingsClaudeCodeRoute@@ -205,7 +205,7 @@ export interface FileRoutesByTo {'/hub/$modelId': typeof HubModelIdRoute'/local-api-server/logs': typeof LocalApiServerLogsRoute'/project/$projectId': typeof ProjectProjectIdRoute- '/settings/agent-tools': typeof SettingsAgentToolsRoute+ '/settings/cowork': typeof SettingsCoworkRoute'/settings/assistant': typeof SettingsAssistantRoute'/settings/attachments': typeof SettingsAttachmentsRoute'/settings/claude-code': typeof SettingsClaudeCodeRoute@@ -234,7 +234,7 @@ export interface FileRoutesById {'/hub/$modelId': typeof HubModelIdRoute'/local-api-server/logs': typeof LocalApiServerLogsRoute'/project/$projectId': typeof ProjectProjectIdRoute- '/settings/agent-tools': typeof SettingsAgentToolsRoute+ '/settings/cowork': typeof SettingsCoworkRoute'/settings/assistant': typeof SettingsAssistantRoute'/settings/attachments': typeof SettingsAttachmentsRoute'/settings/claude-code': typeof SettingsClaudeCodeRoute@@ -264,7 +264,7 @@ export interface FileRouteTypes {| '/hub/$modelId'| '/local-api-server/logs'| '/project/$projectId'- | '/settings/agent-tools'+ | '/settings/cowork'| '/settings/assistant'| '/settings/attachments'| '/settings/claude-code'@@ -292,7 +292,7 @@ export interface FileRouteTypes {| '/hub/$modelId'| '/local-api-server/logs'| '/project/$projectId'- | '/settings/agent-tools'+ | '/settings/cowork'| '/settings/assistant'| '/settings/attachments'| '/settings/claude-code'@@ -320,7 +320,7 @@ export interface FileRouteTypes {| '/hub/$modelId'| '/local-api-server/logs'| '/project/$projectId'- | '/settings/agent-tools'+ | '/settings/cowork'| '/settings/assistant'| '/settings/attachments'| '/settings/claude-code'@@ -349,7 +349,7 @@ export interface RootRouteChildren {HubModelIdRoute: typeof HubModelIdRouteLocalApiServerLogsRoute: typeof LocalApiServerLogsRouteProjectProjectIdRoute: typeof ProjectProjectIdRoute- SettingsAgentToolsRoute: typeof SettingsAgentToolsRoute+ SettingsCoworkRoute: typeof SettingsCoworkRouteSettingsAssistantRoute: typeof SettingsAssistantRouteSettingsAttachmentsRoute: typeof SettingsAttachmentsRouteSettingsClaudeCodeRoute: typeof SettingsClaudeCodeRoute@@ -511,11 +511,11 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsAssistantRouteImportparentRoute: typeof rootRouteImport}- '/settings/agent-tools': {- id: '/settings/agent-tools'- path: '/settings/agent-tools'- fullPath: '/settings/agent-tools'- preLoaderRoute: typeof SettingsAgentToolsRouteImport+ '/settings/cowork': {+ id: '/settings/cowork'+ path: '/settings/cowork'+ fullPath: '/settings/cowork'+ preLoaderRoute: typeof SettingsCoworkRouteImportparentRoute: typeof rootRouteImport}'/project/$projectId': {@@ -565,7 +565,7 @@ const rootRouteChildren: RootRouteChildren = {HubModelIdRoute: HubModelIdRoute,LocalApiServerLogsRoute: LocalApiServerLogsRoute,ProjectProjectIdRoute: ProjectProjectIdRoute,- SettingsAgentToolsRoute: SettingsAgentToolsRoute,+ SettingsCoworkRoute: SettingsCoworkRoute,SettingsAssistantRoute: SettingsAssistantRoute,SettingsAttachmentsRoute: SettingsAttachmentsRoute,SettingsClaudeCodeRoute: SettingsClaudeCodeRoute,diff --git a/web-app/src/routes/settings/agent-tools.tsx b/web-app/src/routes/settings/cowork.tsxsimilarity index 78%rename from web-app/src/routes/settings/agent-tools.tsxrename to web-app/src/routes/settings/cowork.tsxindex bd944151c..fd1c1275d 100644--- a/web-app/src/routes/settings/agent-tools.tsx+++ b/web-app/src/routes/settings/cowork.tsx@@ -25,7 +25,7 @@ import {} from '@tabler/icons-react'import { toast } from 'sonner'import { useTranslation } from '@/i18n/react-i18next-compat'-import { useAgentToolsConfig } from '@/hooks/useAgentToolsConfig'+import { useCoworkConfig } from '@/hooks/useCoworkConfig'import { getSandboxStatus } from '@/lib/agentTools'import type { SandboxStatus } from '@janhq/tauri-plugin-agent-tools-api'import {@@ -43,8 +43,8 @@ import {} from '@/lib/agentWorkspace'// eslint-disable-next-line @typescript-eslint/no-explicit-any-export const Route = createFileRoute(route.settings.agent_tools as any)({- component: AgentToolsContent,+export const Route = createFileRoute(route.settings.cowork as any)({+ component: CoworkSettingsContent,})type EntryKind = 'memory' | 'skill'@@ -65,16 +65,10 @@ const messageOf = (e: unknown): string =>const SKILL_TEMPLATE = '---\ndescription: \n---\n\n'-function AgentToolsContent() {+function CoworkSettingsContent() {const { t } = useTranslation()- const agentToolsEnabled = useAgentToolsConfig((s) => s.agentToolsEnabled)- const setAgentToolsEnabled = useAgentToolsConfig(- (s) => s.setAgentToolsEnabled- )- const bashNetworkEnabled = useAgentToolsConfig((s) => s.bashNetworkEnabled)- const setBashNetworkEnabled = useAgentToolsConfig(- (s) => s.setBashNetworkEnabled- )+ const networkEnabled = useCoworkConfig((s) => s.networkEnabled)+ const setNetworkEnabled = useCoworkConfig((s) => s.setNetworkEnabled)// `undefined` until the probe answers, so the row reads as "checking" rather// than briefly claiming there is no sandbox.const [sandbox, setSandbox] = useState<SandboxStatus | undefined>()@@ -96,7 +90,7 @@ function AgentToolsContent() {setSkills(nextSkills)setMemories(nextMemories)} catch (e) {- toast.error(t('settings:agentTools.loadFailed'), {+ toast.error(t('settings:cowork.loadFailed'), {description: messageOf(e),})}@@ -124,7 +118,7 @@ function AgentToolsContent() {kind === 'skill' ? await readSkill(name) : await readMemory(name)setEditor({ kind, original: name, name, content })} catch (e) {- toast.error(t('settings:agentTools.loadFailed'), {+ toast.error(t('settings:cowork.loadFailed'), {description: messageOf(e),})}@@ -141,7 +135,7 @@ function AgentToolsContent() {setEditor(null)await refresh()} catch (e) {- toast.error(t('settings:agentTools.saveFailed'), {+ toast.error(t('settings:cowork.saveFailed'), {description: messageOf(e),})} finally {@@ -155,7 +149,7 @@ function AgentToolsContent() {else await deleteMemory(name)await refresh()} catch (e) {- toast.error(t('settings:agentTools.deleteFailed'), {+ toast.error(t('settings:cowork.deleteFailed'), {description: messageOf(e),})}@@ -165,7 +159,7 @@ function AgentToolsContent() {try {await revealStore()} catch (e) {- toast.error(t('settings:agentTools.revealFailed'), {+ toast.error(t('settings:cowork.revealFailed'), {description: messageOf(e),})}@@ -209,7 +203,7 @@ function AgentToolsContent() {{t(titleKey)}</h1><Button variant="outline" size="sm" onClick={() => openEditor(kind)}>- {t('settings:agentTools.add')}+ {t('settings:cowork.add')}</Button></div>)@@ -232,10 +226,10 @@ function AgentToolsContent() {<div className="flex items-start justify-between gap-4 mb-4"><div className="space-y-1"><h1 className="text-foreground font-studio font-medium text-base">- {t('settings:agentTools.title')}+ {t('settings:cowork.title')}</h1><p className="text-muted-foreground leading-normal">- {t('settings:agentTools.description')}+ {t('settings:cowork.description')}</p></div>{/* The path is a tooltip, not a row: it derives from the Jan@@ -249,24 +243,13 @@ function AgentToolsContent() {disabled={!path}><IconFolderCode size={16} />- {t('settings:agentTools.openFolder')}+ {t('settings:cowork.openFolder')}</Button></div>}><CardItem- title={t('settings:agentTools.enable')}- description={t('settings:agentTools.enableDesc')}- align="start"- actions={- <Switch- checked={agentToolsEnabled}- onCheckedChange={setAgentToolsEnabled}- />- }- />- <CardItem- title={t('settings:agentTools.shell')}+ title={t('settings:cowork.shell')}align="start"description={<span className="flex items-start gap-1.5">@@ -280,12 +263,12 @@ function AgentToolsContent() {)}<span>{sandbox === undefined- ? t('settings:agentTools.shellChecking')+ ? t('settings:cowork.shellChecking'): sandbox.enforces- ? t('settings:agentTools.shellSandboxed', {+ ? t('settings:cowork.shellSandboxed', {backend: sandbox.backend,})- : t('settings:agentTools.shellUnavailable')}+ : t('settings:cowork.shellUnavailable')}</span></span>}@@ -294,33 +277,32 @@ function AgentToolsContent() {no shell to give network access to in the first place. */}{sandbox?.enforces && (<CardItem- title={t('settings:agentTools.network')}- description={t('settings:agentTools.networkDesc')}+ title={t('settings:cowork.network')}+ description={t('settings:cowork.networkDesc')}align="start"actions={<Switch- checked={bashNetworkEnabled}- onCheckedChange={setBashNetworkEnabled}- disabled={!agentToolsEnabled}+ checked={networkEnabled}+ onCheckedChange={setNetworkEnabled}/>}/>)}</Card>- <Card header={sectionHeader('settings:agentTools.memories', 'memory')}>+ <Card header={sectionHeader('settings:cowork.memories', 'memory')}>{memories.length === 0 ? (<CardItem- description={t('settings:agentTools.noMemories')}+ description={t('settings:cowork.noMemories')}/>) : (memories.map((name) => entryRow('memory', name)))}</Card>- <Card header={sectionHeader('settings:agentTools.skills', 'skill')}>+ <Card header={sectionHeader('settings:cowork.skills', 'skill')}>{skills.length === 0 ? (- <CardItem description={t('settings:agentTools.noSkills')} />+ <CardItem description={t('settings:cowork.noSkills')} />) : (skills.map((skill) =>entryRow('skill', skill.name, skill.description)@@ -340,22 +322,22 @@ function AgentToolsContent() {<DialogTitle>{t(editor?.kind === 'skill'- ? 'settings:agentTools.editSkill'- : 'settings:agentTools.editMemory'+ ? 'settings:cowork.editSkill'+ : 'settings:cowork.editMemory')}</DialogTitle><DialogDescription>{t(editor?.kind === 'skill'- ? 'settings:agentTools.editSkillDesc'- : 'settings:agentTools.editMemoryDesc'+ ? 'settings:cowork.editSkillDesc'+ : 'settings:cowork.editMemoryDesc')}</DialogDescription></DialogHeader><div className="space-y-3"><Inputtype="text"- placeholder={t('settings:agentTools.namePlaceholder')}+ placeholder={t('settings:cowork.namePlaceholder')}value={editor?.name ?? ''}// Locked once the entry exists: a new name would create a second// entry rather than rename this one.@@ -368,7 +350,7 @@ function AgentToolsContent() {/><TextareaclassName="min-h-64 font-mono text-xs"- placeholder={t('settings:agentTools.contentPlaceholder')}+ placeholder={t('settings:cowork.contentPlaceholder')}value={editor?.content ?? ''}onChange={(e) =>setEditor((prev) =>diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex 130adcc86..7aa63df9e 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -78,7 +78,7 @@ import { useToolApproval } from '@/hooks/useToolApproval'import { useToolApprovalRequests } from '@/hooks/useToolApprovalRequests'import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'import { WEB_TOOL_NAMES, executeWebTool } from '@/lib/webSearchTool'-import { AGENT_TOOL_NAMES, executeAgentTool } from '@/lib/agentTools'+import { CHAT_AGENT_TOOL_NAMES, executeAgentTool } from '@/lib/agentTools'import DropdownModelProvider from '@/containers/DropdownModelProvider'import { ExtensionTypeEnum, VectorDBExtension } from '@janhq/core'import { ExtensionManager } from '@/lib/extension'@@ -102,13 +102,13 @@ function serverForTool(toolName: string): string | undefined {}// Internal tools never prompt: RAG and the native web tools are Jan's own, and-// the built-in agent tools are gated in Rust (execute_tool refuses anything-// needing approval), so only workspace-confined calls ever reach here.+// the built-in shell is gated in Rust (execute_tool refuses anything needing+// approval), so only workspace-confined calls ever reach here.function isAutoAllowedTool(toolName: string): boolean {return (useAppState.getState().ragToolNames.has(toolName) ||WEB_TOOL_NAMES.has(toolName) ||- AGENT_TOOL_NAMES.has(toolName)+ CHAT_AGENT_TOOL_NAMES.has(toolName))}@@ -532,7 +532,9 @@ function ThreadDetail() {if (WEB_TOOL_NAMES.has(toolName)) {result = await executeWebTool(toolName, toolCall.input)- } else if (AGENT_TOOL_NAMES.has(toolName)) {+ } else if (CHAT_AGENT_TOOL_NAMES.has(toolName)) {+ // Chat's shell runs with the sandbox network closed: the default+ // `allowNetwork = false` is the contract here, not an accident.const agentResult = await executeAgentTool(toolName,toolCall.input,