Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Add Projects: logical conversation grouping + per-project workspace scope

wyt6171abef2a9a
diff --git a/CLAUDE.md b/CLAUDE.md
index 2cd138e4..350f2d44 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -121,10 +121,12 @@ PC/data/
│ ├── memory/MEMORY.md + USER.md
│ ├── agents/<aid>/ Custom agent: agent.json (spec) + meta/ (metacognition) + skills/ (self-evolved SkillStore)
│ ├── skills/<sid>/ Custom skills (System A, scanned by SkillLoader)
+ │ ├── projects/_index.json + projects/<pid>/ Logical groups of conversations + reserved per-project asset slot (KB/permissions later)
│ └── config/{preferences,component-enabled}.json
└── local/ 🔒 Machine-private domain (never synced)
├── config/ auth-profiles / permissions / reflection-state / web-search-cache
├── search/ Derived indexes (contexts / chats / skill_chats / agent_chats)
+ ├── workspace.json Scoped workspace selection: `{default, projects:{<pid>:…}}` (legacy flat shape auto-promoted on first read)
├── file_cache/<hash>/ Lazy cache for all files (see features/file_indexer.ts)
└── tool-results/<sid>/ Spill for oversized tool outputs
```
@@ -153,6 +155,8 @@ PC/data/
session jsonl files land at `<uid>/cloud/sessions/<session_id>.jsonl` — they are **two independent files** from the UI message list.
+**Project membership** is an index-level field on the conv record (`Conversation.project_id`), **not** part of any path or session_id. cid stays globally unique; `<cid>.jsonl` / `groupChatDir` / `chat_attachments/<cid>/` / `session_id = <uid>-gconv-<cid>` paths are independent of project membership. Workspace resolution is the only place project membership has effect: `getWorkspacePath(uid, projectId?)` (sync) picks the project-scoped selection from `<uid>/local/workspace.json::projects[pid]` when set, falling through to `default.selectedPath` then `DEFAULT_USER_WORKSPACE`. group_chat resolves cid → projectId once at the top of `runTurn` and threads `projectId` through `ChatOptions` → `LocalToolsOpts` / `FileToolsOpts` / `ImageGenToolOpts`. **Do not** re-read the conv index per tool call to look up project membership — the resolved value travels with the turn.
+
**Security invariant**: `session_id` must be `<uid>-<kind>-<tail>`, with the uid in the first segment, and `<kind>` ∈ `gconv | gmember | skill | agent | extract-img | reflect | memory-extract | anon | cli` (`sub` / `organizer` / `conv` are legacy kinds; new code does not generate them, but `migrate-session-ids` preserves these older files). `session-store.ts::sessionFileFor()` enforces this with hard assertions to prevent cross-uid leakage. **Do not** encode brand names (`orkas-` / `aiteam-` / any app name) into session_id — we hit the renaming-breaks-history pitfall once, the startup `migrateLegacySessionIds(uid)` strips legacy prefixes once, and new code never adds them again. Adding a new kind requires extending this table. The `cli` kind has no `sessions/*.jsonl` (CLI dispatches do not run through core-agent); the id exists purely to give per-run records a stable, kind-tagged identifier.
**Skill injection policy**: edit conversations + group-chat commander = no filtering (inject all); group-chat agent worker = filter by `agent.skill_list` three-state (see §6).
@@ -334,6 +338,8 @@ The renderer evaluates `<script>`-loaded files where `module` is undefined, so t
- Add `window.orkas.*` in the renderer without adding a handler in `ipc/index.ts`.
- Bypass `util/locks.ts` / `util/path-sandbox.isPathAllowed` / `features/file_indexer.ts`.
- Add eager pre-processing (extract / preview / chunking) to `chat_attachments.uploadAttachment`.
+- Treat `<uid>/local/workspace.json` as a flat `{selectedPath, recentPaths}` after the projects scope upgrade — the file is now `{default, projects:{<pid>:…}, updatedAt}`. Always go through `getWorkspacePath(uid, projectId?)` / `setWorkspacePath` / `resetWorkspacePath`; reading the JSON directly skips legacy-shape promotion + project-scope fallback.
+- Encode `project_id` into a path / cid / session_id segment. Project membership is an index-level field on the conv record only — see §5.
**Timeouts / locks**:
- Add a "total wall-clock timeout" to LLM calls (`timeout: N` / `setTimeout→abort`). The single application-layer watchdog is `client.ts::streamChatWithModel`'s `idleTimeout=600s` (true idle); the SDK 1h limit is backstopped by `sdk-timeout-patch.ts`; group-chat infinite-loop protection is `bus.ts::MAX_WORKER_TURNS=100` (**turns, do not change to a timeout**).
diff --git a/src/main/features/chats.ts b/src/main/features/chats.ts
index d63654d5..a3cfe9ab 100644
--- a/src/main/features/chats.ts
+++ b/src/main/features/chats.ts
@@ -51,6 +51,12 @@ export interface Conversation {
* agents in the group have their own per-(conv,agent) session ids derived
* via state.buildGmemberSessionId. */
session_id: string;
+ /** Optional project membership. Frozen at create time; not mutable after
+ * creation. Empty / absent → conversation lives outside any project (the
+ * default sidebar group). The project itself is just metadata —
+ * `<cid>.jsonl`, `groupChatDir`, `chat_attachments`, and `session_id`
+ * paths stay verbatim, so cid uniqueness + §5 isolation are unaffected. */
+ project_id?: string;
created_at: string;
updated_at: string;
/** Derived from group_chat state.json at read time; never persisted on
@@ -153,10 +159,14 @@ export interface CreateConversationOptions {
agentId?: string;
skillId?: string;
title?: string;
+ /** Optional project membership. Caller (IPC layer) is responsible for
+ * validating the projectId exists for this user — chats.ts persists it
+ * verbatim. */
+ projectId?: string;
}
export async function createConversation(userId: string, {
- kind = 'normal', agentId = '', skillId = '', title = '',
+ kind = 'normal', agentId = '', skillId = '', title = '', projectId = '',
}: CreateConversationOptions = {}): Promise<Conversation> {
const cid = genConversationId();
const conv: Conversation = {
@@ -166,6 +176,7 @@ export async function createConversation(userId: string, {
agent_id: agentId || '',
skill_id: skillId || '',
session_id: buildGconvSessionId(userId, cid),
+ ...(projectId ? { project_id: projectId } : {}),
created_at: nowIso(),
updated_at: nowIso(),
};
@@ -174,7 +185,7 @@ export async function createConversation(userId: string, {
await saveConversations(userId, items);
// Touch jsonl so subsequent reads don't 404.
await fsp.writeFile(path.join(ensureUserDir(userId), `${cid}.jsonl`), '', { flag: 'a' });
- log.info(`created user=${userId} cid=${cid} kind=${kind} agent=${agentId || '-'} skill=${skillId || '-'}`);
+ log.info(`created user=${userId} cid=${cid} kind=${kind} agent=${agentId || '-'} skill=${skillId || '-'} project=${projectId || '-'}`);
return conv;
}
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index 2f833355..2c1c2c4b 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -722,6 +722,17 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// there's no migration story.
const { getConversationWorkspacePath } = await import('./conv_workspace');
const workingDir = await getConversationWorkspacePath(uid, cid);
+ // Project membership is decided at conv create time and frozen, so we
+ // can resolve it once per turn and thread it through to every workspace
+ // consumer below (CLI cwd fallback, streamChatWithModel, etc.) without
+ // re-reading the conv index per tool call.
+ let turnProjectId: string | undefined;
+ try {
+ const { getConversation } = await import('../chats');
+ const _conv = await getConversation(uid, cid);
+ const _pid = (_conv as any)?.project_id;
+ if (typeof _pid === 'string' && _pid) turnProjectId = _pid;
+ } catch { /* default scope */ }
// First-turn replay: if the persistent session jsonl doesn't exist yet,
// prepend a `<group-chat-history>` block built from the visibility slice
@@ -881,7 +892,7 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// `write_file` tool; CLI agents have their own product-side
// conventions and don't need that scoping. Override here:
const userWorkspace = await import('../user_workspace');
- const wsRoot = userWorkspace.getWorkspacePath(uid);
+ const wsRoot = userWorkspace.getWorkspacePath(uid, turnProjectId);
// Coding agents (claude / codex) honour the per-conversation
// `coding_project_dir` when set so the CLI runs inside the user's
// actual project; non-coding CLIs always use the workspace. The
@@ -952,6 +963,7 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
agentName: 'orkas_chat',
...(actor.kind === 'agent' ? { agentId: actor.id } : {}),
cid,
+ ...(turnProjectId ? { projectId: turnProjectId } : {}),
onFileWritten,
hasProducedPath,
cacheRetention: 'short',
diff --git a/src/main/features/group_chat/conv_workspace.ts b/src/main/features/group_chat/conv_workspace.ts
index d2be45f9..2b5d06bc 100644
--- a/src/main/features/group_chat/conv_workspace.ts
+++ b/src/main/features/group_chat/conv_workspace.ts
@@ -163,31 +163,37 @@ function uniquifySlug(workspaceRoot: string, slug: string): string {
* never produced anything.
*/
export async function getConversationWorkspacePath(uid: string, cid: string): Promise<string> {
- const root = getWorkspacePath(uid);
-
- // Fast path: state already has a workspace_dir baked in.
- const cur = await readState(uid, cid);
- if (cur.workspace_dir) {
- return path.join(root, cur.workspace_dir);
- }
-
- // No workspace_dir yet. Decide one.
- // Legacy convs (created before this feature shipped) keep using the root
- // workspace verbatim — we detect them by absence of a conversation record:
- // if the conv index has nothing for cid, the bus is operating on a phantom
- // and we don't want to spawn a directory off it. In practice every active
- // bus path runs after `chats.createConversation`, so this branch is rare.
+ // Resolve the conv's project membership ONCE so workspace resolution
+ // picks up the project-scoped selection (per CLAUDE.md projects feature).
+ // For convs without a project this is a no-op (projectId stays undefined).
+ let projectId: string | undefined;
let title = '';
try {
const conv = await getConversation(uid, cid);
- if (conv) title = conv.title || '';
- else {
+ if (conv) {
+ title = conv.title || '';
+ const pid = (conv as any).project_id;
+ if (typeof pid === 'string' && pid) projectId = pid;
+ } else {
+ // Legacy convs (created before this feature shipped) keep using the root
+ // workspace verbatim — we detect them by absence of a conversation record:
+ // if the conv index has nothing for cid, the bus is operating on a phantom
+ // and we don't want to spawn a directory off it. In practice every active
+ // bus path runs after `chats.createConversation`, so this branch is rare.
log.warn(`no conv record for cid=${cid} — falling back to root workspace`);
- return root;
+ return getWorkspacePath(uid);
}
} catch (err) {
log.warn(`getConversation failed cid=${cid}: ${(err as Error).message} — falling back to root`);
- return root;
+ return getWorkspacePath(uid);
+ }
+
+ const root = getWorkspacePath(uid, projectId);
+
+ // Fast path: state already has a workspace_dir baked in.
+ const cur = await readState(uid, cid);
+ if (cur.workspace_dir) {
+ return path.join(root, cur.workspace_dir);
}
let slug = slugifyConvTitle(title);
diff --git a/src/main/features/projects.ts b/src/main/features/projects.ts
new file mode 100644
index 00000000..7a08f74f
--- /dev/null
+++ b/src/main/features/projects.ts
@@ -0,0 +1,225 @@
+/**
+ * Projects — logical groups of conversations + a scoped workspace.
+ *
+ * A project is a thin index-only construct: just `{project_id, name, created_at,
+ * updated_at}`. Conversation membership is a `project_id` field on the conv
+ * index entry (`features/chats.ts::Conversation`), not a path component —
+ * `<cid>.jsonl` / `groupChatDir` / `session_id = <uid>-gconv-<cid>` stay verbatim
+ * (CLAUDE.md §5 isolation invariant).
+ *
+ * Storage: `<uid>/cloud/projects/_index.json` (cloud-synced; the project record
+ * is logical and small). Per-project workspace selection lives in
+ * `<uid>/local/workspace.json::projects[pid]` since absolute paths are
+ * machine-specific (CLAUDE.md §4 sync-domain split).
+ *
+ * Future per-project assets (knowledge base, access permissions) will land
+ * under `<uid>/cloud/projects/<pid>/` — `paths.projectDir` reserves the slot
+ * but no writes happen yet.
+ */
+
+import * as fs from 'node:fs';
+import * as fsp from 'node:fs/promises';
+import * as path from 'node:path';
+
+import { userProjectsDir, userProjectsIndexFile } from '../paths';
+import { nowIso, readJson, writeJson } from '../storage';
+import { createLogger } from '../logger';
+import * as chats from './chats';
+import { readState } from './group_chat/state';
+import { purgeProjectWorkspace } from './user_workspace';
+
+const log = createLogger('projects');
+
+export interface Project {
+ project_id: string;
+ name: string;
+ created_at: string;
+ updated_at: string;
+}
+
+/** UI-extended project record: index entry + derived counts. */
+export interface ProjectWithStats extends Project {
+ conv_count: number;
+}
+
+// ── id helper ─────────────────────────────────────────────────────────────
+
+function genProjectId(): string {
+ // 8-hex; collision-safe enough for per-user project counts.
+ return 'p_' + Math.floor(Math.random() * 0xffffffff).toString(16).padStart(8, '0');
+}
+
+// ── index IO ──────────────────────────────────────────────────────────────
+
+function ensureProjectsDir(uid: string): string {
+ const d = userProjectsDir(uid);
+ fs.mkdirSync(d, { recursive: true });
+ return d;
+}
+
+async function readIndex(uid: string): Promise<Project[]> {
+ ensureProjectsDir(uid);
+ const f = userProjectsIndexFile(uid);
+ if (!fs.existsSync(f)) return [];
+ const data: any = await readJson(f);
+ if (Array.isArray(data)) return data as Project[];
+ if (data && Array.isArray(data.items)) return data.items as Project[];
+ return [];
+}
+
+async function writeIndex(uid: string, items: Project[]): Promise<void> {
+ await writeJson(userProjectsIndexFile(uid), items);
+}
+
+// ── Validation ────────────────────────────────────────────────────────────
+
+const NAME_MAX_LEN = 60;
+
+/** Trim + length cap. Returns null if the input is unusable. */
+function normName(raw: unknown): string | null {
+ if (typeof raw !== 'string') return null;
+ const s = raw.trim();
+ if (!s) return null;
+ if (s.length > NAME_MAX_LEN) return s.slice(0, NAME_MAX_LEN);
+ return s;
+}
+
+function isDuplicateName(items: Project[], name: string, excludePid?: string): boolean {
+ const lower = name.toLocaleLowerCase();
+ for (const p of items) {
+ if (excludePid && p.project_id === excludePid) continue;
+ if ((p.name || '').toLocaleLowerCase() === lower) return true;
+ }
+ return false;
+}
+
+// ── Public API ────────────────────────────────────────────────────────────
+
+/** List projects with derived `conv_count`. Reads chats index once and groups. */
+export async function listProjects(uid: string): Promise<ProjectWithStats[]> {
+ const projects = await readIndex(uid);
+ if (!projects.length) return [];
+ const convs = await chats.listConversations(uid).catch(() => []);
+ const counts = new Map<string, number>();
+ for (const c of convs) {
+ const pid = (c as any).project_id;
+ if (!pid) continue;
+ counts.set(pid, (counts.get(pid) || 0) + 1);
+ }
+ return projects.map((p) => ({ ...p, conv_count: counts.get(p.project_id) || 0 }));
+}
+
+/** Resolve a single project by id (no stats). */
+export async function getProject(uid: string, projectId: string): Promise<Project | null> {
+ const items = await readIndex(uid);
+ return items.find((p) => p.project_id === projectId) || null;
+}
+
+export type ProjectError = 'name_empty' | 'name_dup' | 'not_found' | 'has_running_conv';
+
+export async function createProject(
+ uid: string,
+ rawName: string,
+): Promise<{ ok: true; project: Project } | { ok: false; error: ProjectError }> {
+ const name = normName(rawName);
+ if (!name) return { ok: false, error: 'name_empty' };
+ const items = await readIndex(uid);
+ if (isDuplicateName(items, name)) return { ok: false, error: 'name_dup' };
+ const now = nowIso();
+ const project: Project = {
+ project_id: genProjectId(),
+ name,
+ created_at: now,
+ updated_at: now,
+ };
+ items.unshift(project);
+ await writeIndex(uid, items);
+ log.info(`created user=${uid} pid=${project.project_id} name="${name}"`);
+ return { ok: true, project };
+}
+
+export async function renameProject(
+ uid: string,
+ projectId: string,
+ rawName: string,
+): Promise<{ ok: true; project: Project } | { ok: false; error: ProjectError }> {
+ const name = normName(rawName);
+ if (!name) return { ok: false, error: 'name_empty' };
+ const items = await readIndex(uid);
+ const i = items.findIndex((p) => p.project_id === projectId);
+ if (i < 0) return { ok: false, error: 'not_found' };
+ if (isDuplicateName(items, name, projectId)) return { ok: false, error: 'name_dup' };
+ if (items[i].name === name) {
+ return { ok: true, project: items[i] }; // no-op
+ }
+ items[i] = { ...items[i], name, updated_at: nowIso() };
+ await writeIndex(uid, items);
+ log.info(`renamed user=${uid} pid=${projectId} name="${name}"`);
+ return { ok: true, project: items[i] };
+}
+
+/** Cascade-delete: every conversation under this project is dropped (full
+ * per-conv cascade — `<cid>.jsonl` / sessions / attachments / search idx /
+ * group dir / cli sessions), then the project record itself.
+ *
+ * Aborts upfront if any conv is currently `running` (state.json::status). The
+ * user must stop the in-flight turn first; we do not silently abort. */
+export async function deleteProject(
+ uid: string,
+ projectId: string,
+): Promise<{ ok: true; deleted_convs: number } | { ok: false; error: ProjectError }> {
+ const items = await readIndex(uid);
+ const i = items.findIndex((p) => p.project_id === projectId);
+ if (i < 0) return { ok: false, error: 'not_found' };
+
+ const allConvs = await chats.listConversations(uid).catch(() => []);
+ const owned = allConvs.filter((c) => (c as any).project_id === projectId);
+
+ // Running-conv guard: refuse if any conv has a live turn.
+ for (const c of owned) {
+ try {
+ const s = await readState(uid, c.conversation_id);
+ if (s.status === 'running') {
+ log.info(`refused delete user=${uid} pid=${projectId} reason=running cid=${c.conversation_id}`);
+ return { ok: false, error: 'has_running_conv' };
+ }
+ } catch { /* missing state file = idle */ }
+ }
+
+ let deletedConvs = 0;
+ for (const c of owned) {
+ try {
+ if (await chats.deleteConversation(uid, c.conversation_id)) deletedConvs++;
+ } catch (err) {
+ log.warn(`cascade del user=${uid} pid=${projectId} cid=${c.conversation_id}: ${(err as Error).message}`);
+ }
+ }
+
+ // Drop the project record itself.
+ items.splice(i, 1);
+ await writeIndex(uid, items);
+
+ // Drop the per-project workspace selection (machine-private; no cascade
+ // needed beyond removing the dangling pid → path entry).
+ try { purgeProjectWorkspace(uid, projectId); }
+ catch (err) { log.warn(`purge project ws user=${uid} pid=${projectId}: ${(err as Error).message}`); }
+
+ // Clean up the (currently-empty) per-project asset dir if it exists.
+ try {
+ const d = path.join(userProjectsDir(uid), projectId);
+ if (fs.existsSync(d)) await fsp.rm(d, { recursive: true, force: true });
+ } catch (err) {
+ log.warn(`drop project dir user=${uid} pid=${projectId}: ${(err as Error).message}`);
+ }
+
+ log.info(`deleted user=${uid} pid=${projectId} convs=${deletedConvs}`);
+ return { ok: true, deleted_convs: deletedConvs };
+}
+
+/** True iff the given pid is a known project for this user. Used by
+ * conversations.create to validate the projectId before persisting. */
+export async function projectExists(uid: string, projectId: string): Promise<boolean> {
+ if (!projectId) return false;
+ const items = await readIndex(uid);
+ return items.some((p) => p.project_id === projectId);
+}
diff --git a/src/main/features/user_workspace.ts b/src/main/features/user_workspace.ts
index 5579c729..7de3ac57 100644
--- a/src/main/features/user_workspace.ts
+++ b/src/main/features/user_workspace.ts
@@ -1,15 +1,37 @@
/**
- * User Workspace — manages the user-facing working directory.
+ * User Workspace — manages the user-facing working directory(s).
*
* Each user can select a local directory as their "workspace" where agent
* output, intermediate products, and final deliverables are stored. If no
* directory has been chosen, the default `userWorkSpace/` folder (created at
* startup by paths.ensureLayout) is used.
*
- * The per-user selection is persisted in a JSON file under
- * `data/user_workspaces/<user_id>.json` so it survives restarts. The
- * Electron dialog for folder selection is triggered from IPC; this module
- * owns the config read/write + validation logic.
+ * **Scoped selection** (per CLAUDE.md §4 sync-domain split):
+ * - The default scope (no project) keeps using the existing
+ * `<uid>/local/workspace.json` config.
+ * - Each project optionally pins its own workspace; conversations under a
+ * project share that scope. Effective resolution:
+ * conv.project_id → projects[pid]?.selectedPath
+ * ?? default.selectedPath
+ * ?? DEFAULT_USER_WORKSPACE
+ *
+ * The on-disk file goes from a flat
+ * `{ selectedPath, recentPaths, updatedAt }`
+ * to a scoped object
+ * `{ default: {selectedPath, recentPaths}, projects: {<pid>: {...}}, updatedAt }`
+ * — `_normaliseConfig` migrates the legacy shape on first read (no
+ * schema_version field; absence of `default` key is the migration signal).
+ *
+ * **Resolver shape**: `getWorkspacePath(uid, projectId?)` is **synchronous**.
+ * Callers that have a cid (file-tools, group_chat bus, etc.) thread the
+ * `project_id` through their opts pipeline rather than re-reading the conv
+ * index per tool call — group_chat resolves the projectId once at the top
+ * of `runTurn` and passes it down. IPC handlers that take `{cid?}` from the
+ * renderer perform the cid → projectId lookup at the IPC boundary (async
+ * there is fine — single hop) before calling the sync resolver.
+ *
+ * The Electron dialog for folder selection is triggered from IPC; this
+ * module owns the config read/write + validation logic.
*/
import * as fs from 'node:fs';
@@ -20,42 +42,76 @@ import { DEFAULT_USER_WORKSPACE, userWorkspaceConfigFile } from '../paths';
import { createLogger } from '../logger';
import { t } from '../i18n';
import { pruneOrphans } from './file_indexer';
+import { getConversation } from './chats';
const log = createLogger('user-workspace');
// ── Config persistence ──────────────────────────────────────────────────
-/** Shape of the per-user workspace config file. */
-interface WorkspaceConfig {
- /** Absolute path to the chosen directory (or empty → use default). */
+/** A single workspace selection entry — used for both the default scope and
+ * per-project scopes. `selectedPath` empty means "fall back to next level"
+ * (project → default → DEFAULT_USER_WORKSPACE). */
+interface ScopeEntry {
selectedPath: string;
- /** ISO timestamp of last change. */
+ recentPaths: string[];
+}
+
+interface WorkspaceConfig {
+ default: ScopeEntry;
+ projects: Record<string, ScopeEntry>;
updatedAt: string;
- /** Recently used workspace paths (most recent first, excludes current & default). */
- recentPaths?: string[];
}
-// "Which folder did you pick" — stored in the user's local (non-synced) domain
-// at `<uid>/local/workspace.json`. Absolute paths are host-specific so this
-// must never leave the machine.
function configPath(userId: string): string {
return userWorkspaceConfigFile(userId);
}
const MAX_RECENT = 5;
+const EMPTY_ENTRY: ScopeEntry = { selectedPath: '', recentPaths: [] };
+
+function _normaliseEntry(raw: any): ScopeEntry {
+ if (!raw || typeof raw !== 'object') return { ...EMPTY_ENTRY };
+ return {
+ selectedPath: typeof raw.selectedPath === 'string' ? raw.selectedPath : '',
+ recentPaths: Array.isArray(raw.recentPaths)
+ ? raw.recentPaths.filter((p: unknown) => typeof p === 'string')
+ : [],
+ };
+}
+
+/** Promote legacy flat `{selectedPath, recentPaths}` → scoped shape. */
+function _normaliseConfig(raw: any): WorkspaceConfig {
+ if (!raw || typeof raw !== 'object') {
+ return { default: { ...EMPTY_ENTRY }, projects: {}, updatedAt: '' };
+ }
+ if (raw.default && typeof raw.default === 'object') {
+ const projects: Record<string, ScopeEntry> = {};
+ if (raw.projects && typeof raw.projects === 'object') {
+ for (const [pid, entry] of Object.entries(raw.projects)) {
+ if (typeof pid === 'string') projects[pid] = _normaliseEntry(entry);
+ }
+ }
+ return {
+ default: _normaliseEntry(raw.default),
+ projects,
+ updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : '',
+ };
+ }
+ // Legacy flat shape — promote into `default`.
+ return {
+ default: _normaliseEntry(raw),
+ projects: {},
+ updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : '',
+ };
+}
function readConfig(userId: string): WorkspaceConfig {
const p = configPath(userId);
try {
const raw = fs.readFileSync(p, 'utf-8');
- const obj = JSON.parse(raw);
- return {
- selectedPath: typeof obj.selectedPath === 'string' ? obj.selectedPath : '',
- updatedAt: typeof obj.updatedAt === 'string' ? obj.updatedAt : '',
- recentPaths: Array.isArray(obj.recentPaths) ? obj.recentPaths.filter((p: unknown) => typeof p === 'string') : [],
- };
+ return _normaliseConfig(JSON.parse(raw));
} catch {
- return { selectedPath: '', updatedAt: '', recentPaths: [] };
+ return { default: { ...EMPTY_ENTRY }, projects: {}, updatedAt: '' };
}
}
@@ -67,96 +123,152 @@ function writeConfig(userId: string, cfg: WorkspaceConfig): void {
fs.renameSync(tmp, p);
}
-// ── Public API ──────────────────────────────────────────────────────────
+// ── Scope helpers ────────────────────────────────────────────────────────
-/**
- * Return the effective workspace path for a user. Falls back to the
- * default directory if nothing was selected or the selected path no longer
- * exists.
- */
-export function getWorkspacePath(userId: string): string {
- const cfg = readConfig(userId);
- if (cfg.selectedPath) {
+function _readEntry(cfg: WorkspaceConfig, projectId?: string): ScopeEntry {
+ if (projectId) {
+ return cfg.projects[projectId] || { ...EMPTY_ENTRY };
+ }
+ return cfg.default;
+}
+
+function _writeEntry(cfg: WorkspaceConfig, projectId: string | undefined, entry: ScopeEntry): WorkspaceConfig {
+ if (projectId) {
+ return {
+ ...cfg,
+ projects: { ...cfg.projects, [projectId]: entry },
+ updatedAt: new Date().toISOString(),
+ };
+ }
+ return { ...cfg, default: entry, updatedAt: new Date().toISOString() };
+}
+
+/** Effective path for a given scope: project's selection (if any) → default's
+ * selection (if any) → DEFAULT_USER_WORKSPACE. Validates each step exists
+ * on disk; vanished selections fall through. */
+function _effectivePath(cfg: WorkspaceConfig, projectId?: string): string {
+ if (projectId) {
+ const entry = cfg.projects[projectId];
+ if (entry?.selectedPath) {
+ try {
+ if (fs.statSync(entry.selectedPath).isDirectory()) return entry.selectedPath;
+ } catch {
+ log.warn('project workspace path missing — falling back to default', {
+ projectId, path: entry.selectedPath,
+ });
+ }
+ }
+ }
+ if (cfg.default.selectedPath) {
try {
- const stat = fs.statSync(cfg.selectedPath);
- if (stat.isDirectory()) return cfg.selectedPath;
+ if (fs.statSync(cfg.default.selectedPath).isDirectory()) return cfg.default.selectedPath;
} catch {
- // selected path is gone — fall through to default
- log.warn('selected workspace path no longer exists, falling back to default', {
- userId,
- path: cfg.selectedPath,
+ log.warn('default workspace path missing — using DEFAULT_USER_WORKSPACE', {
+ path: cfg.default.selectedPath,
});
}
}
return DEFAULT_USER_WORKSPACE;
}
+// ── Public API ──────────────────────────────────────────────────────────
+
+/**
+ * Synchronous resolver. `projectId` is optional — when omitted the default
+ * scope is used. Callers with a cid in scope should resolve cid → project_id
+ * once via `chats.getConversation` (async) and pass `projectId` through
+ * their downstream opts (group_chat does this at the top of runTurn,
+ * threading through ChatOptions / LocalToolsOpts / FileToolsOpts).
+ */
+export function getWorkspacePath(userId: string, projectId?: string): string {
+ const cfg = readConfig(userId);
+ return _effectivePath(cfg, projectId);
+}
+
/**
- * Persist a user-chosen workspace path. The directory must exist.
- * Returns `{ ok: true, path }` or `{ ok: false, error }`.
+ * Async helper that does the cid → project_id lookup before calling the
+ * sync resolver. IPC handlers that take `{cid?}` from the renderer use
+ * this; main-side feature code that already knows the projectId should
+ * call `getWorkspacePath` directly.
+ */
+export async function resolveProjectIdForCid(userId: string, cid?: string): Promise<string | undefined> {
+ if (!cid) return undefined;
+ try {
+ const conv = await getConversation(userId, cid);
+ const pid = (conv as any)?.project_id;
+ return typeof pid === 'string' && pid ? pid : undefined;
+ } catch (err) {
+ log.warn(`resolveProjectIdForCid cid=${cid}: ${(err as Error).message}`);
+ return undefined;
+ }
+}
+
+/**
+ * Persist a user-chosen workspace path for a given scope. The directory
+ * must exist. Returns `{ ok: true, path }` or `{ ok: false, error }`.
*/
export function setWorkspacePath(
userId: string,
dirPath: string,
+ projectId?: string,
): { ok: true; path: string } | { ok: false; error: string } {
const resolved = path.resolve(dirPath);
try {
const stat = fs.statSync(resolved);
- if (!stat.isDirectory()) {
- return { ok: false, error: t('errors.path_not_dir') };
- }
+ if (!stat.isDirectory()) return { ok: false, error: t('errors.path_not_dir') };
} catch {
return { ok: false, error: t('errors.dir_not_exists') };
}
- // Track the old path in recents (if it's not the default)
- const oldCfg = readConfig(userId);
- const recents = (oldCfg.recentPaths || []).slice();
- if (oldCfg.selectedPath && oldCfg.selectedPath !== resolved) {
- // Remove if already in recents, then prepend
- const idx = recents.indexOf(oldCfg.selectedPath);
+ const cfg = readConfig(userId);
+ const oldEntry = _readEntry(cfg, projectId);
+
+ const recents = (oldEntry.recentPaths || []).slice();
+ if (oldEntry.selectedPath && oldEntry.selectedPath !== resolved) {
+ const idx = recents.indexOf(oldEntry.selectedPath);
if (idx !== -1) recents.splice(idx, 1);
- recents.unshift(oldCfg.selectedPath);
+ recents.unshift(oldEntry.selectedPath);
}
- // Also remove the new path from recents if present
const newIdx = recents.indexOf(resolved);
if (newIdx !== -1) recents.splice(newIdx, 1);
- writeConfig(userId, {
+ const next = _writeEntry(cfg, projectId, {
selectedPath: resolved,
- updatedAt: new Date().toISOString(),
recentPaths: recents.slice(0, MAX_RECENT),
});
- log.info('workspace path updated', { userId, path: resolved });
+ writeConfig(userId, next);
+ log.info('workspace path updated', { userId, projectId: projectId || '(default)', path: resolved });
_sweepFileCacheForWorkspace(userId, resolved);
return { ok: true, path: resolved };
}
/**
- * Reset to the default workspace directory.
+ * Reset the given scope's selection. After reset, the effective path falls
+ * through to the parent scope (project → default → DEFAULT_USER_WORKSPACE).
*/
-export function resetWorkspacePath(userId: string): { ok: true; path: string } {
- const oldCfg = readConfig(userId);
- const recents = (oldCfg.recentPaths || []).slice();
- // Track old selection in recents if non-default
- if (oldCfg.selectedPath) {
- const idx = recents.indexOf(oldCfg.selectedPath);
+export function resetWorkspacePath(userId: string, projectId?: string): { ok: true; path: string } {
+ const cfg = readConfig(userId);
+ const oldEntry = _readEntry(cfg, projectId);
+
+ const recents = (oldEntry.recentPaths || []).slice();
+ if (oldEntry.selectedPath) {
+ const idx = recents.indexOf(oldEntry.selectedPath);
if (idx !== -1) recents.splice(idx, 1);
- recents.unshift(oldCfg.selectedPath);
+ recents.unshift(oldEntry.selectedPath);
}
- writeConfig(userId, {
+
+ const next = _writeEntry(cfg, projectId, {
selectedPath: '',
- updatedAt: new Date().toISOString(),
recentPaths: recents.slice(0, MAX_RECENT),
});
- log.info('workspace path reset to default', { userId });
- _sweepFileCacheForWorkspace(userId, DEFAULT_USER_WORKSPACE);
- return { ok: true, path: DEFAULT_USER_WORKSPACE };
+ writeConfig(userId, next);
+
+ const effective = _effectivePath(next, projectId);
+ log.info('workspace path reset', { userId, projectId: projectId || '(default)', effective });
+ _sweepFileCacheForWorkspace(userId, effective);
+ return { ok: true, path: effective };
}
-/** Workspace switched — drop file_cache entries whose source lives outside
- * the new workspace. Fire-and-forget; cache pruning failure must not
- * fail the user-visible "switch workspace" action. */
function _sweepFileCacheForWorkspace(userId: string, workspacePath: string): void {
pruneOrphans(userId, { workspacePath })
.then((r) => {
@@ -170,24 +282,34 @@ function _sweepFileCacheForWorkspace(userId: string, workspacePath: string): voi
}
/**
- * Return full workspace info for rendering the dropdown:
- * current effective path, default path, and recent paths (validated).
+ * Return full workspace info for rendering the dropdown. `scope` tells the
+ * UI which bucket the chip is acting on so the chip tooltip can show
+ * context.
*/
-export function getWorkspaceInfo(userId: string): {
+export function getWorkspaceInfo(userId: string, projectId?: string): {
currentPath: string;
defaultPath: string;
isDefault: boolean;
recentPaths: string[];
+ scope: 'default' | 'project';
+ projectId?: string;
} {
const cfg = readConfig(userId);
- const currentPath = getWorkspacePath(userId);
- const isDefault = !cfg.selectedPath || currentPath === DEFAULT_USER_WORKSPACE;
- // Filter recents: only keep directories that still exist and aren't current/default
- const recentPaths = (cfg.recentPaths || []).filter(p => {
+ const entry = _readEntry(cfg, projectId);
+ const currentPath = _effectivePath(cfg, projectId);
+ const isDefault = !entry.selectedPath;
+ const recentPaths = (entry.recentPaths || []).filter((p) => {
if (p === currentPath || p === DEFAULT_USER_WORKSPACE) return false;
try { return fs.statSync(p).isDirectory(); } catch { return false; }
});
- return { currentPath, defaultPath: DEFAULT_USER_WORKSPACE, isDefault, recentPaths };
+ return {
+ currentPath,
+ defaultPath: DEFAULT_USER_WORKSPACE,
+ isDefault,
+ recentPaths,
+ scope: projectId ? 'project' : 'default',
+ ...(projectId ? { projectId } : {}),
+ };
}
/**
@@ -205,34 +327,42 @@ export async function selectDirectory(): Promise<string | null> {
}
/**
- * Sweep the active workspace root, removing any empty top-level
- * subdirectory. Existing empty per-conversation slug dirs (legacy from
- * before bash's cold-path rmdir-if-empty was added in `local-tools.ts`,
- * or any future tool that mkdir'd then produced nothing) get cleaned up
- * on every boot. Best-effort: any rmdir failure (non-empty / EACCES /
- * concurrent in-flight bash) is silently swallowed.
+ * Sweep every workspace root the user has selected (default + each
+ * per-project), removing any empty top-level subdirectory. Existing empty
+ * per-conversation slug dirs (legacy from before bash's cold-path
+ * rmdir-if-empty was added in `local-tools.ts`, or any future tool that
+ * mkdir'd then produced nothing) get cleaned up on every boot. Best-effort:
+ * any rmdir failure (non-empty / EACCES / concurrent in-flight bash) is
+ * silently swallowed.
*
- * Only the immediate top level of the workspace is scanned; deeper
- * empty subdirs are the user's own scaffolding and out of scope.
+ * Only the immediate top level of each workspace is scanned; deeper empty
+ * subdirs are the user's own scaffolding and out of scope.
*/
export function sweepEmptyConvDirs(userId: string): { swept: number } {
- const root = getWorkspacePath(userId);
+ const cfg = readConfig(userId);
+ const roots = new Set<string>();
+ roots.add(_effectivePath(cfg, undefined));
+ for (const pid of Object.keys(cfg.projects)) {
+ roots.add(_effectivePath(cfg, pid));
+ }
let swept = 0;
- let entries: string[];
- try { entries = fs.readdirSync(root); }
- catch { return { swept: 0 }; }
- for (const name of entries) {
- if (name.startsWith('.')) continue; // .DS_Store, .git, etc.
- const sub = path.join(root, name);
- try {
- const st = fs.statSync(sub);
- if (!st.isDirectory()) continue;
- if (fs.readdirSync(sub).length !== 0) continue;
- fs.rmdirSync(sub);
- swept++;
- } catch { /* best-effort */ }
+ for (const root of roots) {
+ let entries: string[];
+ try { entries = fs.readdirSync(root); }
+ catch { continue; }
+ for (const name of entries) {
+ if (name.startsWith('.')) continue; // .DS_Store, .git, etc.
+ const sub = path.join(root, name);
+ try {
+ const st = fs.statSync(sub);
+ if (!st.isDirectory()) continue;
+ if (fs.readdirSync(sub).length !== 0) continue;
+ fs.rmdirSync(sub);
+ swept++;
+ } catch { /* best-effort */ }
+ }
}
- if (swept > 0) log.info('swept empty workspace subdirs', { userId, swept, root });
+ if (swept > 0) log.info('swept empty workspace subdirs', { userId, swept, roots: Array.from(roots) });
return { swept };
}
@@ -243,8 +373,9 @@ export function sweepEmptyConvDirs(userId: string): { swept: number } {
*/
export async function openWorkspaceInFileManager(
userId: string,
+ projectId?: string,
): Promise<{ ok: true; path: string } | { ok: false; error: string }> {
- const target = getWorkspacePath(userId);
+ const target = getWorkspacePath(userId, projectId);
try {
const stat = fs.statSync(target);
if (!stat.isDirectory()) return { ok: false, error: t('errors.target_not_dir') };
@@ -258,3 +389,15 @@ export async function openWorkspaceInFileManager(
}
return { ok: true, path: target };
}
+
+/** Drop a project's per-project workspace entry from this user's
+ * workspace.json. Called by `projects.deleteProject` cascade so deleting a
+ * project doesn't leave a dangling pid → path entry on disk. */
+export function purgeProjectWorkspace(userId: string, projectId: string): void {
+ const cfg = readConfig(userId);
+ if (!cfg.projects[projectId]) return;
+ const next: WorkspaceConfig = { ...cfg, projects: { ...cfg.projects }, updatedAt: new Date().toISOString() };
+ delete next.projects[projectId];
+ try { writeConfig(userId, next); }
+ catch (err) { log.warn(`purge project ws user=${userId} pid=${projectId}: ${(err as Error).message}`); }
+}
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts
index aca6d26c..64af0a10 100644
--- a/src/main/ipc/index.ts
+++ b/src/main/ipc/index.ts
@@ -18,6 +18,7 @@ import { ipcMain, dialog, BrowserWindow, type WebContents } from 'electron';
import * as users from '../features/users';
import * as chats from '../features/chats';
+import * as projects from '../features/projects';
import * as groupChat from '../features/group_chat';
import type { GroupEvent } from '../features/group_chat/bus';
import * as agents from '../features/agents';
@@ -58,6 +59,23 @@ type StreamHandler = (
signal: AbortSignal,
) => AsyncGenerator<any, void, unknown>;
+// Resolve the workspace scope hint a renderer payload carries. cid is
+// authoritative (conv.project_id is the truth, so a cid uniquely picks a
+// project); projectId is the fallback for commander-tab clicks where no cid
+// exists yet. Returns `undefined` for default scope.
+async function _resolveWorkspaceScope(
+ userId: string,
+ payload: any,
+): Promise<string | undefined> {
+ if (payload && typeof payload.cid === 'string' && payload.cid && safeId(payload.cid)) {
+ return await userWorkspace.resolveProjectIdForCid(userId, payload.cid);
+ }
+ if (payload && typeof payload.projectId === 'string' && payload.projectId && safeId(payload.projectId)) {
+ return payload.projectId;
+ }
+ return undefined;
+}
+
// ── Invoke handlers ──────────────────────────────────────────────────────
// Contract: `(payload, { userId, sender }) => result` where result is
// merged into a `{ ok: true, ...result }` response. Throw to signal error.
@@ -93,8 +111,22 @@ const invokeHandlers: Record<string, InvokeHandler> = {
};
},
- 'conversations.create': async ({ title = '' } = {}, ctx) => {
- const conv = await chats.createConversation(ctx.userId, { kind: 'normal', title });
+ 'conversations.create': async ({ title = '', projectId = '' } = {}, ctx) => {
+ // Validate the projectId belongs to this user before persisting it on
+ // the conv record. Unknown / invalid projectIds are dropped silently
+ // (the conv lands without project membership) — the renderer should
+ // not be able to put a conv into a project the backend doesn't know
+ // about, but a stale / since-deleted pid coming from the commander chip
+ // shouldn't fail the create either.
+ let validProjectId = '';
+ if (projectId && typeof projectId === 'string' && safeId(projectId)) {
+ if (await projects.projectExists(ctx.userId, projectId)) validProjectId = projectId;
+ }
+ const conv = await chats.createConversation(ctx.userId, {
+ kind: 'normal',
+ title,
+ ...(validProjectId ? { projectId: validProjectId } : {}),
+ });
return { conversation: conv };
},
@@ -109,6 +141,31 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { deleted };
},
+ // ── Projects (logical groups of conversations + scoped workspace) ──
+ 'projects.list': async (_payload, ctx) => {
+ return { projects: await projects.listProjects(ctx.userId) };
+ },
+
+ 'projects.create': async ({ name }, ctx) => {
+ const result = await projects.createProject(ctx.userId, name);
+ if (!result.ok) throw new Error((result as { error: string }).error);
+ return { project: result.project };
+ },
+
+ 'projects.rename': async ({ projectId, name }, ctx) => {
+ if (!safeId(projectId)) throw new Error('invalid projectId');
+ const result = await projects.renameProject(ctx.userId, projectId, name);
+ if (!result.ok) throw new Error((result as { error: string }).error);
+ return { project: result.project };
+ },
+
+ 'projects.delete': async ({ projectId }, ctx) => {
+ if (!safeId(projectId)) throw new Error('invalid projectId');
+ const result = await projects.deleteProject(ctx.userId, projectId);
+ if (!result.ok) throw new Error((result as { error: string }).error);
+ return { deleted_convs: result.deleted_convs };
+ },
+
// ── Group chat (replaces legacy conversations.send / .stream / .markFormSubmitted) ──
'groupChat.send': async ({ cid, content, attachments }, ctx) => {
if (!safeId(cid)) throw new Error('invalid cid');
@@ -567,28 +624,42 @@ const invokeHandlers: Record<string, InvokeHandler> = {
},
// ── User workspace (working directory) ──
- 'workspace.get': async (_payload, ctx) => {
- return { path: userWorkspace.getWorkspacePath(ctx.userId) };
- },
- 'workspace.getInfo': async (_payload, ctx) => {
- return userWorkspace.getWorkspaceInfo(ctx.userId);
- },
- 'workspace.set': async ({ path }, ctx) => {
- if (!path || typeof path !== 'string') throw new Error('missing path');
- const result = userWorkspace.setWorkspacePath(ctx.userId, path);
+ // Workspace handlers accept an optional scope hint:
+ // `{ cid }` → main resolves cid → conv.project_id → scope
+ // `{ projectId }` → renderer-supplied scope (commander tab project chip,
+ // where there's no cid yet)
+ // neither → default scope
+ // When both are passed, cid takes precedence (it's the authoritative source
+ // — conv.project_id is the truth). Project membership is frozen at conv
+ // create time, so `cid → projectId` is a stable mapping.
+ 'workspace.get': async (payload, ctx) => {
+ const projectId = await _resolveWorkspaceScope(ctx.userId, payload);
+ return { path: userWorkspace.getWorkspacePath(ctx.userId, projectId) };
+ },
+ 'workspace.getInfo': async (payload, ctx) => {
+ const projectId = await _resolveWorkspaceScope(ctx.userId, payload);
+ return userWorkspace.getWorkspaceInfo(ctx.userId, projectId);
+ },
+ 'workspace.set': async (payload, ctx) => {
+ const target = payload?.path;
+ if (!target || typeof target !== 'string') throw new Error('missing path');
+ const projectId = await _resolveWorkspaceScope(ctx.userId, payload);
+ const result = userWorkspace.setWorkspacePath(ctx.userId, target, projectId);
if (!result.ok) throw new Error((result as any).error);
return { path: result.path };
},
- 'workspace.reset': async (_payload, ctx) => {
- const result = userWorkspace.resetWorkspacePath(ctx.userId);
+ 'workspace.reset': async (payload, ctx) => {
+ const projectId = await _resolveWorkspaceScope(ctx.userId, payload);
+ const result = userWorkspace.resetWorkspacePath(ctx.userId, projectId);
return { path: result.path };
},
'workspace.selectDirectory': async () => {
const selected = await userWorkspace.selectDirectory();
return { path: selected };
},
- 'workspace.openPath': async (_payload, ctx) => {
- const result = await userWorkspace.openWorkspaceInFileManager(ctx.userId);
+ 'workspace.openPath': async (payload, ctx) => {
+ const projectId = await _resolveWorkspaceScope(ctx.userId, payload);
+ const result = await userWorkspace.openWorkspaceInFileManager(ctx.userId, projectId);
if (!result.ok) throw new Error((result as { ok: false; error: string }).error);
return { path: result.path };
},
@@ -597,11 +668,13 @@ const invokeHandlers: Record<string, InvokeHandler> = {
// Explorer on Windows, default file manager on Linux). The path MUST
// sit inside the active user's workspace — outside paths are refused
// so a malicious / buggy LLM-emitted path can't pop arbitrary folders.
- 'workspace.revealPath': async ({ path: target }, ctx) => {
+ 'workspace.revealPath': async (payload, ctx) => {
+ const target = payload?.path;
if (typeof target !== 'string' || !target) {
throw new Error('missing path');
}
- const ws = userWorkspace.getWorkspacePath(ctx.userId);
+ const projectId = await _resolveWorkspaceScope(ctx.userId, payload);
+ const ws = userWorkspace.getWorkspacePath(ctx.userId, projectId);
const norm = path.resolve(target);
const wsNorm = path.resolve(ws);
if (!norm.startsWith(wsNorm + path.sep) && norm !== wsNorm) {
diff --git a/src/main/model/client.ts b/src/main/model/client.ts
index 2dffadee..59863e98 100644
--- a/src/main/model/client.ts
+++ b/src/main/model/client.ts
@@ -81,6 +81,11 @@ export interface ChatOptions {
* read_file / search_files / grep_files scope to this conv's attachment
* dir in addition to the user's active workspace. */
cid?: string;
+ /** Project id of the conversation, when it belongs to one. Threaded
+ * through to local-tools / file-tools / image-gen-tool so workspace
+ * resolution picks up the project-scoped selection. Caller (group_chat
+ * or skill/agent edit) resolves it once before invoking. */
+ projectId?: string;
/** Extra absolute directory roots whitelisted for file-tools on top of
* workspace + attachment. Read AND write are permitted under these roots.
* Per-skill edit chats pass the skill dir so the LLM can read / search /
diff --git a/src/main/model/core-agent/client.ts b/src/main/model/core-agent/client.ts
index 6aad78a1..ddb59611 100644
--- a/src/main/model/core-agent/client.ts
+++ b/src/main/model/core-agent/client.ts
@@ -87,6 +87,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
readOnlyExtraRoots,
agentId,
cid,
+ projectId,
onFileWritten,
hasProducedPath,
cacheRetention,
@@ -176,6 +177,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
userId,
agentId,
...(cid ? { cid } : {}),
+ ...(projectId ? { projectId } : {}),
...(skillList !== undefined ? { skillList } : {}),
...(extraTools && extraTools.length ? { extraTools } : {}),
...(extraRoots && extraRoots.length ? { extraRoots } : {}),
diff --git a/src/main/model/core-agent/file-tools.ts b/src/main/model/core-agent/file-tools.ts
index 0a428421..1a3f11d5 100644
--- a/src/main/model/core-agent/file-tools.ts
+++ b/src/main/model/core-agent/file-tools.ts
@@ -85,6 +85,11 @@ export interface FileToolsOpts {
* channels for those resources, and a sandbox-level lock keeps the LLM
* honest even when its prompt strays. */
readOnlyExtraRoots?: readonly string[];
+ /** Project id of the current conversation, when it belongs to one.
+ * Threaded through from group_chat at runTurn so workspace resolution
+ * picks up the project-scoped selection (per CLAUDE.md projects feature).
+ * Empty / missing → default-scope workspace. */
+ projectId?: string;
}
/** Assemble the allowed-roots list for the current (uid, cid). File-tools
@@ -92,7 +97,7 @@ export interface FileToolsOpts {
function allowedRoots(opts: FileToolsOpts): string[] {
const roots: string[] = [];
try {
- const ws = getWorkspacePath(opts.userId);
+ const ws = getWorkspacePath(opts.userId, opts.projectId);
if (ws) roots.push(ws);
} catch (err) { log.warn(`resolve workspace: ${(err as Error).message}`); }
if (opts.cid) {
@@ -404,7 +409,7 @@ function createSearchFilesTool(opts: FileToolsOpts): AgentTool {
const rootKinds: Array<{ root: string; source: 'attachment' | 'workspace' }> = [];
try {
- rootKinds.push({ root: getWorkspacePath(opts.userId), source: 'workspace' });
+ rootKinds.push({ root: getWorkspacePath(opts.userId, opts.projectId), source: 'workspace' });
} catch { /* workspace unavailable → skip */ }
if (opts.cid) {
rootKinds.push({ root: chatAttachmentDir(opts.userId, opts.cid), source: 'attachment' });
@@ -526,7 +531,7 @@ function createGrepFilesTool(opts: FileToolsOpts): AgentTool {
}
const rootKinds: Array<{ root: string; source: 'attachment' | 'workspace' }> = [];
- try { rootKinds.push({ root: getWorkspacePath(opts.userId), source: 'workspace' }); }
+ try { rootKinds.push({ root: getWorkspacePath(opts.userId, opts.projectId), source: 'workspace' }); }
catch { /* workspace unavailable */ }
if (opts.cid) rootKinds.push({ root: chatAttachmentDir(opts.userId, opts.cid), source: 'attachment' });
if (!rootKinds.length) {
diff --git a/src/main/model/core-agent/image-gen-tool.ts b/src/main/model/core-agent/image-gen-tool.ts
index e8705f06..8b7fadfd 100644
--- a/src/main/model/core-agent/image-gen-tool.ts
+++ b/src/main/model/core-agent/image-gen-tool.ts
@@ -39,6 +39,10 @@ export interface ImageGenToolOpts {
/** Conversation id — extends the path sandbox to allow writing into
* the conv's attachment dir (and reading reference images from it). */
cid?: string;
+ /** Project id of the current conversation, when it belongs to one.
+ * Threaded through from group_chat so workspace resolution picks up
+ * the project-scoped selection (per CLAUDE.md projects feature). */
+ projectId?: string;
/** Same contract as `local-tools.LocalToolsOpts.onFileWritten`. */
onFileWritten?: (absPath: string) => void;
/** Same contract as `local-tools.LocalToolsOpts.hasProducedPath`:
@@ -51,7 +55,7 @@ export interface ImageGenToolOpts {
function allowedRoots(opts: ImageGenToolOpts): string[] {
const roots: string[] = [];
try {
- const ws = getWorkspacePath(opts.userId);
+ const ws = getWorkspacePath(opts.userId, opts.projectId);
if (ws) roots.push(ws);
} catch (err) { log.warn(`resolve workspace: ${(err as Error).message}`); }
if (opts.cid) {
diff --git a/src/main/model/core-agent/local-tools.ts b/src/main/model/core-agent/local-tools.ts
index 67815a49..88b112b4 100644
--- a/src/main/model/core-agent/local-tools.ts
+++ b/src/main/model/core-agent/local-tools.ts
@@ -66,6 +66,11 @@ export interface LocalToolsOpts {
* conv's attachment dir to the sandbox. Without it, only the workspace
* (+ extraRoots) is editable. */
cid?: string;
+ /** Project id of the current conversation, when it belongs to one.
+ * Threaded through from group_chat at runTurn so workspace resolution
+ * picks up the project-scoped selection (per CLAUDE.md projects feature).
+ * Empty / missing → default-scope workspace. */
+ projectId?: string;
/** Extra absolute directory roots `edit_file` should treat as in-scope
* on top of workspace + attachment. Used by skill-edit / agent-edit
* chats so the LLM can edit files inside the skill / agent dir. */
@@ -115,7 +120,7 @@ function allowedRootsFor(opts: LocalToolsOpts): string[] {
const roots: string[] = [];
if (opts.userId) {
try {
- const ws = getWorkspacePath(opts.userId);
+ const ws = getWorkspacePath(opts.userId, opts.projectId);
if (ws) roots.push(ws);
} catch (err) { log.warn(`edit_file resolve workspace: ${(err as Error).message}`); }
if (opts.cid) {
diff --git a/src/main/model/core-agent/runner.ts b/src/main/model/core-agent/runner.ts
index 5efde80a..af747831 100644
--- a/src/main/model/core-agent/runner.ts
+++ b/src/main/model/core-agent/runner.ts
@@ -75,6 +75,11 @@ export interface BuildRunnerParams {
* / process_file_full calls whose path targets the attachment dir of the
* current conv. */
cid?: string;
+ /** Project id of the conversation, when it belongs to one. Threaded
+ * through to local-tools / file-tools / image-gen-tool so workspace
+ * resolution picks up the project-scoped selection. Resolved once at
+ * the top of group_chat::runTurn from `conv.project_id`. */
+ projectId?: string;
/** Agent id bound to the conversation. Empty/undefined = default scope. */
agentId?: string;
@@ -199,6 +204,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
const localTools = createLocalTools({
...(uid ? { userId: uid } : {}),
...(params.cid ? { cid: params.cid } : {}),
+ ...(params.projectId ? { projectId: params.projectId } : {}),
...(params.extraRoots?.length ? { extraRoots: params.extraRoots } : {}),
...(params.onFileWritten ? { onFileWritten: params.onFileWritten } : {}),
...(params.hasProducedPath ? { hasProducedPath: params.hasProducedPath } : {}),
@@ -216,6 +222,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
? createFileTools({
userId: uid,
...(params.cid ? { cid: params.cid } : {}),
+ ...(params.projectId ? { projectId: params.projectId } : {}),
...(params.extraRoots?.length ? { extraRoots: params.extraRoots } : {}),
...(params.readOnlyExtraRoots?.length ? { readOnlyExtraRoots: params.readOnlyExtraRoots } : {}),
})
@@ -236,6 +243,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
? [createImageGenTool({
userId: uid,
...(params.cid ? { cid: params.cid } : {}),
+ ...(params.projectId ? { projectId: params.projectId } : {}),
...(params.onFileWritten ? { onFileWritten: params.onFileWritten } : {}),
...(params.hasProducedPath ? { hasProducedPath: params.hasProducedPath } : {}),
})]
diff --git a/src/main/paths.ts b/src/main/paths.ts
index 009f6635..e7ab1d42 100644
--- a/src/main/paths.ts
+++ b/src/main/paths.ts
@@ -124,6 +124,17 @@ export const userProfileFile = (uid: string) => path.join(userMemoryDir(uid), 'U
// self-evolved skills).
export const userAgentsDir = (uid: string) => path.join(userCloudRoot(uid), 'agents');
export const userSkillsDir = (uid: string) => path.join(userCloudRoot(uid), 'skills');
+
+// Per-user projects (logical group of conversations + scoped workspace).
+// `_index.json` is the project list; `<pid>/` reserves space for future
+// per-project assets (knowledge base, access permissions, etc.) — empty in
+// the current round. See `features/projects.ts`. Project membership of a
+// conversation is recorded as a `project_id` field on the conv index entry,
+// NOT as a path component (cid stays globally unique; session_id schema is
+// untouched — see CLAUDE.md §5).
+export const userProjectsDir = (uid: string) => path.join(userCloudRoot(uid), 'projects');
+export const userProjectsIndexFile = (uid: string) => path.join(userProjectsDir(uid), '_index.json');
+export const projectDir = (uid: string, pid: string) => path.join(userProjectsDir(uid), pid);
export const agentDir = (uid: string, agentId: string) => path.join(userAgentsDir(uid), agentId || '_default');
export const agentDefinitionFile = (uid: string, agentId: string) => path.join(agentDir(uid, agentId), 'agent.json');
@@ -276,6 +287,7 @@ export function ensureUserLayout(uid: string): void {
userMemoryDir(uid),
userAgentsDir(uid),
userSkillsDir(uid),
+ userProjectsDir(uid),
// userMetaDir is deprecated — per-agent meta now lands in the
// `agents/<aid>/meta/` sub-directory, mkdir'd on demand at agent
// creation time, so no top-level placeholder is required.
diff --git a/src/renderer/index.html b/src/renderer/index.html
index 4beee294..8d2d86bf 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -27,7 +27,17 @@
<button class="sidebar-btn" id="skills-btn" data-i18n="sidebar.skills">Skills</button>
<button class="sidebar-btn" id="contexts-btn" data-i18n="sidebar.contexts">Knowledge</button>
</div>
- <div class="sidebar-section">
+ <div class="sidebar-section sidebar-projects-section">
+ <div class="sidebar-section-title-row">
+ <span class="sidebar-section-title" data-i18n="sidebar.projects">Projects</span>
+ <button class="sidebar-section-add" id="projects-add-btn"
+ data-i18n-title="sidebar.project_create_title"
+ data-i18n-aria-label="sidebar.project_create_title"
+ title="New project" aria-label="New project">+</button>
+ </div>
+ <div class="projects-list" id="projects-list"></div>
+ </div>
+ <div class="sidebar-section sidebar-conversations-section">
<div class="sidebar-section-title" data-i18n="sidebar.conversations">Conversations</div>
<div class="conversation-list" id="conversation-list">
<div class="conv-empty" data-i18n="sidebar.conv_empty">No conversations yet</div>
@@ -52,13 +62,12 @@
<div class="new-chat-subtitle" data-i18n="new_chat.subtitle">Type your question or task</div>
<div class="new-chat-input-wrapper">
<div class="new-chat-input-area">
- <!-- Floats above the input box. Attachments + workspace chip
- share one flex row: attachments wrap on the left, chip
- pinned right. Chip stays anchored to input-area's top
- regardless of attachment count. -->
+ <!-- Floats above the input box. Attachments wrap on the left;
+ the workspace chip moved into .chat-bottom-bar below
+ (next to recipient / project chips) so the overlay only
+ carries attachments now. -->
<div class="chat-input-overlay">
<div class="chat-attachments" id="new-chat-attachments" style="display:none"></div>
- <div class="chat-input-toolbar"></div>
</div>
<textarea id="new-chat-input" data-i18n-placeholder="new_chat.input_placeholder" placeholder="Type a message..." rows="2"></textarea>
<div class="chat-bottom-bar">
@@ -67,6 +76,13 @@
<span class="chat-recipient-prefix" data-i18n="chat.recipient_label">To: </span>
<span class="chat-recipient-name" id="new-chat-recipient-name" data-i18n="chat.recipient_commander">Commander</span>
</button>
+ <button type="button" class="chat-project-chip" id="new-chat-project-chip" data-i18n-title="chat.project_picker_title" title="Pick project">
+ <span class="chat-project-prefix" data-i18n="chat.project_label">Project: </span>
+ <span class="chat-project-name" id="new-chat-project-name" data-i18n="chat.project_none">None</span>
+ <svg class="chat-project-chevron" viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.5">
+ <polyline points="6 9 12 15 18 9"/>
+ </svg>
+ </button>
<div class="chat-skill-chip" id="new-chat-skill-chip" data-target="new-chat" style="display:none">
<span class="chip-label"></span>
<span class="chip-close" data-i18n-title="chat.chip_remove_title" title="Remove">×</span>
@@ -97,15 +113,14 @@
<div class="chat-queue-list" id="chat-queue-list"></div>
</div>
<div class="chat-input-area">
- <!-- Floats above the input box. Attachments + workspace chip
- share one flex row: attachments wrap on the left, chip
- pinned right. Chip stays anchored to input-area's top
- regardless of attachment count. -->
+ <!-- Floats above the input box. Plan rail anchors left, attachments
+ wrap to its right. The workspace chip moved into
+ .chat-bottom-bar below (next to the recipient chip) so
+ the overlay no longer holds it. -->
<div class="chat-input-overlay">
- <!-- Plan rail floats at left, mirroring the workspace chip
- on the right. Self-hides when current cid has no plan.
- Expanded body opens UPWARD (bottom: 100%) over the
- chat-history. See modules/plan-rail.js. -->
+ <!-- Plan rail floats at left. Self-hides when current cid has
+ no plan. Expanded body opens UPWARD (bottom: 100%) over
+ the chat-history. See modules/plan-rail.js. -->
<div id="plan-rail" class="plan-rail" style="display:none">
<div class="plan-rail-header" data-i18n-title="plan.toggle_title" title="Collapse / Expand">
<span class="plan-rail-title">📋 <span data-i18n="plan.title">Execution Plan</span></span>
@@ -115,7 +130,6 @@
<div class="plan-rail-body" id="plan-rail-body"></div>
</div>
<div class="chat-attachments" id="chat-attachments" style="display:none"></div>
- <div class="chat-input-toolbar"></div>
</div>
<div class="chat-quote-preview" id="chat-quote-preview" style="display:none"></div>
<textarea id="chat-input" data-i18n-placeholder="chat.input_placeholder" placeholder="Continue the conversation..." rows="2"></textarea>
@@ -759,6 +773,7 @@
<script src="./modules/chat-input-form.js"></script>
<script src="./modules/chat-lightbox.js"></script>
<script src="./modules/strip-structural-blocks.js"></script>
+ <script src="./modules/projects.js"></script>
<script src="./modules/conversation.js"></script>
<script src="./modules/plan-rail.js"></script>
<script src="./modules/queue-draft.js"></script>
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index 45e58fb0..0c249a82 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -27,6 +27,10 @@
"sidebar.contexts": "Knowledge",
"sidebar.conversations": "Conversations",
"sidebar.conv_empty": "No conversations yet",
+ "sidebar.projects": "Projects",
+ "sidebar.project_create_title": "New project",
+ "sidebar.project_create_placeholder": "Enter project name…",
+ "sidebar.project_conv_empty": "(no conversations)",
"sidebar.settings": "Settings",
"sidebar.settings_title": "Settings",
"new_chat.title": "Command agents to get things done",
@@ -42,6 +46,9 @@
"chat.recipient_commander": "Commander",
"chat.recipient_commander_hint": "Default recipient, no @ needed",
"chat.recipient_picker_title": "Switch recipient (commander / agent)",
+ "chat.project_label": "Project: ",
+ "chat.project_none": "None",
+ "chat.project_picker_title": "Pick project",
"chat.attach_title": "Upload attachment (text / PDF / Word / image / video)",
"chat.chip_remove_title": "Remove",
"chat.send_title": "Send",
@@ -360,9 +367,9 @@
"settings.section.data": "Data",
"settings.section.data_note": "Maintenance actions on local data. These cannot be undone.",
"settings.clear_all_convs.title": "Clear all conversations",
- "settings.clear_all_convs.sub": "Removes every conversation and its associated message history, attachments, plan, sessions, and search index entries — same cascade as clicking × on a single conversation, applied to all of them. Skills and agents are NOT touched.",
+ "settings.clear_all_convs.sub": "Deletes every conversation. Skills and agents are NOT touched.",
"settings.clear_all_convs.btn": "Clear all conversations",
- "settings.clear_all_convs.confirm": "Permanently delete all {count} conversation(s) and every related artifact (messages, attachments, plans, sessions, search index)? This cannot be undone.",
+ "settings.clear_all_convs.confirm": "Permanently delete all {count} conversation(s)? This cannot be undone.",
"settings.clear_all_convs.empty": "No conversations to clear.",
"settings.clear_all_convs.in_progress": "Clearing…",
"settings.clear_all_convs.success": "Cleared {count} conversation(s).",
@@ -545,11 +552,27 @@
"search.close_title": "Close (Esc)",
"search.empty_hint": "Type a keyword to start searching",
"workspace.unselected": "Not set",
+ "workspace.chip_label": "Workspace: ",
"workspace.chip_title": "Click to pick a workspace",
"workspace.default_header": "Default",
"workspace.recent_header": "Recent",
"workspace.pick_folder": "Pick folder...",
"workspace.open_folder": "Open folder...",
+ "workspace.scope_project": "Project \"{name}\" workspace",
+ "workspace.scope_project_generic": "Project workspace",
+ "project.menu.more_actions": "More actions",
+ "project.menu.rename": "Rename",
+ "project.menu.delete": "Delete",
+ "project.name_dup_inline": "A project with this name already exists",
+ "project.name_empty": "Project name cannot be empty",
+ "project.error.generic": "Operation failed, please try again",
+ "project.delete_confirm_title": "Delete project \"{name}\"?",
+ "project.delete_confirm_body": "The {count} conversation(s) in this project will also be deleted. This cannot be undone.",
+ "project.delete_confirm_body_empty": "Delete project \"{name}\"?",
+ "project.delete_danger_label": "Delete project + {count} conversations",
+ "project.delete_danger_label_empty": "Delete project",
+ "project.has_running_conv": "A conversation in this project is still running. Stop it before deleting.",
+ "project.delete_failed_generic": "Failed to delete project, please try again",
"search.history_title": "Recent searches",
"search.history_clear": "Clear",
"search.failed": "Search failed: {msg}",
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index 98255a34..7a99fb56 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -27,6 +27,10 @@
"sidebar.contexts": "知识库",
"sidebar.conversations": "对话记录",
"sidebar.conv_empty": "暂无对话",
+ "sidebar.projects": "项目",
+ "sidebar.project_create_title": "新建项目",
+ "sidebar.project_create_placeholder": "输入项目名称…",
+ "sidebar.project_conv_empty": "(暂无对话)",
"sidebar.settings": "设置",
"sidebar.settings_title": "设置",
"new_chat.title": "指挥智能体为你干活",
@@ -42,6 +46,9 @@
"chat.recipient_commander": "指挥官",
"chat.recipient_commander_hint": "默认接收者,无需 @",
"chat.recipient_picker_title": "切换接收者(指挥官 / 智能体)",
+ "chat.project_label": "项目:",
+ "chat.project_none": "无",
+ "chat.project_picker_title": "选择项目",
"chat.attach_title": "上传附件(文本/PDF/Word/图片/视频)",
"chat.chip_remove_title": "移除",
"chat.send_title": "发送",
@@ -360,9 +367,9 @@
"settings.section.data": "数据",
"settings.section.data_note": "对本地数据的维护操作,无法撤销。",
"settings.clear_all_convs.title": "清空所有对话",
- "settings.clear_all_convs.sub": "删除每一条对话以及它附带的消息记录、附件、计划、会话、搜索索引——和点单条对话上的 × 同样的清理流程,批量执行。技能和智能体不受影响。",
+ "settings.clear_all_convs.sub": "删除全部对话记录。技能和智能体不受影响。",
"settings.clear_all_convs.btn": "清空所有对话",
- "settings.clear_all_convs.confirm": "确认永久删除全部 {count} 条对话及其关联内容(消息、附件、计划、会话、搜索索引)?无法撤销。",
+ "settings.clear_all_convs.confirm": "确认永久删除全部 {count} 条对话记录?无法撤销。",
"settings.clear_all_convs.empty": "目前没有对话可清空。",
"settings.clear_all_convs.in_progress": "正在清理…",
"settings.clear_all_convs.success": "已清空 {count} 条对话。",
@@ -545,11 +552,27 @@
"search.close_title": "关闭 (Esc)",
"search.empty_hint": "输入关键词开始搜索",
"workspace.unselected": "未选择",
+ "workspace.chip_label": "工作区:",
"workspace.chip_title": "点击选择工作区",
"workspace.default_header": "默认",
"workspace.recent_header": "最近",
"workspace.pick_folder": "选择文件夹...",
"workspace.open_folder": "打开文件夹...",
+ "workspace.scope_project": "项目「{name}」工作区",
+ "workspace.scope_project_generic": "项目工作区",
+ "project.menu.more_actions": "更多操作",
+ "project.menu.rename": "重命名",
+ "project.menu.delete": "删除",
+ "project.name_dup_inline": "已有同名项目,换一个吧",
+ "project.name_empty": "项目名不能为空",
+ "project.error.generic": "操作失败,请重试",
+ "project.delete_confirm_title": "删除项目「{name}」?",
+ "project.delete_confirm_body": "该项目下的 {count} 条对话记录会被一并删除,无法恢复。",
+ "project.delete_confirm_body_empty": "确认删除项目「{name}」?",
+ "project.delete_danger_label": "删除项目和 {count} 个对话",
+ "project.delete_danger_label_empty": "删除项目",
+ "project.has_running_conv": "该项目下有对话正在生成,请先停止再删除",
+ "project.delete_failed_generic": "删除项目失败,请重试",
"search.history_title": "搜索历史",
"search.history_clear": "清空",
"search.failed": "搜索失败: {msg}",
diff --git a/src/renderer/modules/boot.js b/src/renderer/modules/boot.js
index e30c58cb..6bae8e85 100644
--- a/src/renderer/modules/boot.js
+++ b/src/renderer/modules/boot.js
@@ -12,6 +12,7 @@ async function bootApp() {
// Avatar catalog must be ready before loadAgents (which triggers card rendering).
await initAvatarCatalog();
await refreshModelGuard();
+ await loadProjects();
await loadConversations();
await loadAgents();
// Warm the commander avatar cache so the first chat render doesn't fall
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index 87ac4837..539c7932 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -285,9 +285,21 @@ function onEnterNewChatView() {
const hasDraft = !!(input && input.value);
if (!hasDraft) _newChatRecipient = { ..._COMMANDER };
_renderRecipientChip('new-chat');
+ // Project chip lives in projects.js — restore the last manual pick
+ // (lastProject localStorage) and refresh the workspace chip's scope.
+ if (typeof onEnterCommanderProjectChip === 'function') onEnterCommanderProjectChip();
}
function onEnterConversationView() {
_renderRecipientChip('conversation');
+ // Workspace chip scope follows the active conv's project (resolved on
+ // main side via cid → conv.project_id). Refresh whenever a conv mounts.
+ if (typeof refreshWorkspaceChip === 'function') refreshWorkspaceChip();
+ // One-shot auto-expand: if the conv we just entered belongs to a
+ // project, surface the project's row in the sidebar. Skipped when the
+ // project is already expanded; manual user collapse on subsequent
+ // renders is preserved (the auto-expand does not run inside
+ // renderProjectsSection — see comments in projects.js).
+ if (typeof autoExpandActiveConvProject === 'function') autoExpandActiveConvProject();
// Kick a one-shot evaluation so that a cid mid-plan picks up its current
// interactive assignee even if no plan_changed/state_changed event fires
// before the user types. View-enter never reverts to commander (see
@@ -1169,12 +1181,21 @@ function _bumpConvToTop(cid) {
function renderConversationList() {
const container = document.getElementById('conversation-list');
- if (!conversations.length) {
+ // Conversations with a project_id are rendered nested under their project
+ // by `projects.js::renderProjectsSection`. The "Conversations" section
+ // here only shows the unprojected ones — same data model as the user's
+ // mental picture (projected convs live "inside" their project, the rest
+ // sit in the catch-all section).
+ const unprojected = (conversations || []).filter((c) => !c || !c.project_id);
+ if (!unprojected.length) {
container.innerHTML = `<div class="conv-empty" data-i18n="sidebar.conv_empty">${escapeHtml(t('sidebar.conv_empty'))}</div>`;
+ // Still re-render the projects section so its badges refresh (the call
+ // is cheap when the cache is already loaded).
+ if (typeof renderProjectsSection === 'function') renderProjectsSection();
return;
}
const delTitle = escapeHtml(t('chat.conv_del_title'));
- container.innerHTML = conversations.map(c => {
+ container.innerHTML = unprojected.map(c => {
// All conversations are now the single `normal` kind — no type badge.
const title = escapeHtml(c.title || t('chat.new_conv_title'));
return `
@@ -1204,7 +1225,13 @@ function renderConversationList() {
});
});
- // Reapply pending / queued status badges after the DOM was re-rendered.
+ // Re-render the projects section (it consumes the same `conversations`
+ // global to group projected items by project).
+ if (typeof renderProjectsSection === 'function') renderProjectsSection();
+
+ // Reapply pending / queued status badges after the DOM was re-rendered
+ // (covers both the unprojected list and the projects section's nested
+ // conv items, since the helper queries by cid only).
_refreshAllConvBadges();
}
@@ -1929,6 +1956,11 @@ async function handleNewChatSubmit() {
// Snapshot the new-chat recipient *now* so a stray view-change between
// here and conv-create doesn't reset it before we can transfer.
_pendingNewChatRecipient = { ..._newChatRecipient };
+ // Same pattern for the commander project chip — capture before any
+ // view-change so the freshly-created conv inherits the picked project.
+ if (typeof _captureCommanderProjectForNewChat === 'function') {
+ _captureCommanderProjectForNewChat();
+ }
const content = applyRecipientPrefix(transformWithSkill(raw, skill), 'new-chat');
const draftItems = _chatAttachList(DRAFT_CID);
if (draftItems.some((a) => a.status === 'uploading')) {
@@ -1950,10 +1982,13 @@ async function handleNewChatSubmit() {
if (newBtn) newBtn.disabled = true;
let convId;
try {
+ const projectId = (typeof _consumeCommanderProjectForNewChat === 'function')
+ ? _consumeCommanderProjectForNewChat()
+ : '';
const res = await apiFetch('/api/conversations/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ kind: 'normal' }),
+ body: JSON.stringify({ kind: 'normal', ...(projectId ? { projectId } : {}) }),
});
const data = await res.json();
if (!data.ok) throw new Error(data.error || t('chat.create_conv_failed'));
@@ -1966,6 +2001,9 @@ async function handleNewChatSubmit() {
conv.title = _autoTitle(raw);
conversations.unshift(conv);
renderConversationList();
+ // The new conv may have landed inside a project — refresh the projects
+ // cache so its conv_count reflects the new total. Cheap (single IPC).
+ if (projectId && typeof loadProjects === 'function') loadProjects(true);
} catch (e) {
await uiAlert(t('chat.create_conv_failed_with_reason', { reason: e.message || e }));
if (newBtn) newBtn.disabled = false;
diff --git a/src/renderer/modules/dialogs.js b/src/renderer/modules/dialogs.js
index a958dd9e..394f7e86 100644
--- a/src/renderer/modules/dialogs.js
+++ b/src/renderer/modules/dialogs.js
@@ -63,6 +63,58 @@ function uiAlert(message) {
return _uiShowDialog({ message, showCancel: false }).then(() => {});
}
+// Danger-styled confirm: title + multi-line message + custom danger button
+// label. The primary button uses .btn-danger (red) so the user sees the
+// destructive action signed by the action wording itself. Used by the
+// project delete flow ("delete project + N conversations") — generic enough
+// to adopt for other irreversible actions later.
+//
+// Returns true if the user confirmed (clicked the danger button), false on
+// cancel / outside click / Esc.
+function uiConfirmDanger({ title, message, dangerLabel, cancelLabel } = {}) {
+ return new Promise((resolve) => {
+ const overlay = document.createElement('div');
+ overlay.className = 'modal-overlay ui-dialog-overlay open';
+ const titleHtml = title ? `<div class="ui-dialog-title">${escapeHtml(String(title))}</div>` : '';
+ const msgHtml = escapeHtml(String(message || '')).replace(/\n/g, '<br />');
+ const cancelText = escapeHtml(cancelLabel || _dialogLabel('common.cancel', 'Cancel'));
+ const dangerText = escapeHtml(dangerLabel || _dialogLabel('common.confirm', 'Confirm'));
+ overlay.innerHTML = `
+ <div class="modal ui-dialog ui-dialog-danger" role="dialog" aria-modal="true">
+ ${titleHtml}
+ <div class="ui-dialog-message">${msgHtml}</div>
+ <div class="modal-actions">
+ <button class="btn" data-act="cancel">${cancelText}</button>
+ <button class="btn btn-danger" data-act="ok">${dangerText}</button>
+ </div>
+ </div>
+ `;
+ document.body.appendChild(overlay);
+
+ const okBtn = overlay.querySelector('[data-act="ok"]');
+ const cancelBtn = overlay.querySelector('[data-act="cancel"]');
+ const onKey = (e) => {
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Escape') finish(false);
+ // Enter does NOT auto-fire danger — the user must explicitly click
+ // the red button. Reduces accidental confirmation on irreversible
+ // actions. (Standard uiConfirm keeps Enter-to-confirm.)
+ };
+ const finish = (val) => {
+ document.removeEventListener('keydown', onKey, true);
+ overlay.remove();
+ resolve(val);
+ };
+ okBtn.addEventListener('click', () => finish(true));
+ cancelBtn.addEventListener('click', () => finish(false));
+ overlay.addEventListener('click', (e) => {
+ if (e.target === overlay) finish(false);
+ });
+ document.addEventListener('keydown', onKey, true);
+ setTimeout(() => cancelBtn.focus(), 0); // focus cancel by default — safer
+ });
+}
+
// Text-input prompt with cancel / confirm buttons. Returns the entered string, or
// null on cancel. Mirrors native `prompt()` semantics.
function uiPrompt(message, defaultValue = '') {
diff --git a/src/renderer/modules/projects.js b/src/renderer/modules/projects.js
new file mode 100644
index 00000000..ad72d39a
--- /dev/null
+++ b/src/renderer/modules/projects.js
@@ -0,0 +1,737 @@
+// ─── Sidebar Projects section ────────────────────────────────────────────
+// Renders the "Projects" group above the conversation list. Each project
+// row supports collapse/expand, a ⋯ menu (rename / delete), and inline
+// rename. Conversations with a `project_id` field are nested under their
+// project; conversations without `project_id` stay in the existing
+// "Conversations" section (rendered by `conversation.js::renderConversationList`).
+//
+// Storage layout (cloud-synced): `<uid>/cloud/projects/_index.json`. See
+// `features/projects.ts`. The renderer never persists projects state directly —
+// every mutation goes through `projects.*` IPC channels.
+//
+// Depends on: ipc-shim.js (apiFetch), conversation.js (escapeHtml /
+// renderConversationList / _refreshAllConvBadges), dialogs.js (uiConfirmDanger).
+
+const _projectsLog = createLogger('projects');
+
+// Live cache of projects fetched from the backend. Mirrors `_agentsCache` /
+// `_skillsCache` patterns. `null` = not yet fetched.
+let _projectsCache = null;
+
+// Per-project expand/collapse state, persisted across sessions so the user's
+// layout sticks. Default: collapsed.
+const _PROJECTS_EXPANDED_KEY = 'sidebar.projectExpanded';
+let _projectsExpanded = {};
+
+function _loadProjectsExpanded() {
+ try {
+ const raw = localStorage.getItem(_PROJECTS_EXPANDED_KEY);
+ if (raw) _projectsExpanded = JSON.parse(raw) || {};
+ } catch (_) { _projectsExpanded = {}; }
+}
+function _saveProjectsExpanded() {
+ try { localStorage.setItem(_PROJECTS_EXPANDED_KEY, JSON.stringify(_projectsExpanded)); } catch (_) {}
+}
+_loadProjectsExpanded();
+
+// In-flight inline-create / inline-rename state. Only one editing row at a
+// time across the whole sidebar.
+let _projectsInlineCreate = false;
+let _projectsInlineRenamePid = null;
+
+// ── Public API: cache + render ──────────────────────────────────────────
+
+async function loadProjects(forceRefresh) {
+ if (_projectsCache && !forceRefresh) {
+ renderProjectsSection();
+ return _projectsCache;
+ }
+ try {
+ const res = await window.orkas.invoke('projects.list', {});
+ _projectsCache = (res && res.ok && Array.isArray(res.projects)) ? res.projects : [];
+ } catch (err) {
+ _projectsLog.warn('load projects failed', err);
+ _projectsCache = [];
+ }
+ renderProjectsSection();
+ // Commander chip visibility depends on cache size — hide entirely when
+ // the user has zero projects (UX request: no project chip clutter on
+ // first run / for users who don't adopt the feature).
+ _renderCommanderProjectChip();
+ return _projectsCache;
+}
+
+/** One-shot: ensure the project owning the active cid is expanded so the
+ * user can see their open conversation. **Does not run on every render**
+ * — that would defeat manual collapse. Call this from boot + setView
+ * ('conversation', cid) only. Manual user collapse always wins on the
+ * next render. */
+function autoExpandActiveConvProject() {
+ if (!currentCid || !Array.isArray(conversations)) return;
+ const owner = conversations.find((c) => c && c.conversation_id === currentCid);
+ const pid = owner && owner.project_id;
+ if (!pid) return;
+ if (_projectsExpanded[pid]) return;
+ _projectsExpanded[pid] = true;
+ _saveProjectsExpanded();
+ renderProjectsSection();
+}
+
+/** Map cid → projectId from the live `conversations` global, used by
+ * `conversation.js::renderConversationList` to filter unprojected items
+ * and by us to group projected items by project. */
+function _convsByProject() {
+ const byPid = new Map();
+ if (!Array.isArray(conversations)) return byPid;
+ for (const c of conversations) {
+ const pid = c && c.project_id;
+ if (!pid) continue;
+ if (!byPid.has(pid)) byPid.set(pid, []);
+ byPid.get(pid).push(c);
+ }
+ return byPid;
+}
+
+/** Project list at the top of the sidebar. Auto-expands the project that
+ * owns the active conversation so the live row is visible. */
+function renderProjectsSection() {
+ const container = document.getElementById('projects-list');
+ if (!container) return;
+ const projects = Array.isArray(_projectsCache) ? _projectsCache : [];
+ if (!projects.length && !_projectsInlineCreate) {
+ // No projects + not creating — render nothing (the `+` button at the
+ // section header is the entry point). Avoid an empty-state row to keep
+ // the sidebar compact when the user hasn't adopted the feature.
+ container.innerHTML = '';
+ return;
+ }
+
+ const byPid = _convsByProject();
+ // **Auto-expand is intentionally NOT done here.** Earlier this lived
+ // inline (force `_projectsExpanded[pid]=true` whenever currentCid belonged
+ // to a project) and that meant clicking the row to collapse a project
+ // whose conv was active immediately re-expanded on the very next render
+ // — user perceived it as "can't collapse projects that have convs". Now
+ // auto-expand is a one-shot side effect of explicit
+ // `autoExpandActiveConvProject()` calls (boot + view-change to a
+ // conversation), so manual collapse always wins.
+
+ const rows = [];
+ // Inline-create row at the top.
+ if (_projectsInlineCreate) {
+ rows.push(_renderInlineCreateRow());
+ }
+ for (const p of projects) {
+ rows.push(_renderProjectRow(p, byPid.get(p.project_id) || []));
+ }
+ container.innerHTML = rows.join('');
+
+ _bindProjectsHandlers(container);
+ // Re-paint pending / queued badges on the conv items we just (re)rendered.
+ if (typeof _refreshAllConvBadges === 'function') _refreshAllConvBadges();
+}
+
+function _renderInlineCreateRow() {
+ const placeholder = escapeHtml(t('sidebar.project_create_placeholder'));
+ // Match the same icon-only chrome as the regular project rows (no caret,
+ // KB-style folder SVG) so the create row reads as "a project being born"
+ // rather than a separate widget shape.
+ return `
+ <div class="project-row project-row-create" data-create>
+ <span class="project-icon">${ICON_FOLDER_CLOSED}</span>
+ <input type="text" class="project-rename-input" id="project-create-input"
+ placeholder="${placeholder}" autocomplete="off" spellcheck="false" />
+ </div>
+ `;
+}
+
+function _renderProjectRow(p, convs) {
+ const expanded = !!_projectsExpanded[p.project_id];
+ const editing = _projectsInlineRenamePid === p.project_id;
+ // Reuse KB tree's folder SVG icons; open variant when expanded, closed
+ // otherwise. Defined as global consts in modules/skills.js (script load
+ // order: skills.js loads after projects.js, but renderProjectsSection
+ // only runs post-DOMContentLoaded by which point all scripts have
+ // initialised). No separate caret — the icon's open/closed state IS the
+ // expand indicator (matches the KB tree pattern).
+ const folderIcon = expanded ? ICON_FOLDER_OPEN : ICON_FOLDER_CLOSED;
+ const moreTitle = escapeHtml(t('project.menu.more_actions'));
+ const safeName = escapeHtml(p.name || '');
+ const nameNode = editing
+ ? `<input type="text" class="project-rename-input" data-rename-pid="${escapeHtml(p.project_id)}"
+ value="${escapeHtml(p.name || '')}" autocomplete="off" spellcheck="false" />`
+ : `<span class="project-name" title="${safeName}">${safeName}</span>`;
+ let html = `
+ <div class="project-row" data-pid="${escapeHtml(p.project_id)}">
+ <span class="project-icon">${folderIcon}</span>
+ ${nameNode}
+ <button type="button" class="ctx-row-menu-btn project-row-menu-btn" data-project-menu
+ data-pid="${escapeHtml(p.project_id)}"
+ title="${moreTitle}" aria-label="${moreTitle}">⋯</button>
+ </div>
+ `;
+ if (expanded) {
+ html += `<div class="project-conv-list" data-pid-children="${escapeHtml(p.project_id)}">`;
+ if (!convs.length) {
+ html += `<div class="project-conv-empty">${escapeHtml(t('sidebar.project_conv_empty'))}</div>`;
+ } else {
+ const delTitle = escapeHtml(t('chat.conv_del_title'));
+ for (const c of convs) {
+ const title = escapeHtml(c.title || t('chat.new_conv_title'));
+ html += `
+ <div class="conv-item conv-item-nested" data-cid="${c.conversation_id}">
+ <div class="conv-item-title" title="${title}">${title}</div>
+ <button class="conv-item-del" data-del-cid="${c.conversation_id}" title="${delTitle}">×</button>
+ </div>
+ `;
+ }
+ }
+ html += '</div>';
+ }
+ return html;
+}
+
+// ── Event wiring ────────────────────────────────────────────────────────
+
+function _bindProjectsHandlers(container) {
+ // Inline-create input.
+ const createInput = container.querySelector('#project-create-input');
+ if (createInput) _bindInlineCreateInput(createInput);
+
+ // Inline-rename inputs (at most one).
+ container.querySelectorAll('input.project-rename-input[data-rename-pid]').forEach((input) => {
+ _bindInlineRenameInput(input);
+ });
+
+ // Project rows: caret / icon / name → toggle expand;
+ // ⋯ button → open menu (stopPropagation);
+ // .project-rename-input → swallow click (don't toggle).
+ container.querySelectorAll('.project-row[data-pid]').forEach((row) => {
+ const pid = row.dataset.pid;
+ row.addEventListener('click', (e) => {
+ if (e.target.closest('.project-rename-input')) {
+ e.stopPropagation();
+ return;
+ }
+ if (e.target.closest('[data-project-menu]')) {
+ e.stopPropagation();
+ _openProjectRowMenu(e.target.closest('[data-project-menu]'), pid);
+ return;
+ }
+ _toggleProjectExpand(pid);
+ });
+ });
+
+ // Nested conv items.
+ container.querySelectorAll('.conv-item-nested').forEach((el) => {
+ el.addEventListener('click', (e) => {
+ if (e.target.closest('.conv-item-del')) return;
+ setView('conversation', el.dataset.cid);
+ });
+ });
+ container.querySelectorAll('.conv-item-nested .conv-item-del').forEach((btn) => {
+ btn.addEventListener('click', async (e) => {
+ e.stopPropagation();
+ const cid = btn.dataset.delCid;
+ if (!(await uiConfirm(t('chat.conv_del_confirm')))) return;
+ if (typeof abortConvStream === 'function') abortConvStream(cid);
+ if (typeof _forgetConvLocal === 'function') _forgetConvLocal(cid);
+ await apiFetch(`/api/conversations/${cid}`, { method: 'DELETE' });
+ if (currentCid === cid) setView('new-chat');
+ await loadConversations();
+ // Project conv counts changed → refresh project cache so future reads
+ // (delete confirm body, etc.) see the right number.
+ await loadProjects(true);
+ });
+ });
+}
+
+function _toggleProjectExpand(pid) {
+ _projectsExpanded[pid] = !_projectsExpanded[pid];
+ _saveProjectsExpanded();
+ renderProjectsSection();
+}
+
+// ── Inline create ───────────────────────────────────────────────────────
+
+function _startProjectInlineCreate() {
+ if (_projectsInlineCreate) return;
+ _projectsInlineRenamePid = null;
+ _projectsInlineCreate = true;
+ renderProjectsSection();
+ setTimeout(() => {
+ const input = document.getElementById('project-create-input');
+ if (input) input.focus();
+ }, 0);
+}
+
+function _cancelProjectInlineCreate() {
+ if (!_projectsInlineCreate) return;
+ _projectsInlineCreate = false;
+ renderProjectsSection();
+}
+
+function _bindInlineCreateInput(input) {
+ input.addEventListener('click', (e) => e.stopPropagation());
+ let committed = false;
+ const commit = async (accept) => {
+ if (committed) return;
+ committed = true;
+ const name = (input.value || '').trim();
+ if (!accept || !name) {
+ _cancelProjectInlineCreate();
+ return;
+ }
+ try {
+ const res = await window.orkas.invoke('projects.create', { name });
+ if (!res || !res.ok) {
+ // Re-enter editing mode + show inline error.
+ committed = false;
+ _showProjectInlineError(input, res && res.error);
+ return;
+ }
+ // Auto-expand the freshly created project so users see it's empty &
+ // ready for new convs.
+ const pid = res.project && res.project.project_id;
+ if (pid) {
+ _projectsExpanded[pid] = true;
+ _saveProjectsExpanded();
+ }
+ _projectsInlineCreate = false;
+ await loadProjects(true);
+ } catch (err) {
+ committed = false;
+ _showProjectInlineError(input, err && err.message);
+ }
+ };
+ input.addEventListener('keydown', (e) => {
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Enter') { e.preventDefault(); commit(true); }
+ else if (e.key === 'Escape') { e.preventDefault(); commit(false); }
+ });
+ input.addEventListener('blur', () => commit(true));
+ // Clear inline error styling as the user types.
+ input.addEventListener('input', () => _clearProjectInlineError(input));
+}
+
+// ── Inline rename ───────────────────────────────────────────────────────
+
+function _startProjectInlineRename(pid) {
+ _projectsInlineCreate = false;
+ _projectsInlineRenamePid = pid;
+ renderProjectsSection();
+ setTimeout(() => {
+ const input = document.querySelector(`input.project-rename-input[data-rename-pid="${CSS.escape(pid)}"]`);
+ if (input) {
+ input.focus();
+ input.select();
+ }
+ }, 0);
+}
+
+function _cancelProjectInlineRename() {
+ if (!_projectsInlineRenamePid) return;
+ _projectsInlineRenamePid = null;
+ renderProjectsSection();
+}
+
+function _bindInlineRenameInput(input) {
+ input.addEventListener('click', (e) => e.stopPropagation());
+ const pid = input.dataset.renamePid;
+ const original = input.value;
+ let committed = false;
+ const commit = async (accept) => {
+ if (committed) return;
+ committed = true;
+ const next = (input.value || '').trim();
+ if (!accept || !next || next === original) {
+ _cancelProjectInlineRename();
+ return;
+ }
+ try {
+ const res = await window.orkas.invoke('projects.rename', { projectId: pid, name: next });
+ if (!res || !res.ok) {
+ committed = false;
+ _showProjectInlineError(input, res && res.error);
+ return;
+ }
+ _projectsInlineRenamePid = null;
+ await loadProjects(true);
+ } catch (err) {
+ committed = false;
+ _showProjectInlineError(input, err && err.message);
+ }
+ };
+ input.addEventListener('keydown', (e) => {
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Enter') { e.preventDefault(); commit(true); }
+ else if (e.key === 'Escape') { e.preventDefault(); commit(false); }
+ });
+ input.addEventListener('blur', () => commit(true));
+ input.addEventListener('input', () => _clearProjectInlineError(input));
+}
+
+function _showProjectInlineError(input, code) {
+ if (!input) return;
+ input.classList.add('is-error');
+ // Build / replace a sibling hint right below the input.
+ let hint = input.parentElement?.querySelector('.project-inline-error');
+ if (!hint) {
+ hint = document.createElement('div');
+ hint.className = 'project-inline-error';
+ input.parentElement?.appendChild(hint);
+ }
+ let key = 'project.error.generic';
+ if (code === 'name_dup') key = 'project.name_dup_inline';
+ else if (code === 'name_empty') key = 'project.name_empty';
+ hint.textContent = t(key);
+ // Re-focus so the user can keep editing without an extra click.
+ setTimeout(() => input.focus(), 0);
+}
+
+function _clearProjectInlineError(input) {
+ if (!input) return;
+ input.classList.remove('is-error');
+ const hint = input.parentElement?.querySelector('.project-inline-error');
+ if (hint) hint.remove();
+}
+
+// ── ⋯ menu ──────────────────────────────────────────────────────────────
+
+function _openProjectRowMenu(anchorBtn, pid) {
+ let menu = document.getElementById('project-row-menu');
+ if (!menu) {
+ menu = document.createElement('div');
+ menu.id = 'project-row-menu';
+ menu.className = 'ctx-row-menu'; // reuse KB menu styling
+ menu.style.display = 'none';
+ document.body.appendChild(menu);
+ }
+ const sameAnchor = menu.dataset.pid === pid && menu.style.display !== 'none';
+ if (sameAnchor) { _closeProjectRowMenu(); return; }
+ _closeProjectRowMenu();
+
+ const items = [
+ { action: 'rename', label: t('project.menu.rename') },
+ { action: 'delete', label: t('project.menu.delete'), danger: true },
+ ];
+ menu.innerHTML = items.map((it) =>
+ `<div class="ctx-row-menu-item${it.danger ? ' is-danger' : ''}" data-action="${escapeHtml(it.action)}">${escapeHtml(it.label)}</div>`
+ ).join('');
+ menu.dataset.pid = pid;
+
+ const srcRow = anchorBtn.closest('.project-row');
+ for (const r of document.querySelectorAll('.is-menu-open')) r.classList.remove('is-menu-open');
+ if (srcRow) srcRow.classList.add('is-menu-open');
+
+ // Position above-or-below, mirroring KB.
+ menu.style.display = 'block';
+ menu.style.left = '-9999px';
+ menu.style.top = '-9999px';
+ const rect = anchorBtn.getBoundingClientRect();
+ const menuRect = menu.getBoundingClientRect();
+ const margin = 8;
+ const gap = 4;
+ let left = rect.right - menuRect.width;
+ if (left < margin) left = margin;
+ if (left + menuRect.width > window.innerWidth - margin) {
+ left = window.innerWidth - menuRect.width - margin;
+ }
+ const below = rect.bottom + gap + menuRect.height <= window.innerHeight - margin;
+ const top = below ? rect.bottom + gap : Math.max(margin, rect.top - menuRect.height - gap);
+ menu.style.left = left + 'px';
+ menu.style.top = top + 'px';
+
+ for (const item of menu.querySelectorAll('.ctx-row-menu-item')) {
+ item.addEventListener('click', async (e) => {
+ e.stopPropagation();
+ const action = item.dataset.action;
+ _closeProjectRowMenu();
+ await _runProjectMenuAction(action, pid);
+ });
+ }
+}
+
+function _closeProjectRowMenu() {
+ const menu = document.getElementById('project-row-menu');
+ if (menu) {
+ menu.style.display = 'none';
+ delete menu.dataset.pid;
+ }
+ for (const r of document.querySelectorAll('.project-row.is-menu-open')) r.classList.remove('is-menu-open');
+}
+
+async function _runProjectMenuAction(action, pid) {
+ if (action === 'rename') return _startProjectInlineRename(pid);
+ if (action === 'delete') return _confirmDeleteProject(pid);
+}
+
+// ── Delete flow ─────────────────────────────────────────────────────────
+
+async function _confirmDeleteProject(pid) {
+ const project = (_projectsCache || []).find((p) => p.project_id === pid);
+ if (!project) return;
+ const name = project.name || '';
+ const count = Number(project.conv_count || 0);
+ // Build the confirm dialog. When N > 0 we surface the destructive scope on
+ // the danger button itself so the user has to read N before clicking;
+ // when N = 0 it's just a simple confirm.
+ let message;
+ let dangerLabel;
+ if (count > 0) {
+ message = t('project.delete_confirm_body', { count });
+ dangerLabel = t('project.delete_danger_label', { count });
+ } else {
+ message = t('project.delete_confirm_body_empty', { name });
+ dangerLabel = t('project.delete_danger_label_empty');
+ }
+ const ok = await uiConfirmDanger({
+ title: t('project.delete_confirm_title', { name }),
+ message,
+ dangerLabel,
+ });
+ if (!ok) return;
+
+ try {
+ const res = await window.orkas.invoke('projects.delete', { projectId: pid });
+ if (!res || !res.ok) {
+ const code = res && res.error;
+ if (code === 'has_running_conv') {
+ await uiAlert(t('project.has_running_conv'));
+ } else {
+ await uiAlert(t('project.delete_failed_generic'));
+ }
+ return;
+ }
+ // Clear lastProject if the commander chip pointed at this pid.
+ try {
+ if (typeof _COMMANDER_LAST_PROJECT_KEY !== 'undefined') {
+ const stored = localStorage.getItem(_COMMANDER_LAST_PROJECT_KEY);
+ if (stored === pid) localStorage.removeItem(_COMMANDER_LAST_PROJECT_KEY);
+ }
+ } catch (_) {}
+ // Drop expanded entry.
+ if (_projectsExpanded[pid]) {
+ delete _projectsExpanded[pid];
+ _saveProjectsExpanded();
+ }
+ // The cascade dropped every conv in this project — if the active cid
+ // was one of them, jump back to the new-chat view (mirrors the existing
+ // single-conv delete behaviour).
+ if (currentCid && Array.isArray(conversations)) {
+ const stillExists = conversations.some((c) => c && c.conversation_id === currentCid && c.project_id !== pid);
+ if (!stillExists) setView('new-chat');
+ }
+ await loadConversations();
+ await loadProjects(true);
+ // Commander chip may need to refresh ("None" if its pid was deleted).
+ if (typeof refreshCommanderProjectChip === 'function') refreshCommanderProjectChip();
+ } catch (err) {
+ _projectsLog.error('delete project failed', err);
+ await uiAlert(t('project.delete_failed_generic'));
+ }
+}
+
+// ── Commander project chip ─────────────────────────────────────────────
+// The commander tab (new-chat) carries a "Project: <name>" chip next to the
+// recipient chip. Default is None; the last manual pick is remembered across
+// sessions so reopening the commander tab restores the user's intent. The
+// pick travels into the freshly-created conversation via
+// `_pendingNewChatProjectId` (mirrors `_pendingNewChatRecipient`).
+//
+// In conversation detail there is NO project chip — project membership is
+// frozen at create time per the design.
+
+const _COMMANDER_LAST_PROJECT_KEY = 'commander.lastProject';
+const _COMMANDER_NONE_SENTINEL = '__none__';
+
+let _commanderProjectId = ''; // ephemeral, lives only while commander tab is mounted
+let _pendingNewChatProjectId = ''; // ferried into the new conv after submit
+
+/** Public: read the commander tab's currently-picked project id (or '' for
+ * None). user-workspace.js uses this to scope its chip on the new-chat panel. */
+function getCommanderProjectId() {
+ return _commanderProjectId || '';
+}
+
+/** Public: resolve a project id to its display name from the cache. Returns
+ * empty string when the pid is unknown (e.g. just deleted). Used by
+ * user-workspace.js for the chip tooltip. */
+function getCommanderProjectIdName(pid) {
+ if (!pid || !Array.isArray(_projectsCache)) return '';
+ const p = _projectsCache.find((x) => x && x.project_id === pid);
+ return (p && p.name) || '';
+}
+
+/** Public: surface the captured commander pick to handleNewChatSubmit so it
+ * can attach the projectId to the freshly-created conversation. The caller
+ * is expected to clear the ferry after consuming. */
+function _captureCommanderProjectForNewChat() {
+ _pendingNewChatProjectId = _commanderProjectId || '';
+}
+
+function _consumeCommanderProjectForNewChat() {
+ const pid = _pendingNewChatProjectId;
+ _pendingNewChatProjectId = '';
+ return pid;
+}
+
+/** Public: re-render the commander chip label + reset to None when the
+ * pid is gone (project was deleted). Called from delete flow + boot. */
+function refreshCommanderProjectChip() {
+ // Bail when the pinned id has vanished from the cache → fall back to None.
+ if (_commanderProjectId && Array.isArray(_projectsCache)) {
+ const exists = _projectsCache.some((p) => p && p.project_id === _commanderProjectId);
+ if (!exists) {
+ _commanderProjectId = '';
+ try { localStorage.removeItem(_COMMANDER_LAST_PROJECT_KEY); } catch (_) {}
+ }
+ }
+ _renderCommanderProjectChip();
+ // Workspace scope on the commander panel changes whenever the project pick
+ // changes (or a pid silently fell back to None). Keep the chip in sync.
+ if (typeof refreshWorkspaceChip === 'function') refreshWorkspaceChip();
+}
+
+function _renderCommanderProjectChip() {
+ const chip = document.getElementById('new-chat-project-chip');
+ const nameEl = document.getElementById('new-chat-project-name');
+ if (!chip || !nameEl) return;
+ // Hide the chip entirely when the user has no projects yet — first-run
+ // / non-adopters don't see a "Project: None" affordance until they
+ // create at least one project. Re-shown automatically the moment a
+ // project lands in the cache.
+ const hasProjects = Array.isArray(_projectsCache) && _projectsCache.length > 0;
+ if (!hasProjects) {
+ chip.style.display = 'none';
+ return;
+ }
+ chip.style.display = '';
+ const pid = _commanderProjectId;
+ if (pid) {
+ const p = _projectsCache.find((x) => x && x.project_id === pid);
+ if (p && p.name) {
+ nameEl.textContent = p.name;
+ nameEl.removeAttribute('data-i18n');
+ return;
+ }
+ }
+ // Fallback to None.
+ nameEl.setAttribute('data-i18n', 'chat.project_none');
+ nameEl.textContent = t('chat.project_none');
+}
+
+/** Restore the commander chip from localStorage on view-enter. Validates
+ * the saved pid still exists; falls back to None and clears storage if
+ * not. Called by conversation.js::onEnterNewChatView. */
+function onEnterCommanderProjectChip() {
+ let saved = '';
+ try { saved = localStorage.getItem(_COMMANDER_LAST_PROJECT_KEY) || ''; } catch (_) {}
+ if (saved === _COMMANDER_NONE_SENTINEL || !saved) {
+ _commanderProjectId = '';
+ } else if (Array.isArray(_projectsCache) && _projectsCache.some((p) => p && p.project_id === saved)) {
+ _commanderProjectId = saved;
+ } else {
+ _commanderProjectId = '';
+ try { localStorage.removeItem(_COMMANDER_LAST_PROJECT_KEY); } catch (_) {}
+ }
+ _renderCommanderProjectChip();
+ if (typeof refreshWorkspaceChip === 'function') refreshWorkspaceChip();
+}
+
+/** User clicked the commander chip → show a small popover listing
+ * None + every existing project. Style mirrors the workspace dropdown. */
+function _showCommanderProjectPicker(anchor) {
+ const old = document.getElementById('commander-project-picker');
+ if (old) { old.remove(); return; }
+
+ const menu = document.createElement('div');
+ menu.id = 'commander-project-picker';
+ menu.className = 'workspace-menu'; // reuse styling
+ anchor.classList.add('chat-project-chip--open');
+
+ const items = [
+ { id: '', name: t('chat.project_none') },
+ ...((_projectsCache || []).map((p) => ({ id: p.project_id, name: p.name }))),
+ ];
+ for (const it of items) {
+ const isActive = (it.id || '') === (_commanderProjectId || '');
+ const row = document.createElement('div');
+ row.className = 'workspace-menu-item' + (isActive ? ' workspace-menu-item--active' : '');
+ const label = document.createElement('span');
+ label.textContent = it.name;
+ row.appendChild(label);
+ if (isActive) {
+ const check = document.createElement('span');
+ check.className = 'workspace-menu-check';
+ check.textContent = '✓';
+ row.appendChild(check);
+ }
+ row.addEventListener('click', () => {
+ _commanderProjectId = it.id || '';
+ try {
+ if (_commanderProjectId) localStorage.setItem(_COMMANDER_LAST_PROJECT_KEY, _commanderProjectId);
+ else localStorage.setItem(_COMMANDER_LAST_PROJECT_KEY, _COMMANDER_NONE_SENTINEL);
+ } catch (_) {}
+ _renderCommanderProjectChip();
+ if (typeof refreshWorkspaceChip === 'function') refreshWorkspaceChip();
+ _closeMenu();
+ });
+ menu.appendChild(row);
+ }
+
+ const rect = anchor.getBoundingClientRect();
+ menu.style.position = 'fixed';
+ menu.style.left = rect.left + 'px';
+ menu.style.bottom = (window.innerHeight - rect.top + 4) + 'px';
+
+ document.body.appendChild(menu);
+
+ function _closeMenu() {
+ menu.remove();
+ anchor.classList.remove('chat-project-chip--open');
+ document.removeEventListener('mousedown', _onOutside);
+ }
+ function _onOutside(e) {
+ if (!menu.contains(e.target) && !anchor.contains(e.target)) _closeMenu();
+ }
+ setTimeout(() => document.addEventListener('mousedown', _onOutside), 0);
+}
+
+// ── Init ────────────────────────────────────────────────────────────────
+
+document.addEventListener('DOMContentLoaded', () => {
+ // `+` button on the section header.
+ const addBtn = document.getElementById('projects-add-btn');
+ if (addBtn) {
+ addBtn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ _startProjectInlineCreate();
+ });
+ }
+ // Commander chip click → open picker.
+ const commanderChip = document.getElementById('new-chat-project-chip');
+ if (commanderChip) {
+ commanderChip.addEventListener('click', (e) => {
+ e.stopPropagation();
+ _showCommanderProjectPicker(commanderChip);
+ });
+ }
+ // Outside-click closes the ⋯ menu (mirrors KB).
+ document.addEventListener('click', (e) => {
+ const menu = document.getElementById('project-row-menu');
+ if (!menu || menu.style.display === 'none') return;
+ if (menu.contains(e.target)) return;
+ if (e.target.closest('[data-project-menu]')) return;
+ _closeProjectRowMenu();
+ });
+ window.addEventListener('scroll', _closeProjectRowMenu, true);
+ window.addEventListener('resize', _closeProjectRowMenu);
+ window.addEventListener('i18n-change', () => {
+ _closeProjectRowMenu();
+ if (_projectsCache) {
+ renderProjectsSection();
+ _renderCommanderProjectChip();
+ }
+ });
+});
diff --git a/src/renderer/modules/user-workspace.js b/src/renderer/modules/user-workspace.js
index d2aa7a9d..2fc50448 100644
--- a/src/renderer/modules/user-workspace.js
+++ b/src/renderer/modules/user-workspace.js
@@ -1,14 +1,30 @@
// ─── User Workspace selector ────────────────────────────────────────
-// Adds a "workspace" chip to the bottom-left of chat input toolbars
-// (new-chat + conversation + agent-edit). Clicking it opens a dropdown
-// with Default workspace, recently used workspaces, and a folder picker.
+// Adds a "workspace" chip to the bottom bar of chat input toolbars
+// (new-chat + conversation). Clicking it opens a dropdown with Default
+// workspace, recently used workspaces, and a folder picker.
+//
+// **Scoped resolution** (per CLAUDE.md projects feature):
+// - On the conversation panel, the chip resolves scope from the active
+// `currentCid` — main looks up `conv.project_id` and operates on the
+// project's per-scope workspace entry. Changes apply to every conv in
+// that project.
+// - On the commander (new-chat) panel, the chip reads the current
+// project pick from `getCommanderProjectId()` (managed by
+// modules/projects.js / conversation.js commander chip). When the
+// commander has no project picked, scope falls back to default.
//
// Depends on: ipc-shim.js (apiFetch / window.orkas.invoke)
const _wsLog = createLogger('user-workspace');
-/** Cached workspace info. */
-let _wsInfo = { currentPath: '', defaultPath: '', isDefault: true, recentPaths: [] };
+/** Cached workspace info, keyed by chip target. The chip on the conversation
+ * panel and the chip on the commander panel may show different paths when
+ * they resolve to different scopes (e.g. conv belongs to project A, commander
+ * has project B picked). */
+const _wsInfoByTarget = {
+ 'new-chat': { currentPath: '', defaultPath: '', isDefault: true, recentPaths: [], scope: 'default' },
+ 'conversation': { currentPath: '', defaultPath: '', isDefault: true, recentPaths: [], scope: 'default' },
+};
// ── Workspace display helpers ───────────────────────────────────────
@@ -19,28 +35,62 @@ function _wsFolderName(fullPath) {
return parts[parts.length - 1] || fullPath;
}
-/** Update all workspace chip labels on the page. */
-function _updateAllChips() {
- const name = _wsFolderName(_wsInfo.currentPath);
- const chips = document.querySelectorAll('.workspace-chip');
- for (const chip of chips) {
- const label = chip.querySelector('.workspace-chip-label');
- if (label) label.textContent = name;
- chip.title = _wsInfo.currentPath || t('workspace.chip_title');
+/** Build the scope hint payload for a given chip target. The conversation
+ * panel passes `cid` (main resolves cid → conv.project_id); the commander
+ * panel passes `projectId` from the current commander chip pick. */
+function _wsScopeHintFor(target) {
+ if (target === 'conversation') {
+ return currentCid ? { cid: currentCid } : {};
+ }
+ // new-chat / commander panel
+ if (typeof getCommanderProjectId === 'function') {
+ const pid = getCommanderProjectId();
+ if (pid) return { projectId: pid };
}
+ return {};
+}
+
+/** Update workspace chip label for one or both targets. */
+function _updateChipForTarget(target) {
+ const info = _wsInfoByTarget[target] || _wsInfoByTarget['conversation'];
+ const sel = target === 'new-chat'
+ ? '#panel-new-chat .workspace-chip'
+ : '#panel-conversation .workspace-chip';
+ const chip = document.querySelector(sel);
+ if (!chip) return;
+ const label = chip.querySelector('.workspace-chip-label');
+ if (label) label.textContent = _wsFolderName(info.currentPath);
+ // Tooltip carries the full path + scope context (project vs default).
+ let tooltip = info.currentPath || t('workspace.chip_title');
+ if (info.scope === 'project' && typeof getCommanderProjectIdName === 'function') {
+ // Resolve a friendly project name when available; fallback to the id.
+ const name = getCommanderProjectIdName(info.projectId);
+ if (name) tooltip += ` · ${t('workspace.scope_project', { name })}`;
+ } else if (info.scope === 'project') {
+ tooltip += ` · ${t('workspace.scope_project_generic')}`;
+ }
+ chip.title = tooltip;
+}
+
+function _updateAllChips() {
+ _updateChipForTarget('new-chat');
+ _updateChipForTarget('conversation');
}
// ── Core actions ────────────────────────────────────────────────────
-async function _fetchWorkspaceInfo() {
+async function _fetchWorkspaceInfo(target) {
+ const hint = _wsScopeHintFor(target);
try {
- const result = await window.orkas.invoke('workspace.getInfo', {});
+ const result = await window.orkas.invoke('workspace.getInfo', hint);
if (result && result.ok) {
- _wsInfo = {
+ _wsInfoByTarget[target] = {
currentPath: result.currentPath || '',
defaultPath: result.defaultPath || '',
isDefault: !!result.isDefault,
recentPaths: result.recentPaths || [],
+ scope: result.scope || 'default',
+ ...(result.projectId ? { projectId: result.projectId } : {}),
};
}
} catch (err) {
@@ -48,7 +98,15 @@ async function _fetchWorkspaceInfo() {
}
}
-async function _selectAndSetWorkspace(dirPath) {
+/** Refetch info for both targets — called on boot, on commander chip change,
+ * and on conversation switch. */
+async function _refreshAllWorkspaceInfo() {
+ await Promise.all([_fetchWorkspaceInfo('new-chat'), _fetchWorkspaceInfo('conversation')]);
+ _updateAllChips();
+}
+
+async function _selectAndSetWorkspace(target, dirPath) {
+ const hint = _wsScopeHintFor(target);
try {
let selectedPath = dirPath;
if (!selectedPath) {
@@ -56,33 +114,33 @@ async function _selectAndSetWorkspace(dirPath) {
if (!dirResult || !dirResult.ok || !dirResult.path) return;
selectedPath = dirResult.path;
}
- const setResult = await window.orkas.invoke('workspace.set', { path: selectedPath });
+ const setResult = await window.orkas.invoke('workspace.set', { path: selectedPath, ...hint });
if (setResult && setResult.ok && setResult.path) {
- await _fetchWorkspaceInfo();
- _updateAllChips();
- _wsLog.info('workspace selected', setResult.path);
+ await _refreshAllWorkspaceInfo();
+ _wsLog.info('workspace selected', { target, path: setResult.path });
}
} catch (err) {
_wsLog.error('workspace selection failed', err);
}
}
-async function _resetWorkspace() {
+async function _resetWorkspace(target) {
+ const hint = _wsScopeHintFor(target);
try {
- const result = await window.orkas.invoke('workspace.reset', {});
+ const result = await window.orkas.invoke('workspace.reset', hint);
if (result && result.ok && result.path) {
- await _fetchWorkspaceInfo();
- _updateAllChips();
- _wsLog.info('workspace reset to default', result.path);
+ await _refreshAllWorkspaceInfo();
+ _wsLog.info('workspace reset', { target, path: result.path });
}
} catch (err) {
_wsLog.error('workspace reset failed', err);
}
}
-async function _openWorkspaceFolder() {
+async function _openWorkspaceFolder(target) {
+ const hint = _wsScopeHintFor(target);
try {
- const result = await window.orkas.invoke('workspace.openPath', {});
+ const result = await window.orkas.invoke('workspace.openPath', hint);
if (result && result.ok) {
_wsLog.info('workspace opened', result.path);
}
@@ -93,24 +151,26 @@ async function _openWorkspaceFolder() {
// ── Chip creation ───────────────────────────────────────────────────
-function _createWorkspaceChip() {
+function _createWorkspaceChip(target) {
const chip = document.createElement('button');
chip.type = 'button';
chip.className = 'workspace-chip';
- chip.title = _wsInfo.currentPath
- || (typeof t === 'function' ? t('workspace.chip_title') : 'Click to pick a workspace');
+ chip.dataset.wsTarget = target;
+ chip.title = (typeof t === 'function' ? t('workspace.chip_title') : 'Click to pick a workspace');
+ // Text-prefix layout matches the recipient / project chip pattern
+ // ("给:" / "项目:" / "工作区:") — the folder icon was replaced per UX
+ // feedback so all three left-side chips read as "[label]: [value]".
+ const prefix = (typeof t === 'function' ? t('workspace.chip_label') : 'Workspace: ');
chip.innerHTML =
- '<svg class="workspace-chip-icon" viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">' +
- '<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>' +
- '</svg>' +
- '<span class="workspace-chip-label">' + _wsFolderName(_wsInfo.currentPath) + '</span>' +
+ `<span class="workspace-chip-prefix">${escapeHtml(prefix)}</span>` +
+ '<span class="workspace-chip-label"></span>' +
'<svg class="workspace-chip-chevron" viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.5">' +
'<polyline points="6 9 12 15 18 9"/>' +
'</svg>';
chip.addEventListener('click', (e) => {
e.stopPropagation();
- _showWorkspaceDropdown(chip);
+ _showWorkspaceDropdown(chip, target);
});
return chip;
@@ -118,18 +178,17 @@ function _createWorkspaceChip() {
// ── Dropdown menu ───────────────────────────────────────────────────
-function _showWorkspaceDropdown(anchor) {
- // Remove any existing dropdown
+function _showWorkspaceDropdown(anchor, target) {
const old = document.getElementById('workspace-menu');
if (old) { old.remove(); return; }
+ const info = _wsInfoByTarget[target] || _wsInfoByTarget['conversation'];
+
const menu = document.createElement('div');
menu.id = 'workspace-menu';
menu.className = 'workspace-menu';
- // Flip chevron
- const chevron = anchor.querySelector('.workspace-chip-chevron');
- if (chevron) anchor.classList.add('workspace-chip--open');
+ anchor.classList.add('workspace-chip--open');
// ── Default section ──
const defaultHeader = document.createElement('div');
@@ -138,20 +197,19 @@ function _showWorkspaceDropdown(anchor) {
menu.appendChild(defaultHeader);
const defaultItem = _createMenuItem(
- _wsFolderName(_wsInfo.defaultPath),
- _wsInfo.isDefault,
- () => { _closeMenu(); _resetWorkspace(); }
+ _wsFolderName(info.defaultPath),
+ info.isDefault,
+ () => { _closeMenu(); _resetWorkspace(target); }
);
menu.appendChild(defaultItem);
// ── Recently section ──
- // If current is not default, show it first in recents with checkmark
const showRecents = [];
- if (!_wsInfo.isDefault) {
- showRecents.push({ path: _wsInfo.currentPath, active: true });
+ if (!info.isDefault) {
+ showRecents.push({ path: info.currentPath, active: true });
}
- for (const rp of _wsInfo.recentPaths) {
- if (rp !== _wsInfo.currentPath) {
+ for (const rp of (info.recentPaths || [])) {
+ if (rp !== info.currentPath) {
showRecents.push({ path: rp, active: false });
}
}
@@ -165,7 +223,7 @@ function _showWorkspaceDropdown(anchor) {
const item = _createMenuItem(
_wsFolderName(entry.path),
entry.active,
- entry.active ? () => { _closeMenu(); } : () => { _closeMenu(); _selectAndSetWorkspace(entry.path); }
+ entry.active ? () => { _closeMenu(); } : () => { _closeMenu(); _selectAndSetWorkspace(target, entry.path); }
);
item.title = entry.path;
menu.appendChild(item);
@@ -182,7 +240,7 @@ function _showWorkspaceDropdown(anchor) {
selectItem.textContent = t('workspace.pick_folder');
selectItem.addEventListener('click', () => {
_closeMenu();
- _selectAndSetWorkspace();
+ _selectAndSetWorkspace(target);
});
menu.appendChild(selectItem);
@@ -191,11 +249,10 @@ function _showWorkspaceDropdown(anchor) {
openItem.textContent = t('workspace.open_folder');
openItem.addEventListener('click', () => {
_closeMenu();
- _openWorkspaceFolder();
+ _openWorkspaceFolder(target);
});
menu.appendChild(openItem);
- // Position above the anchor
const rect = anchor.getBoundingClientRect();
menu.style.position = 'fixed';
menu.style.left = rect.left + 'px';
@@ -235,16 +292,30 @@ function _createMenuItem(text, isActive, onClick) {
// ── Init ────────────────────────────────────────────────────────────
async function initUserWorkspace() {
- await _fetchWorkspaceInfo();
-
- const toolbarIds = [
- '.new-chat-input-wrapper .chat-input-toolbar',
- '#panel-conversation .chat-input-toolbar',
- ];
- for (const sel of toolbarIds) {
- const toolbar = document.querySelector(sel);
- if (toolbar) {
- toolbar.appendChild(_createWorkspaceChip());
- }
+ // Insert one chip per panel into the bottom-bar (right of the recipient /
+ // project / skill chips, left of the send button). Mirroring the recipient
+ // chip's lifecycle so visuals stay consistent across panels.
+ const newBar = document.querySelector('#panel-new-chat .chat-bottom-bar');
+ if (newBar) {
+ const sendBtn = newBar.querySelector('.chat-send-btn');
+ const chip = _createWorkspaceChip('new-chat');
+ if (sendBtn) newBar.insertBefore(chip, sendBtn);
+ else newBar.appendChild(chip);
}
+ const convBar = document.querySelector('#panel-conversation .chat-bottom-bar');
+ if (convBar) {
+ const sendBtn = convBar.querySelector('.chat-send-btn');
+ const chip = _createWorkspaceChip('conversation');
+ if (sendBtn) convBar.insertBefore(chip, sendBtn);
+ else convBar.appendChild(chip);
+ }
+
+ await _refreshAllWorkspaceInfo();
+}
+
+/** Public: called by conversation.js when the active cid changes (entering a
+ * conversation, or switching tabs while one is mounted). Also called by
+ * projects.js when the commander chip's project pick changes. */
+async function refreshWorkspaceChip() {
+ await _refreshAllWorkspaceInfo();
}
diff --git a/src/renderer/style.css b/src/renderer/style.css
index 792315aa..b72e5447 100644
--- a/src/renderer/style.css
+++ b/src/renderer/style.css
@@ -400,6 +400,35 @@ body {
margin-top: 4px;
}
+/* Projects section sits on top of conversations; let it stay intrinsic-sized
+ (rows are short, even ~20 projects fit in a small slab) while the
+ conversations section underneath takes the remaining height. Cap so a user
+ with dozens of projects doesn't push the conv list off-screen — internal
+ scroll engages. */
+.sidebar-projects-section {
+ flex: 0 0 auto;
+ max-height: 40vh;
+ border-top: 1px solid var(--border);
+}
+
+/* Conversations section under Projects — share the same conceptual area as
+ Projects (per UX feedback "可以认为是同样的区域"). The divider stays as
+ a hairline visual cue but in a much lighter tone so the two sections
+ read as related rather than partitioned. Falls back to var(--border)
+ on platforms / themes where the muted variant isn't defined. */
+.sidebar-conversations-section {
+ flex: 1 1 auto;
+ border-top: 1px solid rgba(15, 23, 42, 0.05);
+ margin-top: 0;
+}
+
+.sidebar-section-title-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 12px 4px 6px;
+}
+
.sidebar-section-title {
padding: 12px 4px 6px;
font-size: 11px;
@@ -409,6 +438,137 @@ body {
color: #9ca3af;
}
+/* When the title sits inside a row, its own padding is owned by the row;
+ collapse the per-element padding so the row's vertical rhythm stays clean. */
+.sidebar-section-title-row .sidebar-section-title { padding: 0 4px; }
+
+.sidebar-section-add {
+ border: none;
+ background: transparent;
+ color: #94a3b8;
+ cursor: pointer;
+ width: 22px;
+ height: 22px;
+ border-radius: 4px;
+ font-size: 18px;
+ line-height: 1;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ font-family: inherit;
+ transition: background 0.12s, color 0.12s;
+}
+.sidebar-section-add:hover { background: #f1f5f9; color: var(--text); }
+
+/* ─── Projects list ─── */
+
+.projects-list {
+ flex: 1;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ padding-right: 2px;
+}
+.projects-list::-webkit-scrollbar { width: 4px; }
+.projects-list::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.1); border-radius: 3px; }
+
+.project-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 7px 8px;
+ border-radius: 7px;
+ cursor: pointer;
+ color: #374151;
+ font-size: 13px;
+ line-height: 1.35;
+ transition: background 0.12s;
+ position: relative;
+}
+.project-row:hover { background: #f1f5f9; color: var(--text); }
+.project-row.is-menu-open { background: #f1f5f9; }
+
+.project-icon {
+ flex-shrink: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 18px;
+ color: #94a3b8;
+}
+/* Make sure clicks on the SVG / its paths bubble cleanly to .project-row's
+ click handler (otherwise nested <path> targets can confuse `closest()`
+ queries downstream). The icon itself is purely decorative — collapse /
+ expand is driven by clicking anywhere on the row except the menu /
+ rename input. */
+.project-icon svg { pointer-events: none; }
+
+.project-name {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.project-rename-input {
+ flex: 1;
+ min-width: 0;
+ border: 1px solid var(--primary);
+ background: #fff;
+ color: var(--text);
+ font-size: 13px;
+ padding: 2px 6px;
+ border-radius: 4px;
+ font-family: inherit;
+ outline: none;
+}
+.project-rename-input.is-error { border-color: #dc2626; box-shadow: 0 0 0 2px rgba(220,38,38,0.12); }
+
+.project-inline-error {
+ font-size: 11px;
+ color: #dc2626;
+ padding: 2px 8px 4px 26px; /* align below the name (caret + icon offset) */
+ line-height: 1.3;
+}
+
+/* ⋯ button styling: hidden by default, surfaces on row hover or while the
+ menu is open. Mirrors the KB tree pattern (.ctx-row-menu-btn). */
+.project-row-menu-btn {
+ visibility: hidden;
+}
+.project-row:hover .project-row-menu-btn,
+.project-row.is-menu-open .project-row-menu-btn {
+ visibility: visible;
+}
+
+/* Nested conv items inside a project — slight indent so the hierarchy reads. */
+.project-conv-list {
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ padding-left: 16px;
+}
+.conv-item-nested { font-size: 12.5px; padding: 5px 8px; }
+.project-conv-empty {
+ padding: 4px 8px 8px 16px;
+ font-size: 11.5px;
+ color: #94a3b8;
+}
+
+/* Danger-styled confirm modal ornaments. */
+.ui-dialog-title {
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--text);
+ margin-bottom: 8px;
+}
+.ui-dialog-danger .ui-dialog-message {
+ white-space: pre-wrap;
+ color: #475569;
+}
+
.conversation-list {
flex: 1;
overflow-y: auto;
@@ -1614,10 +1774,8 @@ body.model-not-configured .main-content { flex-direction: column; }
padding: 7px 16px;
box-shadow: 0 8px 32px rgba(15, 23, 42, 0.1);
transition: all 0.2s;
- /* Anchor for the absolutely-positioned `.chat-input-toolbar` (workspace
- chip floats above the right shoulder of this box). Decouples the chip
- from the attachments row so adding/removing attachments never shifts
- the chip's vertical position. */
+ /* Anchor for the absolutely-positioned `.chat-input-overlay` (attachments
+ strip floats above this box). Plan rail lives inside the overlay too. */
position: relative;
}
@@ -1730,16 +1888,14 @@ body.model-not-configured .main-content { flex-direction: column; }
.chat-send-btn.streaming .stop-icon { display: block; }
/* Queue panel above the input area.
- Aligned with .chat-input-area's centered 80% layout BUT with the right
- edge shrunken to clear the workspace chip floating above the input
- bubble (chip is anchored to input-area's right shoulder, up to ~218px
- wide; without this it overlaps the queue's bottom-right corner). The
- shared `--ws-chip-reserve` lives next to `.chat-input-overlay` so any
- future chip-width tweak only needs one site update. */
+ Aligned with .chat-input-area's centered 80% layout. The workspace chip
+ no longer floats above the input bubble (it moved into .chat-bottom-bar
+ inside the input area), so the queue's right edge can use the full 80%
+ width without a reserved gutter. */
.chat-queue {
pointer-events: auto;
width: 80%;
- max-width: max(160px, calc(80% - var(--ws-chip-reserve, 232px)));
+ max-width: 80%;
margin: 0 0 8px 10%;
background: rgba(255, 255, 255, 0.96);
backdrop-filter: blur(6px);
@@ -1749,17 +1905,15 @@ body.model-not-configured .main-content { flex-direction: column; }
box-shadow: 0 6px 20px rgba(15, 23, 42, 0.08);
}
-/* Plan-rail pill chip floats above the input bubble's LEFT shoulder, the
- mirror of the workspace chip on the right. When a plan exists,
- plan-rail.js stamps `has-plan-rail` on .chat-input-wrapper; reserve
- ~188px on the queue's left so the chip clears the queue's bottom-left.
- Symmetric to the right-side workspace reserve above. */
+/* Plan-rail pill chip still floats above the input bubble's LEFT shoulder
+ (the workspace chip moved into the bottom-bar but the plan rail stayed
+ in the overlay because it expands UPWARD over chat-history). When a
+ plan exists, plan-rail.js stamps `has-plan-rail` on .chat-input-wrapper;
+ reserve ~188px on the queue's left so the chip clears the queue's
+ bottom-left. */
.chat-input-wrapper.has-plan-rail .chat-queue {
margin-left: calc(10% + var(--plan-rail-reserve, 188px));
- max-width: max(
- 120px,
- calc(80% - var(--ws-chip-reserve, 232px) - var(--plan-rail-reserve, 188px))
- );
+ max-width: calc(80% - var(--plan-rail-reserve, 188px));
}
/* Narrower panels (skill / agent edit) don't have the 80%-centered shape
@@ -1938,10 +2092,14 @@ body.model-not-configured .main-content { flex-direction: column; }
color: #334155;
}
-/* Bottom row inside the input area: [+] [agent] [skill] [chip] ... [send] */
+/* Bottom row inside the input area: [+] [recipient] [project] [skill]
+ [workspace] ... [send]. Wraps row-by-row on narrow windows so chips
+ never overflow the input box. */
.chat-bottom-bar {
display: flex;
align-items: center;
+ flex-wrap: wrap;
+ row-gap: 6px;
gap: 8px;
width: 100%;
}
@@ -2900,26 +3058,16 @@ body.model-not-configured .main-content { flex-direction: column; }
50% { opacity: 0.5; }
}
-/* ─── Skill picker (used by chat inputs) ─── */
-
-.chat-input-toolbar {
- pointer-events: auto;
- display: flex;
- gap: 6px;
-}
-
-/* Overlay strip floating above the input bubble. Holds the attachments
- chips (left, wrap-aware) and the workspace toolbar (right, intrinsic).
- Absolutely positioned so it doesn't push the input box; anchored to
- input-area's top via translateY based on the strip's own height — the
- strip's bottom edge is always 6px above input-area's top, regardless
- of how many attachment rows wrap inside. The workspace chip therefore
- never shifts when attachments are added/removed.
+/* Overlay strip floating above the input bubble. Now holds attachments
+ only (and the plan-rail in the conversation panel, which is itself
+ absolutely positioned and anchors left). The workspace chip moved into
+ `.chat-bottom-bar` next to the recipient/project chips, so this strip's
+ geometry simplified — attachments take the full width and wrap freely;
+ no right-side reservation needed.
- align-items:flex-end keeps the workspace chip anchored to the strip's
- bottom edge (= input-area top - 6px) on all wrap counts; min-width:0 on
- the attachments child lets flex actually shrink it so chips wrap
- instead of pushing the toolbar off the right edge. */
+ `pointer-events: none` on the wrapper keeps clicks falling through to
+ the input box while still letting individual chip children (which set
+ `pointer-events: auto` via .chat-attachments) receive hits. */
.chat-input-overlay {
position: absolute;
top: 0;
@@ -2937,11 +3085,6 @@ body.model-not-configured .main-content { flex-direction: column; }
min-width: 0;
}
-.chat-input-overlay > .chat-input-toolbar {
- flex: 0 0 auto;
- margin-left: auto;
-}
-
.chat-skill-btn,
.chat-toolbar-btn {
@@ -3017,6 +3160,55 @@ body.model-not-configured .main-content { flex-direction: column; }
white-space: nowrap;
}
+/* Project chip on the commander tab (right of recipient chip). Visually
+ matches the workspace chip — solid white pill with a hairline border
+ and a chevron — so the two "secondary picker" chips read as a pair.
+ Distinguishes from the recipient chip (filled blue, primary action) by
+ surface, and from each other only by content. Both open a popover. */
+.chat-project-chip {
+ flex-shrink: 0;
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px 10px;
+ background: rgba(255, 255, 255, 0.9);
+ backdrop-filter: blur(6px);
+ border: 1px solid var(--border);
+ color: var(--text);
+ border-radius: 14px;
+ font-size: 12px;
+ font-weight: 500;
+ line-height: 1.4;
+ cursor: pointer;
+ font-family: inherit;
+ transition: all 0.15s;
+}
+.chat-project-chip:hover,
+.chat-project-chip.chat-project-chip--open {
+ border-color: rgba(37, 99, 235, 0.25);
+ background: #fff;
+}
+.chat-project-chip .chat-project-prefix {
+ color: var(--muted);
+ font-weight: 400;
+ white-space: nowrap;
+}
+.chat-project-chip .chat-project-name {
+ max-width: 160px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--text);
+}
+.chat-project-chevron {
+ flex-shrink: 0;
+ color: var(--muted);
+ transition: transform 0.2s;
+}
+.chat-project-chip.chat-project-chip--open .chat-project-chevron {
+ transform: rotate(180deg);
+}
+
.chat-skill-chip .chip-label {
max-width: 160px;
overflow: hidden;
@@ -3052,17 +3244,20 @@ body.model-not-configured .main-content { flex-direction: column; }
background: rgba(255, 255, 255, 0.9);
backdrop-filter: blur(6px);
color: var(--text);
- font-size: 13px;
+ font-size: 12px;
font-weight: 500;
- padding: 5px 10px;
- border-radius: 16px;
+ padding: 4px 10px;
+ border-radius: 14px;
cursor: pointer;
font-family: inherit;
transition: all 0.15s;
display: inline-flex;
align-items: center;
- gap: 5px;
- margin-left: auto;
+ gap: 4px;
+ /* No `margin-left: auto` — the chip used to be pushed to the right edge
+ of the bottom-bar (where the floating-overlay version lived). Now the
+ bottom-bar layout is `[+] [给:] [项目:] [工作区:] … [send]` and `+send`
+ itself owns the right-pin via its own `margin-left: auto`. */
}
.workspace-chip:hover {
@@ -3070,9 +3265,10 @@ body.model-not-configured .main-content { flex-direction: column; }
background: #fff;
}
-.workspace-chip-icon {
- flex-shrink: 0;
+.workspace-chip-prefix {
color: var(--muted);
+ font-weight: 400;
+ white-space: nowrap;
}
.workspace-chip-label {
@@ -3080,6 +3276,7 @@ body.model-not-configured .main-content { flex-direction: column; }
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
+ color: var(--text);
}
.workspace-chip-chevron {
diff --git a/test/main/features/chats.test.ts b/test/main/features/chats.test.ts
index 7e062a47..8c21b832 100644
--- a/test/main/features/chats.test.ts
+++ b/test/main/features/chats.test.ts
@@ -60,6 +60,27 @@ describe('chats › createConversation', () => {
expect(fs.existsSync(path.join(tmpDir, TEST_UID, 'cloud', 'chats', `${conv.conversation_id}.jsonl`)))
.toBe(true);
});
+
+ // Project membership wiring (added with the projects feature). The field
+ // is persisted on the conv record only — `<cid>.jsonl` / session_id /
+ // groupChatDir paths are unchanged (CLAUDE.md §5 invariant). When a
+ // projectId is omitted the record must NOT carry a stale empty string.
+ it('persists project_id when supplied; omits the field when absent', async () => {
+ const chats = await loadChats();
+ const c1 = await chats.createConversation(TEST_UID, { projectId: 'p_aabbccdd' });
+ expect(c1.project_id).toBe('p_aabbccdd');
+ // session_id MUST stay independent of project_id.
+ expect(c1.session_id).toBe(`${TEST_UID}-gconv-${c1.conversation_id}`);
+ const c2 = await chats.createConversation(TEST_UID);
+ expect(c2.project_id).toBeUndefined();
+
+ const idx = JSON.parse(fs.readFileSync(
+ path.join(tmpDir, TEST_UID, 'cloud', 'chats', '_index.json'), 'utf-8'));
+ const persistedC1 = idx.find((c: any) => c.conversation_id === c1.conversation_id);
+ const persistedC2 = idx.find((c: any) => c.conversation_id === c2.conversation_id);
+ expect(persistedC1.project_id).toBe('p_aabbccdd');
+ expect(persistedC2.project_id).toBeUndefined();
+ });
});
describe('chats › deleteConversation', () => {
diff --git a/test/main/features/projects.test.ts b/test/main/features/projects.test.ts
new file mode 100644
index 00000000..be9815d8
--- /dev/null
+++ b/test/main/features/projects.test.ts
@@ -0,0 +1,264 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+// Mock the model client so cascade-delete (which calls
+// `chats.deleteConversation`, which clears CLI sessions etc.) doesn't
+// accidentally try real LLM calls. Same stub pattern as chats.test.ts.
+vi.mock('../../../src/main/model/client', () => ({
+ async *streamChatWithModel(_opts: any) {
+ yield { type: 'final', text: '' };
+ yield { type: 'done' };
+ },
+ async chatWithModel() { return { ok: true, text: '', error: '', aborted: false }; },
+}));
+
+let tmpDir: string;
+let prevWs: string | undefined;
+const TEST_UID = 'uProj';
+
+beforeEach(async () => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-projects-'));
+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
+ vi.resetModules();
+ const users = await import('../../../src/main/features/users');
+ users.activateUser(TEST_UID);
+});
+
+afterEach(() => {
+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+async function loadProjects() {
+ return import('../../../src/main/features/projects');
+}
+async function loadChats() {
+ return import('../../../src/main/features/chats');
+}
+
+describe('projects › createProject', () => {
+ it('persists `_index.json` with name + project_id starting with p_', async () => {
+ const projects = await loadProjects();
+ const r = await projects.createProject(TEST_UID, ' My Project ');
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.project.project_id).toMatch(/^p_[0-9a-f]{8}$/);
+ expect(r.project.name).toBe('My Project'); // trimmed
+ expect(r.project.created_at).toBeTruthy();
+ expect(r.project.updated_at).toBe(r.project.created_at);
+ const idxFile = path.join(tmpDir, TEST_UID, 'cloud', 'projects', '_index.json');
+ const idx = JSON.parse(fs.readFileSync(idxFile, 'utf-8'));
+ expect(idx).toHaveLength(1);
+ expect(idx[0].project_id).toBe(r.project.project_id);
+ });
+
+ it('rejects empty / whitespace-only names with name_empty', async () => {
+ const projects = await loadProjects();
+ const r1 = await projects.createProject(TEST_UID, '');
+ expect(r1.ok).toBe(false);
+ if (!r1.ok) expect(r1.error).toBe('name_empty');
+ const r2 = await projects.createProject(TEST_UID, ' ');
+ expect(r2.ok).toBe(false);
+ if (!r2.ok) expect(r2.error).toBe('name_empty');
+ });
+
+ it('rejects case-insensitive duplicate names with name_dup', async () => {
+ const projects = await loadProjects();
+ const ok = await projects.createProject(TEST_UID, 'Alpha');
+ expect(ok.ok).toBe(true);
+
+ // Exact dup.
+ const dup1 = await projects.createProject(TEST_UID, 'Alpha');
+ expect(dup1.ok).toBe(false);
+ if (!dup1.ok) expect(dup1.error).toBe('name_dup');
+
+ // Case-insensitive dup.
+ const dup2 = await projects.createProject(TEST_UID, 'ALPHA');
+ expect(dup2.ok).toBe(false);
+ if (!dup2.ok) expect(dup2.error).toBe('name_dup');
+
+ // Whitespace-trimmed dup.
+ const dup3 = await projects.createProject(TEST_UID, ' alpha ');
+ expect(dup3.ok).toBe(false);
+ if (!dup3.ok) expect(dup3.error).toBe('name_dup');
+ });
+
+ it('per-user isolation: same name allowed across users', async () => {
+ const projects = await loadProjects();
+ const users = await import('../../../src/main/features/users');
+ users.activateUser('userA');
+ const a = await projects.createProject('userA', 'Shared');
+ expect(a.ok).toBe(true);
+ users.activateUser('userB');
+ const b = await projects.createProject('userB', 'Shared');
+ expect(b.ok).toBe(true);
+ });
+});
+
+describe('projects › listProjects', () => {
+ it('returns conv_count derived from chats index', async () => {
+ const projects = await loadProjects();
+ const chats = await loadChats();
+ const p = await projects.createProject(TEST_UID, 'Proj');
+ if (!p.ok) throw new Error('precondition');
+ const pid = p.project.project_id;
+
+ await chats.createConversation(TEST_UID, { title: 'c1', projectId: pid });
+ await chats.createConversation(TEST_UID, { title: 'c2', projectId: pid });
+ await chats.createConversation(TEST_UID, { title: 'unprojected' });
+
+ const list = await projects.listProjects(TEST_UID);
+ expect(list).toHaveLength(1);
+ expect(list[0].project_id).toBe(pid);
+ expect(list[0].conv_count).toBe(2);
+ });
+
+ it('returns [] when no projects exist (does not crash on missing _index.json)', async () => {
+ const projects = await loadProjects();
+ const list = await projects.listProjects(TEST_UID);
+ expect(list).toEqual([]);
+ });
+});
+
+describe('projects › renameProject', () => {
+ it('updates name + bumps updated_at', async () => {
+ const projects = await loadProjects();
+ const p = await projects.createProject(TEST_UID, 'Old');
+ if (!p.ok) throw new Error('precondition');
+ // updated_at granularity is seconds — sleep one tick so the bump is observable.
+ await new Promise((r) => setTimeout(r, 1100));
+ const r = await projects.renameProject(TEST_UID, p.project.project_id, 'New');
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.project.name).toBe('New');
+ expect(r.project.updated_at >= p.project.updated_at).toBe(true);
+ });
+
+ it('rejects rename to existing other project name (case-insensitive) with name_dup', async () => {
+ const projects = await loadProjects();
+ const a = await projects.createProject(TEST_UID, 'Alpha');
+ const b = await projects.createProject(TEST_UID, 'Beta');
+ if (!a.ok || !b.ok) throw new Error('precondition');
+ const r = await projects.renameProject(TEST_UID, b.project.project_id, 'alpha');
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toBe('name_dup');
+ });
+
+ it('renaming to the SAME name (no change) is a no-op success, not name_dup', async () => {
+ const projects = await loadProjects();
+ const p = await projects.createProject(TEST_UID, 'Same');
+ if (!p.ok) throw new Error('precondition');
+ const r = await projects.renameProject(TEST_UID, p.project.project_id, 'Same');
+ expect(r.ok).toBe(true);
+ if (r.ok) expect(r.project.name).toBe('Same');
+ });
+
+ it('rejects with not_found when projectId does not exist', async () => {
+ const projects = await loadProjects();
+ const r = await projects.renameProject(TEST_UID, 'p_deadbeef', 'X');
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toBe('not_found');
+ });
+});
+
+describe('projects › deleteProject', () => {
+ it('cascades: every conv with project_id is dropped + project record removed', async () => {
+ const projects = await loadProjects();
+ const chats = await loadChats();
+ const p = await projects.createProject(TEST_UID, 'Cascade');
+ if (!p.ok) throw new Error('precondition');
+ const pid = p.project.project_id;
+ const c1 = await chats.createConversation(TEST_UID, { projectId: pid });
+ const c2 = await chats.createConversation(TEST_UID, { projectId: pid });
+ const cOuter = await chats.createConversation(TEST_UID); // unprojected — must NOT be dropped
+
+ const r = await projects.deleteProject(TEST_UID, pid);
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.deleted_convs).toBe(2);
+
+ const remaining = await chats.listConversations(TEST_UID);
+ const ids = remaining.map((c) => c.conversation_id).sort();
+ expect(ids).toEqual([cOuter.conversation_id]);
+
+ // Project record gone.
+ const list = await projects.listProjects(TEST_UID);
+ expect(list).toEqual([]);
+
+ // Per-conv jsonl files for c1/c2 dropped (cascade actually deletes).
+ expect(fs.existsSync(path.join(tmpDir, TEST_UID, 'cloud', 'chats', `${c1.conversation_id}.jsonl`))).toBe(false);
+ expect(fs.existsSync(path.join(tmpDir, TEST_UID, 'cloud', 'chats', `${c2.conversation_id}.jsonl`))).toBe(false);
+ });
+
+ it('refuses with has_running_conv when any owned conv is `running`', async () => {
+ const projects = await loadProjects();
+ const chats = await loadChats();
+ const { setStatus } = await import('../../../src/main/features/group_chat/state');
+ const p = await projects.createProject(TEST_UID, 'Busy');
+ if (!p.ok) throw new Error('precondition');
+ const pid = p.project.project_id;
+ const c = await chats.createConversation(TEST_UID, { projectId: pid });
+ await setStatus(TEST_UID, c.conversation_id, 'running');
+
+ const r = await projects.deleteProject(TEST_UID, pid);
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toBe('has_running_conv');
+
+ // Project + conv must still be present (refusal should not partially delete).
+ const list = await projects.listProjects(TEST_UID);
+ expect(list).toHaveLength(1);
+ const convs = await chats.listConversations(TEST_UID);
+ expect(convs.find((x) => x.conversation_id === c.conversation_id)).toBeDefined();
+ });
+
+ it('purges per-project workspace selection from workspace.json', async () => {
+ const projects = await loadProjects();
+ const ws = await import('../../../src/main/features/user_workspace');
+ const p = await projects.createProject(TEST_UID, 'WithWs');
+ if (!p.ok) throw new Error('precondition');
+ const pid = p.project.project_id;
+
+ const dir = path.join(tmpDir, 'project-ws');
+ fs.mkdirSync(dir, { recursive: true });
+ const setRes = ws.setWorkspacePath(TEST_UID, dir, pid);
+ expect(setRes.ok).toBe(true);
+
+ // Sanity: workspace.json now has the project bucket.
+ const cfgFile = path.join(tmpDir, TEST_UID, 'local', 'workspace.json');
+ const before = JSON.parse(fs.readFileSync(cfgFile, 'utf-8'));
+ expect(before.projects?.[pid]?.selectedPath).toBe(dir);
+
+ const r = await projects.deleteProject(TEST_UID, pid);
+ expect(r.ok).toBe(true);
+
+ const after = JSON.parse(fs.readFileSync(cfgFile, 'utf-8'));
+ expect(after.projects?.[pid]).toBeUndefined();
+ });
+
+ it('returns not_found for unknown projectId without touching anything', async () => {
+ const projects = await loadProjects();
+ const chats = await loadChats();
+ await chats.createConversation(TEST_UID, { title: 'untouched' });
+
+ const r = await projects.deleteProject(TEST_UID, 'p_deadbeef');
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toBe('not_found');
+
+ const convs = await chats.listConversations(TEST_UID);
+ expect(convs).toHaveLength(1);
+ });
+});
+
+describe('projects › projectExists', () => {
+ it('true for known pid, false for unknown / empty', async () => {
+ const projects = await loadProjects();
+ const p = await projects.createProject(TEST_UID, 'X');
+ if (!p.ok) throw new Error('precondition');
+ expect(await projects.projectExists(TEST_UID, p.project.project_id)).toBe(true);
+ expect(await projects.projectExists(TEST_UID, 'p_nosuch00')).toBe(false);
+ expect(await projects.projectExists(TEST_UID, '')).toBe(false);
+ });
+});
diff --git a/test/main/features/user_workspace.test.ts b/test/main/features/user_workspace.test.ts
index 33f3a4d9..ee1286ff 100644
--- a/test/main/features/user_workspace.test.ts
+++ b/test/main/features/user_workspace.test.ts
@@ -164,6 +164,134 @@ describe('user_workspace › selectDirectory (mocked)', () => {
});
});
+// ── Scoped workspace (default vs per-project) — added with the projects
+// feature. workspace.json moved from flat
+// `{selectedPath, recentPaths, updatedAt}` → scoped
+// `{default:{...}, projects:{<pid>:{...}}, updatedAt}`. Legacy flat is
+// promoted into `default` on first read; project scope falls back to
+// default when not set; deleting a project must remove its bucket.
+describe('user_workspace › scoped (projects)', () => {
+ it('legacy flat config is promoted into `default` on first read', async () => {
+ const ws = await import('../../../src/main/features/user_workspace');
+ const cfgFile = path.join(tmpDir, 'userMig', 'local', 'workspace.json');
+ fs.mkdirSync(path.dirname(cfgFile), { recursive: true });
+ const dir = path.join(tmpDir, 'legacy-ws');
+ fs.mkdirSync(dir, { recursive: true });
+ // Hand-craft a legacy flat shape (pre-projects schema).
+ fs.writeFileSync(cfgFile, JSON.stringify({
+ selectedPath: dir,
+ updatedAt: '2026-01-01T00:00:00',
+ recentPaths: [],
+ }));
+ // Default scope must read the promoted value back.
+ expect(ws.getWorkspacePath('userMig')).toBe(dir);
+ // Trigger a write so the file is rewritten in scoped shape, then
+ // assert the on-disk schema upgraded.
+ const dir2 = path.join(tmpDir, 'legacy-ws2');
+ fs.mkdirSync(dir2, { recursive: true });
+ const r = ws.setWorkspacePath('userMig', dir2);
+ expect(r.ok).toBe(true);
+ const after = JSON.parse(fs.readFileSync(cfgFile, 'utf-8'));
+ expect(after.default.selectedPath).toBe(dir2);
+ // Legacy `selectedPath` at the root is gone — value lives under
+ // `default` now.
+ expect(after.selectedPath).toBeUndefined();
+ expect(after.projects).toEqual({});
+ });
+
+ it('project scope falls through to default when no project selection is set', async () => {
+ const ws = await import('../../../src/main/features/user_workspace');
+ const defaultDir = path.join(tmpDir, 'def-ws');
+ fs.mkdirSync(defaultDir, { recursive: true });
+ ws.setWorkspacePath('userScope', defaultDir);
+ // No call yet for projectId='p_aaaa1111' → effective path is the
+ // default selection (which itself falls through to DEFAULT_USER_WORKSPACE
+ // only when default is also unset).
+ expect(ws.getWorkspacePath('userScope', 'p_aaaa1111')).toBe(defaultDir);
+ });
+
+ it('project scope wins over default when explicitly set', async () => {
+ const ws = await import('../../../src/main/features/user_workspace');
+ const defaultDir = path.join(tmpDir, 'def');
+ const projDir = path.join(tmpDir, 'proj');
+ fs.mkdirSync(defaultDir, { recursive: true });
+ fs.mkdirSync(projDir, { recursive: true });
+
+ ws.setWorkspacePath('userScope2', defaultDir);
+ ws.setWorkspacePath('userScope2', projDir, 'p_b0b0');
+
+ expect(ws.getWorkspacePath('userScope2')).toBe(defaultDir);
+ expect(ws.getWorkspacePath('userScope2', 'p_b0b0')).toBe(projDir);
+ });
+
+ it('per-scope recents are independent', async () => {
+ const ws = await import('../../../src/main/features/user_workspace');
+ const defA = path.join(tmpDir, 'defA');
+ const defB = path.join(tmpDir, 'defB');
+ const projA = path.join(tmpDir, 'projA');
+ const projB = path.join(tmpDir, 'projB');
+ [defA, defB, projA, projB].forEach((d) => fs.mkdirSync(d, { recursive: true }));
+
+ ws.setWorkspacePath('userR', defA);
+ ws.setWorkspacePath('userR', defB); // defA → default.recents
+ ws.setWorkspacePath('userR', projA, 'p_recents');
+ ws.setWorkspacePath('userR', projB, 'p_recents'); // projA → projects[p_recents].recents
+
+ const defInfo = ws.getWorkspaceInfo('userR');
+ const projInfo = ws.getWorkspaceInfo('userR', 'p_recents');
+ expect(defInfo.recentPaths).toContain(defA);
+ expect(defInfo.recentPaths).not.toContain(projA);
+ expect(projInfo.recentPaths).toContain(projA);
+ expect(projInfo.recentPaths).not.toContain(defA);
+ });
+
+ it('reset on project scope falls through to default; default scope intact', async () => {
+ const ws = await import('../../../src/main/features/user_workspace');
+ const defaultDir = path.join(tmpDir, 'reset-def');
+ const projDir = path.join(tmpDir, 'reset-proj');
+ fs.mkdirSync(defaultDir, { recursive: true });
+ fs.mkdirSync(projDir, { recursive: true });
+
+ ws.setWorkspacePath('userReset', defaultDir);
+ ws.setWorkspacePath('userReset', projDir, 'p_reset0');
+ expect(ws.getWorkspacePath('userReset', 'p_reset0')).toBe(projDir);
+
+ ws.resetWorkspacePath('userReset', 'p_reset0');
+ // Project scope now falls through to default.
+ expect(ws.getWorkspacePath('userReset', 'p_reset0')).toBe(defaultDir);
+ // Default scope unchanged.
+ expect(ws.getWorkspacePath('userReset')).toBe(defaultDir);
+ });
+
+ it('getWorkspaceInfo returns scope=project when projectId given, default otherwise', async () => {
+ const ws = await import('../../../src/main/features/user_workspace');
+ const defInfo = ws.getWorkspaceInfo('userS');
+ expect(defInfo.scope).toBe('default');
+ expect(defInfo.projectId).toBeUndefined();
+ const projInfo = ws.getWorkspaceInfo('userS', 'p_scope1');
+ expect(projInfo.scope).toBe('project');
+ expect(projInfo.projectId).toBe('p_scope1');
+ });
+
+ it('purgeProjectWorkspace removes only that project bucket', async () => {
+ const ws = await import('../../../src/main/features/user_workspace');
+ const dir1 = path.join(tmpDir, 'pwA');
+ const dir2 = path.join(tmpDir, 'pwB');
+ fs.mkdirSync(dir1, { recursive: true });
+ fs.mkdirSync(dir2, { recursive: true });
+ ws.setWorkspacePath('userPurge', dir1, 'p_keep');
+ ws.setWorkspacePath('userPurge', dir2, 'p_drop');
+
+ ws.purgeProjectWorkspace('userPurge', 'p_drop');
+
+ expect(ws.getWorkspacePath('userPurge', 'p_keep')).toBe(dir1);
+ // p_drop's bucket gone — falls through to default (which is unset →
+ // DEFAULT_USER_WORKSPACE).
+ const p = await import('../../../src/main/paths');
+ expect(ws.getWorkspacePath('userPurge', 'p_drop')).toBe(p.DEFAULT_USER_WORKSPACE);
+ });
+});
+
describe('user_workspace › openWorkspaceInFileManager', () => {
it('invokes shell.openPath with the current workspace directory', async () => {
const { shell } = await import('electron');