Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(projects): let Edit project promote another folder to primary

vastsadd375d6b85f9
diff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.ts
index 666e4d925..32a511205 100644
--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts
+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts
@@ -289,20 +289,31 @@ export function registerWorkspaceIpc({
);
handle(
IPC.invoke.projectGroupUpdate,
- async (input: { groupId?: unknown; name?: unknown; folders?: unknown } = {}) => {
+ async (input: {
+ groupId?: unknown;
+ name?: unknown;
+ folders?: unknown;
+ primary?: unknown;
+ } = {}) => {
if (!host) throw new Error("host unavailable");
const groupId = typeof input.groupId === "string" ? input.groupId.trim() : "";
const name = typeof input.name === "string" ? input.name.trim() : "";
const folders = Array.isArray(input.folders)
? input.folders.filter((path): path is string => typeof path === "string")
: [];
+ const primary = typeof input.primary === "string" ? input.primary.trim() : "";
if (!groupId || !name || folders.length === 0) {
throw Object.assign(new Error("project group id, name and folders required"), {
errorCode: ErrorCodes.INVALID_ARGUMENT,
});
}
if (folders.every((path) => path.startsWith("remote-project:"))) {
- const result = await host.call("project.group.update", { groupId, name, folders });
+ const result = await host.call("project.group.update", {
+ groupId,
+ name,
+ folders,
+ ...(primary ? { primary } : {}),
+ });
void refreshProjectGroups(host);
return result;
}
@@ -319,10 +330,18 @@ export function registerWorkspaceIpc({
errorCode: ErrorCodes.INVALID_ARGUMENT,
});
}
+ // The promoted primary must be one of the folders this call keeps.
+ const safePrimary = primary ? resolve(primary) : "";
+ if (safePrimary && !safeFolders.includes(safePrimary)) {
+ throw Object.assign(new Error("project group primary must be one of its folders"), {
+ errorCode: ErrorCodes.INVALID_ARGUMENT,
+ });
+ }
const updated = await host.call("project.group.update", {
groupId,
name,
folders: safeFolders,
+ ...(safePrimary ? { primary: safePrimary } : {}),
});
void refreshProjectGroups(host);
return updated;
diff --git a/apps/desktop/src/components/ProjectEditDialog.tsx b/apps/desktop/src/components/ProjectEditDialog.tsx
index 5a418e532..3ed84f081 100644
--- a/apps/desktop/src/components/ProjectEditDialog.tsx
+++ b/apps/desktop/src/components/ProjectEditDialog.tsx
@@ -166,6 +166,13 @@ export function ProjectEditDialog({
}
};
+ // Promoting a folder only changes which selected root is primary; the host
+ // stores the primary root first, and the rows below follow that order.
+ const promoteFolder = (path: string) => {
+ if (loading || busy || group?.remote) return;
+ setPrimaryPath(path);
+ };
+
const submit = async () => {
const trimmedName = name.trim();
if (!group || loading || !trimmedName || busyRef.current) return;
@@ -175,7 +182,7 @@ export function ProjectEditDialog({
try {
const result = group.remote
? await api.renameProjectGroup(group.id, trimmedName)
- : await api.updateProjectGroup(group.id, trimmedName, folders);
+ : await api.updateProjectGroup(group.id, trimmedName, folders, primaryPath);
onSaved(result.group);
onClose();
} catch (error) {
@@ -186,6 +193,11 @@ export function ProjectEditDialog({
}
};
+ // The primary folder stays the first row, exactly as the host stores it.
+ const orderedFolders = [
+ primaryPath,
+ ...folders.filter((path) => !samePath(path, primaryPath)),
+ ];
const dialog = (
<div
className="overlay project-create-dialog-overlay"
@@ -279,7 +291,7 @@ export function ProjectEditDialog({
{!loading && folders.length > 0 ? (
<div className="project-create-dialog-folder-list" role="list">
- {folders.map((path) => {
+ {orderedFolders.map((path) => {
const primary = samePath(path, primaryPath);
const displayPath = group?.remote?.path ?? path;
return (
@@ -301,6 +313,18 @@ export function ProjectEditDialog({
{t("project.createPrimary")}
</span>
) : null}
+ {primary || group?.remote ? null : (
+ <TooltipButton
+ type="button"
+ className="project-create-folder-primary"
+ tooltip={t("project.editSetPrimary")}
+ ariaLabel={`${t("project.editSetPrimary")}: ${folderName(displayPath)}`}
+ disabled={loading || busy}
+ onClick={() => promoteFolder(path)}
+ >
+ <IconStar size={15} aria-hidden />
+ </TooltipButton>
+ )}
<TooltipButton
type="button"
className="project-create-folder-remove"
diff --git a/apps/desktop/src/components/Sidebar.tsx b/apps/desktop/src/components/Sidebar.tsx
index e44752f13..827ba753b 100644
--- a/apps/desktop/src/components/Sidebar.tsx
+++ b/apps/desktop/src/components/Sidebar.tsx
@@ -2630,7 +2630,17 @@ export function Sidebar({
<ProjectEditDialog
project={editProjectFor}
onClose={() => setEditProjectFor(null)}
- onSaved={(group) => editProjectEntry(editProjectFor, group.name)}
+ onSaved={(group) => {
+ editProjectEntry(editProjectFor, group.name);
+ // A promoted primary owns the group name from now on, so the entry
+ // that opens there later already carries it.
+ if (
+ normalizeProjectPath(editProjectFor.path) !==
+ normalizeProjectPath(group.primaryPath)
+ ) {
+ renameProject(group.primaryPath, group.name);
+ }
+ }}
onError={reportError}
/>
) : null}
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index be16a3e62..b6fa7423c 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -845,11 +845,19 @@ export const api = {
invoke<{ group: ProjectGroupRecord }>(IPC.invoke.projectGroupCreate, { name, folders }),
renameProjectGroup: (groupId: string, name: string) =>
invoke<{ group: ProjectGroupRecord }>(IPC.invoke.projectGroupRename, { groupId, name }),
- updateProjectGroup: (groupId: string, name: string, folders: string[]) =>
+ // `primary` names the folder that becomes the group's primary root; the host
+ // keeps the stored one when it is omitted.
+ updateProjectGroup: (
+ groupId: string,
+ name: string,
+ folders: string[],
+ primary?: string,
+ ) =>
invoke<{ group: ProjectGroupRecord }>(IPC.invoke.projectGroupUpdate, {
groupId,
name,
folders,
+ ...(primary ? { primary } : {}),
}),
getProjectGroupMemory: (groupId: string) =>
invoke<{ memory: ProjectMemory }>(IPC.invoke.projectGroupMemoryGet, { groupId }),
diff --git a/apps/desktop/src/pages/ProjectsPage.tsx b/apps/desktop/src/pages/ProjectsPage.tsx
index b8531dfc7..7821a2039 100644
--- a/apps/desktop/src/pages/ProjectsPage.tsx
+++ b/apps/desktop/src/pages/ProjectsPage.tsx
@@ -724,6 +724,14 @@ export function ProjectsPage() {
onClose={() => setEditProjectFor(null)}
onSaved={(group) => {
renameProject(group.primaryPath, group.name);
+ // Promoting another folder to primary moves the group's identity,
+ // while the row that is still open keeps the same display name.
+ if (
+ normalizeProjectPath(editProjectFor.path) !==
+ normalizeProjectPath(group.primaryPath)
+ ) {
+ renameProject(editProjectFor.path, group.name);
+ }
setDurableProjects((current) =>
current.map((item) =>
item.id === group.id || item.id === editProjectFor.groupId ? group : item,
diff --git a/apps/desktop/src/styles/project-create-dialog.css b/apps/desktop/src/styles/project-create-dialog.css
index cc43e2ad2..df1fb1516 100644
--- a/apps/desktop/src/styles/project-create-dialog.css
+++ b/apps/desktop/src/styles/project-create-dialog.css
@@ -397,6 +397,26 @@
color: var(--ds-error);
}
+/* Promotes one member folder to the group's primary root. */
+.project-create-folder-primary {
+ display: inline-flex;
+ width: 28px;
+ height: 28px;
+ flex: 0 0 auto;
+ align-items: center;
+ justify-content: center;
+ border-radius: var(--radius-sm);
+ color: var(--ds-text-muted);
+ transition:
+ background var(--motion-duration-fast) var(--motion-ease-out),
+ color var(--motion-duration-fast) var(--motion-ease-out);
+}
+
+.project-create-folder-primary:hover:not(:disabled) {
+ background: color-mix(in oklab, var(--ds-accent) 13%, transparent);
+ color: var(--ds-accent);
+}
+
.project-create-add-folder {
width: 100%;
min-height: 48px;
@@ -525,6 +545,7 @@
.project-create-dialog-location,
.project-create-folder-row,
.project-create-folder-remove,
+ .project-create-folder-primary,
.project-create-add-folder {
transition: none;
}
diff --git a/apps/desktop/test/project-edit.test.mjs b/apps/desktop/test/project-edit.test.mjs
index 8f7af5e54..8b7debabe 100644
--- a/apps/desktop/test/project-edit.test.mjs
+++ b/apps/desktop/test/project-edit.test.mjs
@@ -3,7 +3,18 @@ import { readFile } from "node:fs/promises";
import test from "node:test";
const read = (path) => readFile(new URL(path, import.meta.url), "utf8");
-const [sidebarSource, projectsSource, dialogSource, apiSource, protocolSource, hostSource, enSource, zhSource, trSource] =
+const [
+ sidebarSource,
+ projectsSource,
+ dialogSource,
+ apiSource,
+ protocolSource,
+ hostSource,
+ ipcSource,
+ enSource,
+ zhSource,
+ trSource,
+] =
await Promise.all([
read("../src/components/Sidebar.tsx"),
read("../src/pages/ProjectsPage.tsx"),
@@ -11,6 +22,7 @@ const [sidebarSource, projectsSource, dialogSource, apiSource, protocolSource, h
read("../src/lib/api.ts"),
read("../../../packages/shared/src/protocol.ts"),
read("../../../crates/host-core/src/rpc/mod.rs"),
+ read("../electron/main/ipc/workspace-ipc.ts"),
read("../../../packages/i18n/src/locales/en/index.ts"),
read("../../../packages/i18n/src/locales/zh-CN/index.ts"),
read("../../../packages/i18n/src/locales/tr/index.ts"),
@@ -29,7 +41,10 @@ test("project rows expose an edit action in both project surfaces", () => {
test("project edit dialog updates names and adjusts folder roots", () => {
assert.match(dialogSource, /export function ProjectEditDialog/);
assert.match(dialogSource, /listProjectGroups\(\)/);
- assert.match(dialogSource, /api\.updateProjectGroup\(group\.id, trimmedName, folders\)/);
+ assert.match(
+ dialogSource,
+ /api\.updateProjectGroup\(group\.id, trimmedName, folders, primaryPath\)/,
+ );
assert.match(dialogSource, /api\.pickProjectFolders\(\)/);
assert.match(dialogSource, /setFolders\(\(current\) =>[\s\S]*?current\.filter/);
assert.match(dialogSource, /busy \|\| primary/);
@@ -39,11 +54,34 @@ test("project edit dialog updates names and adjusts folder roots", () => {
assert.match(dialogSource, /event\.key === "Escape"/);
});
+test("project edit dialog promotes another folder to primary", () => {
+ // Promotion is one state change: the rows derive their order from it, and the
+ // dialog sends it as the group's primary root on save.
+ assert.match(dialogSource, /const promoteFolder = \(path: string\) => \{/);
+ assert.match(dialogSource, /setPrimaryPath\(path\)/);
+ assert.match(
+ dialogSource,
+ /const orderedFolders = \[[\s\S]*?folders\.filter\(\(path\) => !samePath\(path, primaryPath\)\)/,
+ );
+ assert.match(dialogSource, /\{orderedFolders\.map\(\(path\) => \{/);
+ assert.match(dialogSource, /project\.editSetPrimary/);
+ assert.match(dialogSource, /className="project-create-folder-primary"/);
+ // A remote project keeps its host-owned binding and never promotes.
+ assert.match(dialogSource, /\{primary \|\| group\?\.remote \? null : \(/);
+});
+
test("project group update is available through the host RPC and preload API", () => {
assert.match(protocolSource, /projectGroupUpdate:\s*"pi-desktop\/project-group\/update"/);
- assert.match(apiSource, /updateProjectGroup: \(groupId: string, name: string, folders: string\[\]\)/);
+ assert.match(
+ apiSource,
+ /updateProjectGroup: \([\s\S]*?groupId: string,[\s\S]*?name: string,[\s\S]*?folders: string\[\],[\s\S]*?primary\?: string,/,
+ );
+ assert.match(apiSource, /\.\.\.\(primary \? \{ primary \} : \{\}\)/);
assert.match(hostSource, /"project\.group\.update"/);
- assert.match(hostSource, /update_project_group\(group_id, name, &folders\)/);
+ assert.match(hostSource, /update_project_group\(group_id, name, &folders, primary\)/);
+ assert.match(hostSource, /params\.get\("primary"\)/);
+ assert.match(ipcSource, /primary\?: unknown;/);
+ assert.match(ipcSource, /\.\.\.\(safePrimary \? \{ primary: safePrimary \} : \{\}\)/);
});
for (const [locale, source] of [["en", enSource], ["zh-CN", zhSource], ["tr", trSource]]) {
@@ -56,6 +94,7 @@ for (const [locale, source] of [["en", enSource], ["zh-CN", zhSource], ["tr", tr
"editSaving",
"editCancel",
"editPrimaryLocked",
+ "editSetPrimary",
]) {
assert.match(source, new RegExp(`(?:\\b${key}|"${key}"):`));
}
diff --git a/crates/host-core/src/db/project_groups.rs b/crates/host-core/src/db/project_groups.rs
index 4d4e40017..0be9c6f74 100644
--- a/crates/host-core/src/db/project_groups.rs
+++ b/crates/host-core/src/db/project_groups.rs
@@ -328,11 +328,18 @@ impl Database {
Ok(group)
}
+ /// Edits a stored group's display name and ordered roots.
+ ///
+ /// `primary` selects which selected root becomes the primary root; the
+ /// stored primary is kept when it is `None`, and dropping it from `paths`
+ /// without naming a replacement is refused. The primary root always stays
+ /// first, so naming another root reorders the group around it.
pub fn update_project_group(
&self,
id: &str,
name: &str,
paths: &[String],
+ primary: Option<&str>,
) -> Result<ProjectGroupRecord> {
let name = name.trim();
if name.is_empty() || name.chars().count() > MAX_PROJECT_GROUP_NAME_CHARS {
@@ -342,13 +349,20 @@ impl Database {
return Err(anyhow!("project group not found"));
};
if current.remote.is_some() {
- if paths != [current.primary_path.clone()] {
+ let keeps_current_primary = primary.is_none_or(|path| path == current.primary_path);
+ if paths != [current.primary_path.clone()] || !keeps_current_primary {
return Err(anyhow!("remote project folder binding cannot be changed"));
}
return self.rename_project_group(&current.id, name);
}
- let primary = canonical_project_path(&current.primary_path)
+ let current_primary = canonical_project_path(&current.primary_path)
.ok_or_else(|| anyhow!("project group primary path is invalid"))?;
+ let requested_primary = primary
+ .map(|path| {
+ canonical_project_path(path)
+ .ok_or_else(|| anyhow!("project group primary path must not be blank"))
+ })
+ .transpose()?;
let mut selected = Vec::with_capacity(paths.len());
for raw in paths {
let path = canonical_project_path(raw)
@@ -366,9 +380,16 @@ impl Database {
}
selected.push(path);
}
- if !selected.iter().any(|path| path == &primary) {
- return Err(anyhow!("the primary folder cannot be removed"));
- }
+ let primary = match requested_primary {
+ Some(requested) if selected.iter().any(|path| path == &requested) => requested,
+ Some(requested) => {
+ return Err(anyhow!(
+ "the primary folder must be one of the group folders: {requested}"
+ ))
+ }
+ None if selected.iter().any(|path| path == &current_primary) => current_primary,
+ None => return Err(anyhow!("the primary folder cannot be removed")),
+ };
let mut ordered = vec![primary.clone()];
ordered.extend(selected.into_iter().filter(|path| path != &primary));
diff --git a/crates/host-core/src/db/tests.rs b/crates/host-core/src/db/tests.rs
index c4468c867..765e42b10 100644
--- a/crates/host-core/src/db/tests.rs
+++ b/crates/host-core/src/db/tests.rs
@@ -1400,6 +1400,7 @@ fn project_group_update_detaches_roots_with_chats_without_orphaning_them() {
primary.to_string_lossy().into(),
second.to_string_lossy().into(),
],
+ None,
)
.unwrap();
assert_eq!(updated.name, "Adjusted");
@@ -1426,6 +1427,7 @@ fn project_group_update_detaches_roots_with_chats_without_orphaning_them() {
&updated.id,
"Adjusted again",
&[second.to_string_lossy().into()],
+ None,
)
.unwrap_err()
.to_string()
@@ -1441,6 +1443,7 @@ fn project_group_update_detaches_roots_with_chats_without_orphaning_them() {
&updated.id,
"Adjusted again",
&[primary.to_string_lossy().into()],
+ None,
)
.expect("a root with chats can be detached from the group");
assert_eq!(detached.roots.len(), 1);
@@ -1460,6 +1463,114 @@ fn project_group_update_detaches_roots_with_chats_without_orphaning_them() {
);
}
+#[test]
+fn project_group_update_switches_the_primary_root() {
+ let dir = tempfile::tempdir().unwrap();
+ let primary = dir.path().join("primary");
+ let member = dir.path().join("member");
+ let other = dir.path().join("other");
+ std::fs::create_dir_all(&primary).unwrap();
+ std::fs::create_dir_all(&member).unwrap();
+ std::fs::create_dir_all(&other).unwrap();
+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
+ let group = db
+ .create_project_group(
+ "Switchable",
+ &[
+ primary.to_string_lossy().into(),
+ member.to_string_lossy().into(),
+ other.to_string_lossy().into(),
+ ],
+ )
+ .unwrap();
+ let canonical_primary = crate::db::canonical_project_path(&primary.to_string_lossy()).unwrap();
+ let canonical_member = crate::db::canonical_project_path(&member.to_string_lossy()).unwrap();
+ let canonical_other = crate::db::canonical_project_path(&other.to_string_lossy()).unwrap();
+ let all_folders = || {
+ vec![
+ primary.to_string_lossy().into_owned(),
+ member.to_string_lossy().into_owned(),
+ other.to_string_lossy().into_owned(),
+ ]
+ };
+
+ // Naming another selected folder promotes it and keeps it first.
+ let switched = db
+ .update_project_group(
+ &group.id,
+ "Switchable",
+ &all_folders(),
+ Some(&canonical_member),
+ )
+ .unwrap();
+ assert_eq!(switched.primary_path, canonical_member);
+ assert_eq!(
+ switched
+ .roots
+ .iter()
+ .map(|root| root.path.as_str())
+ .collect::<Vec<_>>(),
+ [
+ canonical_member.as_str(),
+ canonical_primary.as_str(),
+ canonical_other.as_str()
+ ]
+ );
+ assert_eq!(
+ switched
+ .roots
+ .iter()
+ .map(|root| root.position)
+ .collect::<Vec<_>>(),
+ [0, 1, 2]
+ );
+ // The former primary becomes an ordinary member root.
+ assert!(switched
+ .roots
+ .iter()
+ .skip(1)
+ .any(|root| root.path == canonical_primary));
+ // The switch survives reloading the stored record.
+ let reloaded = db
+ .list_project_groups()
+ .unwrap()
+ .into_iter()
+ .find(|candidate| candidate.id == group.id)
+ .unwrap();
+ assert_eq!(reloaded.primary_path, canonical_member);
+
+ // A primary outside the selected folders is refused.
+ assert!(db
+ .update_project_group(
+ &group.id,
+ "Switchable",
+ std::slice::from_ref(&canonical_primary),
+ Some(&canonical_member),
+ )
+ .unwrap_err()
+ .to_string()
+ .contains("must be one of the group folders"));
+ // Omitting the primary still refuses dropping the stored one.
+ assert!(db
+ .update_project_group(
+ &group.id,
+ "Switchable",
+ std::slice::from_ref(&canonical_primary),
+ None
+ )
+ .unwrap_err()
+ .to_string()
+ .contains("primary folder"));
+ // The refused calls leave the stored switch in place.
+ let unchanged = db
+ .list_project_groups()
+ .unwrap()
+ .into_iter()
+ .find(|candidate| candidate.id == group.id)
+ .unwrap();
+ assert_eq!(unchanged.primary_path, canonical_member);
+}
+
#[test]
fn remove_project_from_group_detaches_even_with_chats_and_may_move_primary() {
let dir = tempfile::tempdir().unwrap();
@@ -1559,6 +1670,7 @@ fn editing_a_legacy_project_with_an_extra_folder_upgrades_it_to_a_group() {
primary.to_string_lossy().into(),
extra.to_string_lossy().into(),
],
+ None,
)
.unwrap();
assert!(!upgraded.legacy);
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index a7ef7e477..76cf50788 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -1946,10 +1946,11 @@ async fn handle_request(
.filter_map(Value::as_str)
.map(str::to_string)
.collect::<Vec<_>>();
+ let primary = params.get("primary").and_then(Value::as_str);
let st = state.lock().await;
let group = st
.db
- .update_project_group(group_id, name, &folders)
+ .update_project_group(group_id, name, &folders, primary)
.map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
Ok(json!({ "group": group }))
}
@@ -5717,6 +5718,65 @@ mod tests {
assert_eq!(updated["group"]["roots"].as_array().unwrap().len(), 2);
}
+ #[tokio::test]
+ async fn project_group_update_rpc_switches_the_primary_folder() {
+ let data_dir = tempfile::tempdir().unwrap();
+ let primary = data_dir.path().join("primary");
+ let extra = data_dir.path().join("extra");
+ fs::create_dir_all(&primary).unwrap();
+ fs::create_dir_all(&extra).unwrap();
+ let mut app_state = AppState::open(data_dir.path()).unwrap();
+ app_state.handshook = true;
+ let state = Arc::new(Mutex::new(app_state));
+ let created = handle_request(
+ state.clone(),
+ "project.group.create",
+ json!({ "name": "Switchable", "folders": [primary, extra] }),
+ mpsc::unbounded_channel().0,
+ )
+ .await
+ .unwrap();
+ let group_id = created["group"]["id"].as_str().unwrap().to_string();
+ let primary_path = created["group"]["primaryPath"]
+ .as_str()
+ .unwrap()
+ .to_string();
+ let extra_path = created["group"]["roots"][1]["path"]
+ .as_str()
+ .unwrap()
+ .to_string();
+
+ let switched = handle_request(
+ state.clone(),
+ "project.group.update",
+ json!({
+ "groupId": group_id,
+ "name": "Switchable",
+ "folders": [primary_path, extra_path],
+ "primary": extra_path,
+ }),
+ mpsc::unbounded_channel().0,
+ )
+ .await
+ .expect("a member folder can be promoted to primary");
+ assert_eq!(switched["group"]["primaryPath"], json!(extra_path));
+ assert_eq!(switched["group"]["roots"][0]["path"], json!(extra_path));
+ assert_eq!(switched["group"]["roots"][1]["path"], json!(primary_path));
+
+ // The stored record keeps the promoted folder as primary.
+ let listed = handle_request(
+ state.clone(),
+ "project.groups.list",
+ json!({}),
+ mpsc::unbounded_channel().0,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ listed["groups"][0]["primaryPath"],
+ json!(switched["group"]["primaryPath"])
+ );
+ }
#[tokio::test]
async fn grouped_folder_with_chats_can_be_detached_and_deleted_separately() {
let data_dir = tempfile::tempdir().unwrap();
diff --git a/docs/adr/0249-chatgpt-style-logical-project-groups.md b/docs/adr/0249-chatgpt-style-logical-project-groups.md
index f56c5eeaf..f10d64c02 100644
--- a/docs/adr/0249-chatgpt-style-logical-project-groups.md
+++ b/docs/adr/0249-chatgpt-style-logical-project-groups.md
@@ -39,9 +39,10 @@ policy.
group membership never grants arbitrary external filesystem access.
6. The project overflow action is named **Edit project**. The editor can change
the group name and adjust its root list through the additive
- `project.group.update` capability. The primary root remains first and cannot
- be removed. An additional root can be detached even when it has chats; those
- chats remain available under the detached path as a standalone project.
+ `project.group.update` capability, which also promotes any registered root to
+ the primary root when the caller names it. The primary root remains first and
+ cannot be removed. An additional root can be detached even when it has chats;
+ those chats remain available under the detached path as a standalone project.
Future chats use that project's path-scoped context, while the group's shared
instructions and memory remain with the original group.
7. Group creation, editing, shared instruction editing, and shared memory editing
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 29f38a4e4..ee14880fc 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -93,8 +93,13 @@ type ProjectGroupRecord = {
`project-group/create` is additive and does not change the active workspace.
`project-group/list` returns one row per logical group; old path projects are
returned as `legacy` single-root groups. Group memory and instructions are
-shared by all sessions whose primary path belongs to the group. The primary
-path is the default builtin-tool workspace. The runtime advertises all registered
+shared by all sessions whose primary path belongs to the group. The first
+selected root is primary at creation; `project-group/update` may promote any
+other selected root by naming it as `primary`, and the host then stores that
+root first. The primary path is the default builtin-tool workspace. The runtime
+advertises all registered roots; an absolute path under an additional root is
+canonicalized and executed against that root, while arbitrary external paths
+still require the ordinary permission flow.
roots; an absolute path under an additional root is canonicalized and executed
against that root, while arbitrary external paths still require the ordinary
permission flow.
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index ac7bf3986..1016141ea 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -245,12 +245,14 @@ type ToolBudgetHealth = {
without changing the active workspace. A non-legacy root cannot belong to a
second group.
- `project.group.rename({ groupId, name })` — persists the group display name.
-- `project.group.update({ groupId, name, folders })` — edits the group name and
- ordered roots. The primary root must remain first; duplicate roots are
- removed, roots owned by another non-legacy group are rejected, and a root
- with existing chats cannot be detached. Removed roots are retained as
- suppressed historical paths rather than reappearing as standalone legacy
- groups.
+- `project.group.update({ groupId, name, folders, primary? })` — edits the group
+ name and ordered roots. The stored primary root must remain first; naming a
+ `primary` promotes that selected root and reorders the roots around it, while
+ omitting it keeps the stored primary and refuses dropping it. Duplicate roots
+ are removed, a `primary` outside `folders` is rejected, roots owned by
+ another non-legacy group are rejected, and a root with existing chats cannot
+ be detached. Removed roots are retained as suppressed historical paths rather
+ than reappearing as standalone legacy groups.
- `project.group.memory.get/set({ groupId, entries })` — reads or normalizes
shared group memory using the existing 32 KiB entry limit.
- `project.group.instructions.get/set({ groupId, content })` — reads or stores
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index 247c4835d..d8e59935f 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -545,10 +545,14 @@ visually distinct from list content.
the workspace list with a softly filled Add folder action; the field does not
repeat its label as placeholder text and uses the shared field well plus the
accent-tinted focus ring, not an outline stroke. Edit project reuses the same
- surface, loads the host-owned group, allows the name and non-primary folders
- to be adjusted, keeps Primary first and non-removable, and rejects removal of
- a folder that still owns chats. Background session or run-status updates
- must preserve unsaved name and folder edits in the open editor. The source selector offers This computer and
+ surface, loads the host-owned group, allows the name and folders to be
+ adjusted, keeps the Primary folder first and non-removable, and rejects
+ removal of a folder that still owns chats. Every other folder row carries a
+ Set as Primary action that promotes it: the row moves to the top, the Primary
+ tag moves with it, and the host stores the promoted folder as the group's
+ primary root on save. A remote project keeps its host-owned binding and shows
+ no promotion action. Background session or run-status updates
+ must preserve unsaved name, folder, and primary edits in the open editor.
Git repository as equal filled tiles without strokes (D297); the active source
uses a deeper tile, not a selected border. A repository URL reuses the clone
rules of ADR 0247 and its checkout becomes the primary root of the same group.
diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.md
index e6cc5f930..9b65c6f23 100644
--- a/docs/spec/04-ux/09-interaction-patterns.md
+++ b/docs/spec/04-ux/09-interaction-patterns.md
@@ -250,8 +250,10 @@ may be retained while exactly one workspace supplies the visible shell context.
- **Edit project** — the project overflow menu in the sidebar and Project
archive opens the same editor for the selected logical project. The editor
trims and persists a 1–80 Unicode-code-point group name and lists every
- registered folder. The Primary folder stays first and cannot be removed;
- additional folders can be added through the native multi-selection picker or
+ registered folder. The Primary folder stays first and cannot be removed, and
+ every other folder row offers a Set as Primary action that promotes it to the
+ top and makes it the group's primary root on save; additional folders can be
+ added through the native multi-selection picker or
removed individually. Saving updates group membership without rewriting path
identities, workspace identity, session ownership, transcripts, or on-disk
folders. Removing an additional folder with chats detaches it as a standalone
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 4acf62da9..e9d68a16e 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -4052,30 +4052,39 @@ window; opening a normal panel afterward must still work.
#### E2E-048b: Edit a logical project name and folder roots
- **Preconditions**: One retained logical project is visible in the sidebar and
- in Settings → Project archive; it has a primary folder and one additional
- folder without chats.
+ in Settings → Project archive; it has a primary folder, one additional folder
+ promoted to primary during the scenario, and one other additional folder
+ without chats.
- **Steps**: 1) Open the project's overflow menu in the sidebar and choose
- Edit project. 2) Change the name, remove the additional folder, and add it
- again with the native folder picker. 3) Confirm the Primary row cannot be
- removed. 4) Save and inspect the sidebar row, Project archive roots, and
- active workspace. 5) Restart the app and inspect the group again.
+ Edit project. 2) Change the name, use the extra folder's Set as Primary
+ action, and confirm that row moves to the top with the Primary tag while the
+ former primary becomes an ordinary row. 3) Remove the other additional folder
+ and add it again with the native folder picker. 4) Confirm the Primary row
+ cannot be removed. 5) Save and inspect the sidebar row, Project archive
+ roots, and active workspace. 6) Restart the app and inspect the group again.
- **Background-update regression**: Open Edit project from Settings, change the
- name and remove the additional folder, then complete a background task before
- saving. Both draft edits must remain visible and save together. The isolated
- rendered test is `node scripts/e2e-project-edit.mjs`; it uses real page/store
- wiring with a controlled host IPC boundary and does not prove disk persistence.
+ name, promote another folder to primary, and remove the additional folder,
+ then complete a background task before saving. Every draft edit must remain
+ visible and save together. The isolated rendered test is
+ `node scripts/e2e-project-edit.mjs`; it uses real page/store wiring with a
+ controlled host IPC boundary and does not prove disk persistence.
- **Expected**: Both project menus offer Edit project. The editor keeps focus
- contained, trims the name, limits it to 80 Unicode characters, preserves the
+ contained, trims the name, limits it to 80 Unicode characters, keeps the
Primary folder as the first row, and updates the root count without removing
- another row. Saving persists one logical group with the adjusted roots; the
- name survives restart, while normalized paths, workspace identity, sessions,
- and on-disk folders remain unchanged.
+ another row. Promoting a member folder makes it the first row and the stored
+ primary root, so the project opens there afterwards; a folder outside the
+ saved roots is never accepted as primary, and a remote project keeps its
+ host-owned binding unchanged. Saving persists one logical group with the
+ adjusted roots; the name and the promoted primary folder survive restart,
+ while the group's sessions, transcripts, and on-disk folders remain
+ unchanged.
- **Specs linked**: `04-ux/01-ui-ia.md`, `04-ux/08-component-spec.md`,
`04-ux/09-interaction-patterns.md`
- **Acceptance**: D (workspace identity), F (local presentation persistence)
- **Milestone**: M5
- **Status**: Unit-covered (`project-edit.test.mjs`,
- `sidebar-preferences.test.mjs`); rendered scenario Draft
+ `sidebar-preferences.test.mjs`); rendered scenario Draft, with primary
+ promotion covered by `node scripts/e2e-project-edit.mjs`
#### E2E-048c: Detach a project folder with chats and delete it
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 85137a730..78220f856 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -1700,6 +1700,7 @@ sklm: {
"editSaving": "Speichern…",
"editCancel": "Abbrechen",
"editPrimaryLocked": "Der primäre Ordner kann nicht entfernt werden",
+ "editSetPrimary": "Als primären Ordner festlegen",
"editInstructions": "Projektanweisungen",
"instructionsSaved": "Projektanweisungen gespeichert",
"editMemory": "Projektspeicher",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 8ade92675..8238fbc10 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -1720,6 +1720,7 @@ sklm: {
editSaving: "Saving…",
editCancel: "Cancel",
editPrimaryLocked: "The Primary folder cannot be removed",
+ editSetPrimary: "Set as Primary folder",
editInstructions: "Project instructions",
instructionsSaved: "Project instructions saved",
editMemory: "Project memory",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 73c526602..80dd0b702 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -1700,6 +1700,7 @@ sklm: {
"editSaving": "Guardando…",
"editCancel": "Cancelar",
"editPrimaryLocked": "La carpeta principal no se puede eliminar",
+ "editSetPrimary": "Establecer como carpeta principal",
"editInstructions": "Instrucciones del proyecto",
"instructionsSaved": "Instrucciones del proyecto guardadas",
"editMemory": "Memoria del proyecto",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index f4eb7a242..fabce2df0 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -1700,6 +1700,7 @@ sklm: {
"editSaving": "Enregistrement…",
"editCancel": "Annuler",
"editPrimaryLocked": "Le dossier principal ne peut pas être supprimé",
+ "editSetPrimary": "Définir comme dossier principal",
"editInstructions": "Instructions du projet",
"instructionsSaved": "Instructions du projet enregistrées",
"editMemory": "Mémoire du projet",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index e360db8c5..e2f33e611 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -1716,6 +1716,7 @@ sklm: {
editSaving: "저장 중…",
editCancel: "취소",
editPrimaryLocked: "기본 폴더는 삭제할 수 없습니다",
+ editSetPrimary: "기본 폴더로 지정",
editInstructions: "프로젝트 지침",
instructionsSaved: "프로젝트 지침 저장됨",
editMemory: "프로젝트 메모리",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 394d2afa2..e7866b214 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -1670,6 +1670,7 @@ export const ptBR = {
editSaving: "Salvando…",
editCancel: "Cancelar",
editPrimaryLocked: "A pasta Principal não pode ser removida",
+ editSetPrimary: "Definir como pasta principal",
editInstructions: "Instruções do projeto",
instructionsSaved: "Instruções do projeto salvas",
editMemory: "Memória do projeto",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index e7b145fb9..44caad155 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -1710,6 +1710,7 @@ sklm: {
editSaving: "Kaydediliyor…",
editCancel: "İptal",
editPrimaryLocked: "Birincil klasör kaldırılamaz",
+ editSetPrimary: "Birincil klasör olarak ayarla",
editInstructions: "Proje talimatları",
instructionsSaved: "Proje talimatları kaydedildi",
editMemory: "Proje belleği",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index da26b5f4f..7499f5a22 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -1695,6 +1695,7 @@ sklm: {
editSaving: "保存中…",
editCancel: "取消",
editPrimaryLocked: "主要文件夹不能移除",
+ editSetPrimary: "设为主要文件夹",
editInstructions: "项目指令",
instructionsSaved: "项目指令已保存",
editMemory: "项目记忆",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index f4c234d20..45f146c73 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -1695,6 +1695,7 @@ sklm: {
editSaving: "儲存中…",
editCancel: "取消",
editPrimaryLocked: "主要資料夾不能移除",
+ editSetPrimary: "設為主要資料夾",
editInstructions: "專案指示",
instructionsSaved: "專案指示已儲存",
editMemory: "專案記憶",
diff --git a/scripts/e2e-project-edit.mjs b/scripts/e2e-project-edit.mjs
index 64f66d443..835c91b6f 100644
--- a/scripts/e2e-project-edit.mjs
+++ b/scripts/e2e-project-edit.mjs
@@ -45,10 +45,14 @@ const {app,BrowserWindow,ipcMain}=require('electron');
const path=require('node:path');
app.setPath('userData',path.join(__dirname,'profile'));
let group={id:'website',name:'Website',primaryPath:'/fixture/website',lastOpenedAt:1,pinned:false,
- roots:[{path:'/fixture/website',name:'website',position:0},{path:'/fixture/assets',name:'assets',position:1}]};
+ roots:[{path:'/fixture/website',name:'website',position:0},{path:'/fixture/assets',name:'assets',position:1},{path:'/fixture/docs',name:'docs',position:2}]};
ipcMain.handle('pi-desktop/project-group/list',()=>({ok:true,data:{groups:[group]}}));
ipcMain.handle('pi-desktop/project-group/update',(_event,input)=>{
- group={...group,name:input.name,roots:input.folders.map((p,i)=>({path:p,name:path.basename(p),position:i}))};
+ // Mirrors the host: an explicit primary is promoted and stays the first root.
+ const primary=input.primary??input.folders[0];
+ const ordered=[primary,...input.folders.filter(p=>p!==primary)];
+ group={...group,name:input.name,primaryPath:primary,
+ roots:ordered.map((p,i)=>({path:p,name:path.basename(p),position:i}))};
return {ok:true,data:{group}};
});
app.whenReady().then(async()=>{
diff --git a/scripts/e2e/project-edit.tsx b/scripts/e2e/project-edit.tsx
index ffac5f0f7..6dc609540 100644
--- a/scripts/e2e/project-edit.tsx
+++ b/scripts/e2e/project-edit.tsx
@@ -78,23 +78,40 @@ async function openEditor() {
globalThis.projectEditProbe = async () => {
await openEditor();
inputName("Website redesign");
- await click("Remove folder: assets");
- await until(() => !document.querySelector('[aria-label="Remove folder: assets"]'), "removed extra folder");
+ // Promoting a member folder makes it the primary row and the saved root order.
+ await click("Set as Primary folder: assets");
+ const primaryRow = await until(() => {
+ const rows = [...document.querySelectorAll<HTMLElement>(".project-create-folder-row")];
+ const first = rows[0];
+ return first?.classList.contains("is-primary") && first.textContent?.includes("assets")
+ ? first
+ : null;
+ }, "promoted primary row");
+ const promoted = Boolean(primaryRow) &&
+ !document.querySelector('[aria-label="Set as Primary folder: assets"]') &&
+ Boolean(document.querySelector('[aria-label="Set as Primary folder: website"]'));
+ await click("Remove folder: docs");
+ await until(() => !document.querySelector('[aria-label="Remove folder: docs"]'), "removed extra folder");
completeTask();
// Let the update traverse the real ProjectsPage and any resulting IPC loads.
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
const input = document.querySelector<HTMLInputElement>("#project-edit-name")!;
const preserved = input.value === "Website redesign";
- const foldersPreserved = !document.querySelector('[aria-label="Remove folder: assets"]');
- if (!preserved || !foldersPreserved) {
- return { ok: false, name: input.value, preserved, foldersPreserved };
+ const foldersPreserved = !document.querySelector('[aria-label="Remove folder: docs"]');
+ const primaryPreserved = document
+ .querySelector(".project-create-folder-row")
+ ?.textContent?.includes("assets") === true;
+ if (!preserved || !foldersPreserved || !primaryPreserved || !promoted) {
+ return { ok: false, name: input.value, preserved, foldersPreserved, primaryPreserved, promoted };
}
await click("Save changes");
await until(() => !document.querySelector("#project-edit-name"), "saved editor closed");
await until(() => document.body.textContent?.includes("Website redesign"), "updated project visible");
const { groups } = await api.listProjectGroups();
const saved = groups[0]?.name === "Website redesign" &&
- groups[0]?.primaryPath === "/fixture/website" &&
- groups[0]?.roots.length === 1 && groups[0]?.roots[0]?.path === "/fixture/website";
- return { ok: saved, preserved, foldersPreserved, saved };
+ groups[0]?.primaryPath === "/fixture/assets" &&
+ groups[0]?.roots.length === 2 &&
+ groups[0]?.roots[0]?.path === "/fixture/assets" &&
+ groups[0]?.roots[1]?.path === "/fixture/website";
+ return { ok: saved, preserved, foldersPreserved, primaryPreserved, promoted, saved };
};