Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(cowork): merge global and folder skills instead of replacing (#8879)
Akarshan Biswas41127c66a396
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex ebe22725b..7d58aa9a1 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -752,7 +752,18 @@ async fn execute_tool_inner(.ensure(Path::new(&data_folder), &thread_id).await?;let scratch = workspace::ensure_scratch_dir(&thread_id).await?;- let store = resolve_store(&data_folder, project.as_deref());+ // Base store for memory and skill *writes*: always the permanent store,+ // independent of `project`. `project` only overlays its co-located skills on+ // top for `skill_list`/`skill_read` (#8879), so an attached folder's skills+ // reach the model without moving memory or authored skills off the permanent+ // store. (Equivalent to the old `resolve_store(.., None)`, which is what every+ // caller passed.)+ let store = workspace::permanent_store(Path::new(&data_folder));+ let skill_project: Option<PathBuf> = project+ .as_deref()+ .map(str::trim)+ .filter(|p| !p.is_empty())+ .map(|p| workspace::project_store(Path::new(p)));// Plural from the outset so attaching a second folder later is not another// signature change.let attached: Vec<PathBuf> = match read_only_project.as_deref() {@@ -866,6 +877,9 @@ async fn execute_tool_inner(.with_scratch_root(&scratch).with_read_roots(&read_roots).with_write_roots(&write_roots);+ if let Some(sp) = skill_project.as_deref() {+ ctx = ctx.with_skill_project_root(sp);+ }if let Some(id) = call_id.as_deref() {ctx = ctx.with_call_id(id);}@@ -1747,6 +1761,71 @@ mod tests {assert_eq!(out.content, "run it");let _ = std::fs::remove_dir_all(&data);}++ /// A folder passed as `project` layers its co-located skills on top of the+ /// permanent store: both reach `skill_list`, `skill_read` loads the folder's+ /// own skill, and memory/skill-writes stay on the permanent store (#8879).+ #[tokio::test]+ async fn an_attached_project_layers_skills_over_the_permanent_store() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();+ let repo = repo_outside_tmp("skilllayer");+ let project = repo.to_string_lossy().to_string();++ skills::write(+ &workspace::permanent_store(&data),+ "global_skill",+ "---\ndescription: from global\n---\nglobal body",+ )+ .unwrap();+ skills::write(+ &workspace::project_store(&repo),+ "folder_skill",+ "---\ndescription: from folder\n---\nfolder body",+ )+ .unwrap();++ let listed = execute_tool(+ df.clone(),+ T1.into(),+ Some(project.clone()),+ "skill_list".into(),+ json!({}),+ None,+ None,+ None,+ None,+ None,+ None,+ )+ .await+ .unwrap();+ assert!(+ listed.content.contains("global_skill") && listed.content.contains("folder_skill"),+ "both stores must appear, got: {}",+ listed.content+ );++ let body = execute_tool(+ df.clone(),+ T2.into(),+ Some(project.clone()),+ "skill_read".into(),+ json!({"name": "folder_skill"}),+ None,+ None,+ None,+ None,+ None,+ None,+ )+ .await+ .unwrap();+ assert_eq!(body.content, "folder body");++ let _ = std::fs::remove_dir_all(&data);+ let _ = std::fs::remove_dir_all(&repo);+ }// ---- read-only attached folder, end to end ------------------------------/// The contract the workspace UI promises: the agent reads your folder anddiff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/skills.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/skills.rsindex 67f68ce92..b4858ad1e 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/skills.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/skills.rs@@ -143,7 +143,22 @@ pub fn safe_stem(name: &str) -> Result<String, String> {Ok(file.trim_end_matches(".md").to_string())}-/// All skills in the store, sorted by name. Folder skills (`<name>/SKILL.md`)+/// All skills across `roots` in precedence order, sorted by name. An earlier+/// root shadows a later one on a name collision, so a project's co-located+/// skills layer on top of the permanent store (#8879) without either set+/// vanishing. Within one root, the folder form wins over a legacy flat file.+pub fn discover_layered(roots: &[&Path]) -> Vec<SkillEntry> {+ let mut by_name: std::collections::BTreeMap<String, SkillEntry> =+ std::collections::BTreeMap::new();+ for root in roots {+ for entry in discover(root) {+ by_name.entry(entry.name.clone()).or_insert(entry);+ }+ }+ by_name.into_values().collect()+}++/// All skills in one store, sorted by name. Folder skills (`<name>/SKILL.md`)/// and legacy flat skills (`<name>.md`) are both discovered. When both forms/// share a name, the folder form wins so a skill is never listed/injected twice.pub fn discover(store: &Path) -> Vec<SkillEntry> {@@ -286,13 +301,13 @@ pub fn list_meta(store: &Path) -> Vec<SkillMeta> {/// invocation side. Skills with neither a description nor a body are skipped/// (nothing to advertise or invoke).fn side_catalog(- root: &Path,+ roots: &[&Path],enabled: &[String],side: impl Fn(&ParsedSkill) -> bool,) -> Vec<SkillMeta> {let allow: Option<std::collections::HashSet<&str>> =(!enabled.is_empty()).then(|| enabled.iter().map(String::as_str).collect());- let mut skills = discover(root)+ let mut skills = discover_layered(roots).into_iter().filter_map(|e| {if let Some(allow) = &allow {@@ -331,17 +346,30 @@ fn side_catalog(////// `enabled` is a whitelist of skill names; an empty list means "all skills"/// (backward-compatible with the agent.toml scaffold, which ships `enabled = []`).-pub(crate) fn catalog(root: &Path, enabled: &[String]) -> Vec<SkillMeta> {- side_catalog(root, enabled, |p| p.model_invocable)+///+/// `roots` are skill stores in precedence order: a project's co-located skills+/// layer on top of the permanent store, both reaching the model (#8879).+pub(crate) fn catalog_layered(roots: &[&Path], enabled: &[String]) -> Vec<SkillMeta> {+ side_catalog(roots, enabled, |p| p.model_invocable)}/// Raw SKILL.md text (frontmatter included) for the editor.pub fn read_raw(store: &Path, name: &str) -> Result<String, String> {+ read_raw_layered(&[store], name)+}++/// `read_raw` across `roots` in precedence order: the first root holding the+/// skill wins, so a project skill shadows a same-named permanent one (#8879).+pub fn read_raw_layered(roots: &[&Path], name: &str) -> Result<String, String> {if is_default_jan_skill(name) {return Ok(parse(DEFAULT_JAN_SKILL).body);}- let entry = resolve(store, name)?;- std::fs::read_to_string(&entry.file).map_err(|e| format!("ERROR: {e}"))+ for root in roots {+ if let Ok(entry) = resolve(root, name) {+ return std::fs::read_to_string(&entry.file).map_err(|e| format!("ERROR: {e}"));+ }+ }+ Err(format!("ERROR: skill '{name}' not found"))}/// A skill's markdown body with the frontmatter fence stripped — what the@@ -584,12 +612,11 @@ mod tests {write("model_only", "user-invocable: false\n");write("user_only", "disable-model-invocation: true\n");- let model: Vec<_> = catalog(&root, &[]).into_iter().map(|m| m.name).collect();- assert_eq!(- model,- vec!["both", "model_only", "jan"],- "model side: {model:?}"- );+ let model: Vec<_> = catalog_layered(&[root.as_path()], &[])+ .into_iter()+ .map(|m| m.name)+ .collect();+ assert_eq!(model, vec!["both", "model_only", "jan"], "model side: {model:?}");// Both flags still visible to the management list.let all = list_meta(&root);@@ -622,10 +649,10 @@ mod tests {write(&root, "b", "body b").unwrap();// Empty whitelist = all skills.- assert_eq!(catalog(&root, &[]).len(), 3);+ assert_eq!(catalog_layered(&[root.as_path()], &[]).len(), 3);// Non-empty whitelist restricts to the listed names.- let only_a = catalog(&root, &["a".to_string()]);+ let only_a = catalog_layered(&[root.as_path()], &["a".to_string()]);assert_eq!(only_a.len(), 1);assert_eq!(only_a[0].name, "a");let _ = std::fs::remove_dir_all(&root);@@ -683,4 +710,65 @@ mod tests {);let _ = std::fs::remove_dir_all(&root);}++ fn scratch(tag: &str) -> PathBuf {+ std::env::temp_dir().join(format!(+ "jan_skills_{tag}_{}",+ std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_nanos()+ ))+ }++ #[test]+ fn discover_layered_unions_roots_and_earlier_root_shadows() {+ let project = scratch("layer_p");+ let permanent = scratch("layer_g");+ write(&project, "shared", "project body").unwrap();+ write(&project, "only_project", "p").unwrap();+ write(&permanent, "shared", "permanent body").unwrap();+ write(&permanent, "only_global", "g").unwrap();++ let entries = discover_layered(&[project.as_path(), permanent.as_path()]);+ let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();+ assert_eq!(names, vec!["only_global", "only_project", "shared"]);+ // The project root wins the name collision.+ let shared = entries.iter().find(|e| e.name == "shared").unwrap();+ assert!(shared.file.starts_with(&project));++ let _ = std::fs::remove_dir_all(&project);+ let _ = std::fs::remove_dir_all(&permanent);+ }++ #[test]+ fn catalog_layered_merges_both_stores_with_one_jan() {+ let project = scratch("catp");+ let permanent = scratch("catg");+ write(&project, "p_skill", "p body").unwrap();+ write(&permanent, "g_skill", "g body").unwrap();++ let names: Vec<_> = catalog_layered(&[project.as_path(), permanent.as_path()], &[])+ .into_iter()+ .map(|m| m.name)+ .collect();+ assert_eq!(names, vec!["g_skill", "p_skill", "jan"], "got {names:?}");++ let _ = std::fs::remove_dir_all(&project);+ let _ = std::fs::remove_dir_all(&permanent);+ }++ #[test]+ fn read_raw_layered_shadows_then_falls_back() {+ let project = scratch("readp");+ let permanent = scratch("readg");+ write(&project, "shared", "project text").unwrap();+ write(&permanent, "shared", "permanent text").unwrap();+ write(&permanent, "only_global", "global text").unwrap();++ let roots = [project.as_path(), permanent.as_path()];+ assert!(read_raw_layered(&roots, "shared").unwrap().contains("project text"));+ assert!(read_raw_layered(&roots, "only_global").unwrap().contains("global text"));+ assert!(read_raw_layered(&roots, "missing").is_err());++ let _ = std::fs::remove_dir_all(&project);+ let _ = std::fs::remove_dir_all(&permanent);+ }}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rsindex e53d6a876..d4a456d6b 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs@@ -426,7 +426,7 @@ fn render_write_diff(prior: Option<&str>, content: &str) -> String {/// `skill_list` tool: catalog of `name — description` lines for ENABLED skills/// only (disabled skills must stay invisible to the model). Empty if none.fn skill_list(ctx: &ToolContext<'_>) -> String {- skills::catalog(ctx.store_root, ctx.enabled_skills)+ skills::catalog_layered(&ctx.skill_roots(), ctx.enabled_skills).iter().map(|m| {if m.description.is_empty() {@@ -449,7 +449,7 @@ fn skill_read(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {if !skills::is_enabled(ctx.enabled_skills, name) {return format!("ERROR: skill '{name}' not found");}- let raw = match skills::read_raw(ctx.store_root, name) {+ let raw = match skills::read_raw_layered(&ctx.skill_roots(), name) {Ok(raw) => raw,Err(e) => return e,};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.rsindex 2070b9191..6f554eaf5 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@@ -63,6 +63,12 @@ pub struct ImageContentPart {pub struct ToolContext<'a> {pub project_root: &'a Path,pub store_root: &'a Path,+ /// A project's co-located store whose `skills/` layer on top of `store_root`+ /// for discovery and `skill_read`, so the desktop/Cowork agent sees an+ /// attached folder's skills alongside the permanent ones (#8879). `None` on+ /// every surface with no folder attached. Skill *writes* and all memory ops+ /// still target `store_root`; only skill reads consult this overlay.+ pub skill_project_root: Option<&'a Path>,pub enabled_skills: &'a [String],pub allow_network: bool,/// When set, `write`/`edit` re-canonicalize the target and refuse a path@@ -141,6 +147,7 @@ impl std::fmt::Debug for ToolContext<'_> {f.debug_struct("ToolContext").field("project_root", &self.project_root).field("store_root", &self.store_root)+ .field("skill_project_root", &self.skill_project_root).field("enabled_skills", &self.enabled_skills).field("allow_network", &self.allow_network).field("confine_writes", &self.confine_writes)@@ -167,6 +174,7 @@ impl<'a> ToolContext<'a> {Self {project_root,store_root,+ skill_project_root: None,enabled_skills,allow_network: false,confine_writes: false,@@ -196,6 +204,22 @@ impl<'a> ToolContext<'a> {self}+ /// Overlay a project's co-located skill store on top of the permanent one.+ /// See [`Self::skill_project_root`].+ pub fn with_skill_project_root(mut self, root: &'a Path) -> Self {+ self.skill_project_root = Some(root);+ self+ }++ /// Skill stores in precedence order for discovery and `skill_read`: the+ /// project overlay (when attached) on top of the permanent store.+ pub fn skill_roots(&self) -> Vec<&Path> {+ match self.skill_project_root {+ Some(project) => vec![project, self.store_root],+ None => vec![self.store_root],+ }+ }+/// The shell env policy this context carries, for [`crate::tools::proc::spawn`].pub fn shell_env(&self) -> crate::tools::proc::ShellEnv<'a> {crate::tools::proc::ShellEnv {diff --git a/web-app/src/containers/SkillSelector.tsx b/web-app/src/containers/SkillSelector.tsxindex 80ec94123..e167fbea7 100644--- a/web-app/src/containers/SkillSelector.tsx+++ b/web-app/src/containers/SkillSelector.tsx@@ -76,7 +76,18 @@ export default function SkillSelector({ folder }: { folder: string | null }) {className="flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 hover:bg-accent"><div className="flex-1 min-w-0">- <div className="truncate text-sm font-medium">{s.name}</div>+ <div className="flex items-center gap-1.5 min-w-0">+ <span className="truncate text-sm font-medium">{s.name}</span>+ {scoped && s.origin && (+ <span className="shrink-0 rounded bg-muted px-1 text-[10px] leading-4 text-muted-foreground">+ {t(+ s.origin === 'project'+ ? 'common:skillOriginFolder'+ : 'common:skillOriginGlobal'+ )}+ </span>+ )}+ </div>{s.description && (<div className="truncate text-xs text-muted-foreground">{s.description}diff --git a/web-app/src/containers/__tests__/SkillSelector.test.tsx b/web-app/src/containers/__tests__/SkillSelector.test.tsxindex ba923b4e0..b5141e866 100644--- a/web-app/src/containers/__tests__/SkillSelector.test.tsx+++ b/web-app/src/containers/__tests__/SkillSelector.test.tsx@@ -74,4 +74,23 @@ describe('SkillSelector', () => {expect(setEnabled).toHaveBeenCalled()expect(screen.queryByText('common:skillsScopeGlobal')).toBeNull()})++ // #8879: with a folder attached the list is the union of global and folder+ // skills, and each row is labelled with the store it came from.+ it('labels each skill origin when a folder is attached', async () => {+ useSkills.mockReturnValue({+ skills: [+ { ...skill('git'), origin: 'store' },+ { ...skill('deploy'), origin: 'project' },+ ],+ enabled: [],+ setEnabled: vi.fn(),+ })+ render(<SkillSelector folder="/home/u/repo" />)+ await userEvent.click(await screen.findByRole('button'))+ expect(screen.getByText('git')).toBeInTheDocument()+ expect(screen.getByText('deploy')).toBeInTheDocument()+ expect(screen.getByText('common:skillOriginGlobal')).toBeInTheDocument()+ expect(screen.getByText('common:skillOriginFolder')).toBeInTheDocument()+ })})diff --git a/web-app/src/containers/dialogs/SkillsManagerDialog.tsx b/web-app/src/containers/dialogs/SkillsManagerDialog.tsxindex 593b4e1e1..e854f75fd 100644--- a/web-app/src/containers/dialogs/SkillsManagerDialog.tsx+++ b/web-app/src/containers/dialogs/SkillsManagerDialog.tsx@@ -135,11 +135,12 @@ export default function SkillsManagerDialog({<DialogContent className="max-w-3xl"><DialogHeader><DialogTitle>{t('common:skillsTitle')}</DialogTitle>- {/* Name the store being managed: the current session's folder, or the- global store every session reads when nothing is attached. */}+ {/* Name the stores being managed. With a folder attached the list is+ the union of its co-located skills and the global store (#8879);+ with nothing attached it is the global store every session reads. */}<p className="text-xs text-muted-foreground">{folder- ? t('common:skillsScopeProject', { folder })+ ? t('common:skillsScopeMerged', { folder }): t('common:skillsScopeGlobal')}</p></DialogHeader>@@ -185,7 +186,18 @@ export default function SkillsManagerDialog({><FileText size={14} className="shrink-0 text-muted-foreground" /><div className="flex-1 min-w-0">- <div className="truncate font-medium">{s.name}</div>+ <div className="flex items-center gap-1.5 min-w-0">+ <span className="truncate font-medium">{s.name}</span>+ {folder && (+ <span className="shrink-0 rounded bg-muted px-1 text-[10px] leading-4 text-muted-foreground">+ {t(+ s.origin === 'project'+ ? 'common:skillOriginFolder'+ : 'common:skillOriginGlobal'+ )}+ </span>+ )}+ </div>{s.description && (<div className="line-clamp-2 break-words text-xs text-muted-foreground">{s.description}diff --git a/web-app/src/hooks/useSkills.ts b/web-app/src/hooks/useSkills.tsindex 8e0e6d9ba..0e340693f 100644--- a/web-app/src/hooks/useSkills.ts+++ b/web-app/src/hooks/useSkills.ts@@ -9,6 +9,11 @@ import type { SkillMeta } from '@/lib/skillStore'export type { SkillMeta }export type HubSkill = { name: string; description: string }+/** Which store a listed skill came from. `project` shadows `store` on a name+ * collision, matching the agent's runtime precedence (#8879). */+export type SkillOrigin = 'store' | 'project'+export type ScopedSkill = SkillMeta & { origin: SkillOrigin }+// The `[skills].enabled` whitelist uses three shapes:// [] -> all skills enabled (scaffold default; backward compatible)// ['a','b'] -> only the named skills@@ -46,15 +51,18 @@ const useSkillsVersion = create<{ v: number; bump: () => void }>((set) => ({}))/**- * CRUD over the agent's skills. With a `folder`, the project's co-located- * store (`<folder>/.jan/agent/skills`); without one, the permanent store in- * the Jan data folder -- which is also what the Cowork agent's `skill_*`- * tools read, so the sidebar manager works with nothing attached. The+ * CRUD over the agent's skills. The permanent store in the Jan data folder is+ * always listed -- it is what the Cowork agent's `skill_*` tools read by+ * default -- and with a `folder` its co-located store+ * (`<folder>/.jan/agent/skills`) layers on top, a project skill shadowing a+ * same-named global one (#8879). Each returned skill carries its `origin` so+ * `read`/`write`/`remove` target the store it lives in; a brand-new skill lands+ * in the folder's store when one is attached, else the permanent store. The* `[skills].enabled` whitelist stays a project concern: with no folder it has* nowhere to live, so everything reads as enabled and `setEnabled` is a no-op.*/export function useSkills(folder: string | null) {- const [skills, setSkills] = useState<SkillMeta[]>([])+ const [skills, setSkills] = useState<ScopedSkill[]>([])// Enabled-skill whitelist from `[skills].enabled`; empty = all skills enabled.const [enabled, setEnabledState] = useState<string[]>([])const [loading, setLoading] = useState(false)@@ -63,24 +71,49 @@ export function useSkills(folder: string | null) {// Mirrors `enabled` so `setEnabled` can roll back to the last known value after// an await without depending on (and being recreated by) the state itself.const enabledRef = useRef<string[]>([])+ // name -> origin, so the CRUD callbacks route each skill to its own store+ // without depending on (and being recreated by) the `skills` state.+ const originRef = useRef<Map<string, SkillOrigin>>(new Map())- const scope = useMemo(+ // Where a NEW skill is written: the folder's store when attached, else global.+ const newScope = useMemo(() => (folder ? skillStore.projectScope(folder) : skillStore.storeScope),[folder])+ const scopeOf = useCallback(+ (name: string) => {+ const origin = originRef.current.get(name)+ if (origin === 'project' && folder) return skillStore.projectScope(folder)+ if (origin === 'store') return skillStore.storeScope+ return newScope+ },+ [folder, newScope]+ )const refresh = useCallback(async () => {setLoading(true)try {- const [list, en] = await Promise.all([- skillStore.listSkills(scope),+ const [storeList, projectList, en] = await Promise.all([+ skillStore.listSkills(skillStore.storeScope),+ folder+ ? skillStore.listSkills(skillStore.projectScope(folder))+ : Promise.resolve([]),// The whitelist lives in the project's agent.toml; the permanent// store has none, so everything it holds is enabled.folder? invoke<string[]>('agent_skill_enabled_get', { project: folder }): Promise.resolve([]),])+ // Folder skills layer on top: a project skill shadows a same-named global+ // one, matching the agent's runtime precedence (#8879).+ const merged = new Map<string, ScopedSkill>()+ for (const s of storeList) merged.set(s.name, { ...s, origin: 'store' })+ for (const s of projectList) merged.set(s.name, { ...s, origin: 'project' })+ const list = [...merged.values()].sort((a, b) =>+ a.name.localeCompare(b.name)+ )setSkills(list)+ originRef.current = new Map(list.map((s) => [s.name, s.origin]))setEnabledState(en)enabledRef.current = en} catch (e) {@@ -89,7 +122,7 @@ export function useSkills(folder: string | null) {} finally {setLoading(false)}- }, [folder, scope])+ }, [folder])// Persist the enabled whitelist (empty = all). Optimistic local update; on a// write failure, roll back so the UI never diverges from the on-disk config.@@ -122,24 +155,24 @@ export function useSkills(folder: string | null) {}, [refresh, version])const read = useCallback(- (name: string) => skillStore.readSkill(scope, name),- [scope]+ (name: string) => skillStore.readSkill(scopeOf(name), name),+ [scopeOf])const write = useCallback(async (name: string, content: string) => {- await skillStore.writeSkill(scope, name, content)+ await skillStore.writeSkill(scopeOf(name), name, content)bump()},- [scope, bump]+ [scopeOf, bump])const remove = useCallback(async (name: string) => {- await skillStore.deleteSkill(scope, name)+ await skillStore.deleteSkill(scopeOf(name), name)bump()},- [scope, bump]+ [scopeOf, bump])// Anthropic skill hub. `hubList` is project-independent; `hubImport` downloadsdiff --git a/web-app/src/lib/__tests__/agentTools.test.ts b/web-app/src/lib/__tests__/agentTools.test.tsindex 11cd38295..e1c3264d7 100644--- a/web-app/src/lib/__tests__/agentTools.test.ts+++ b/web-app/src/lib/__tests__/agentTools.test.ts@@ -274,6 +274,52 @@ describe('agentTools', () => {expect(vi.mocked(executeTool).mock.calls.at(-1)?.[7]).toBeUndefined()})+ // Cowork layers the attached folder's skills over the permanent store, so the+ // folder is forwarded as the plugin's skill-overlay `project` (arg 5) as well+ // as the read-only filesystem root (arg 8) -- #8879.+ it('forwards a skill-overlay project as the plugin project arg', async () => {+ vi.mocked(executeTool).mockResolvedValue({+ content: 'ok',+ isError: false,+ diff: null,+ } as never)+ const { executeAgentTool } = await import('../agentTools')+ await executeAgentTool(+ 'skill_list',+ {},+ 'sess-1',+ '/repo',+ 'session',+ true,+ true,+ '/repo'+ )+ expect(executeTool).toHaveBeenLastCalledWith(+ '/data',+ 'sess-1',+ 'skill_list',+ {},+ '/repo',+ undefined,+ true,+ '/repo',+ true,+ 'session'+ )+ })++ // Chat never passes a skill overlay, so its skills stay global-only.+ it('leaves the skill-overlay project undefined by default', async () => {+ vi.mocked(executeTool).mockResolvedValue({+ content: 'ok',+ isError: false,+ diff: null,+ } as never)+ const { executeAgentTool } = await import('../agentTools')+ await executeAgentTool('skill_list', {}, 'thread-1', '/home/u/repo')+ expect(vi.mocked(executeTool).mock.calls.at(-1)?.[4]).toBeUndefined()+ })+it('maps a gate refusal to an error rather than content', async () => {executeTool.mockResolvedValue({content: "tool 'write' needs user approval",diff --git a/web-app/src/lib/__tests__/coworkDispatch.test.ts b/web-app/src/lib/__tests__/coworkDispatch.test.tsindex 151dd370d..4b6f7ec3c 100644--- a/web-app/src/lib/__tests__/coworkDispatch.test.ts+++ b/web-app/src/lib/__tests__/coworkDispatch.test.ts@@ -53,7 +53,8 @@ describe('dispatchCoworkTool', () => {null,'session',true,- true+ true,+ null)})@@ -68,7 +69,8 @@ describe('dispatchCoworkTool', () => {null,'session',true,- true+ true,+ null)coworkConfig.networkEnabled = falsetry {@@ -80,7 +82,8 @@ describe('dispatchCoworkTool', () => {null,'session',false,- true+ true,+ null)} finally {coworkConfig.networkEnabled = true@@ -111,7 +114,10 @@ describe('dispatchCoworkTool', () => {expect(executeAgentTool).toHaveBeenCalled()})- it('passes the attached folder through', async () => {+ // The attached folder is passed twice: as the read-only filesystem root and+ // as the skill-overlay project (last arg), so the folder's skills reach the+ // agent on top of the permanent store (#8879).+ it('passes the attached folder through as both read root and skill overlay', async () => {await dispatchCoworkTool(call('grep'), ctx({ readOnlyFolder: '/repo' }))expect(executeAgentTool).toHaveBeenCalledWith('grep',@@ -120,7 +126,8 @@ describe('dispatchCoworkTool', () => {'/repo','session',true,- true+ true,+ '/repo')})diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.tsindex 89a5c339c..6386503c7 100644--- a/web-app/src/lib/agentTools.ts+++ b/web-app/src/lib/agentTools.ts@@ -260,7 +260,15 @@ export async function executeAgentTool(allowNetwork = false,/** Opt the attached folder into writes and edits in place (Cowork's shared* folder). Off by default, so chat's attachment stays read-only. */- projectWritable = false+ projectWritable = false,+ /**+ * A project folder whose co-located skills (`<folder>/.jan/agent/skills`)+ * layer on top of the permanent store for `skill_list`/`skill_read`, so an+ * attached folder's skills reach the agent alongside the global ones (#8879).+ * Cowork passes its attached folder; chat leaves it unset, keeping its skills+ * global-only. Memory and skill writes stay on the permanent store regardless.+ */+ skillProject?: string | null): Promise<AgentToolResult> {try {const dataFolder = await getServiceHub().app().getJanDataFolder()@@ -274,7 +282,7 @@ export async function executeAgentTool(threadId,toolName,args,- undefined,+ skillProject ?? undefined,undefined,allowNetwork,readOnlyProject ?? undefined,diff --git a/web-app/src/lib/coworkDispatch.ts b/web-app/src/lib/coworkDispatch.tsindex ad656df87..5cc801c9a 100644--- a/web-app/src/lib/coworkDispatch.ts+++ b/web-app/src/lib/coworkDispatch.ts@@ -151,6 +151,8 @@ export async function dispatchCoworkTool(// the next command; chat's shell stays network-closed regardless.// The attached folder is writable on this surface: Cowork's shared folder// takes writes and edits in place, unlike chat's read-only attachment.+ // The attached folder is also the skill-overlay project, so the folder's+ // own skills reach the agent on top of the permanent store (#8879).const result = await executeAgentTool(toolName,call.input,@@ -158,7 +160,8 @@ export async function dispatchCoworkTool(ctx.readOnlyFolder,'session',useCoworkConfig.getState().networkEnabled,- true+ true,+ ctx.readOnlyFolder)if (result.error) return { output: result.error, isError: true }return {diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex 33b6cdb65..9d8fcef82 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -66,6 +66,9 @@"skillsTitle": "Manage skills","skillsScopeProject": "Skills for {{folder}}","skillsScopeGlobal": "Global skills, available to every session",+ "skillsScopeMerged": "Skills for {{folder}}, plus the global skills every session shares",+ "skillOriginFolder": "folder",+ "skillOriginGlobal": "global","skillsEmpty": "No skills yet","skillsPickOrNew": "Select a skill to edit, or create a new one.","skillNew": "New skill",