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.

feat: project scope — per-project agent/skill bindings + detail page + search grouping

wyta3610d581e6a
diff --git a/CLAUDE.md b/CLAUDE.md
index 350f2d44..564d6842 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -121,7 +121,7 @@ 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)
+ │ ├── projects/<pid>/{project.json, bindings.json} Logical groups of conversations + per-project agent/skill scope (no aggregate index — list = directory scan)
│ └── config/{preferences,component-enabled}.json
└── local/ 🔒 Machine-private domain (never synced)
├── config/ auth-profiles / permissions / reflection-state / web-search-cache
@@ -155,7 +155,7 @@ 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.
+**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. Project membership has effect in two places, both resolved once at the top of `runTurn` and threaded through `ChatOptions`: (1) **workspace** — `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`; (2) **agent/skill scope** — `projects.resolveProjectScope(uid, projectId)` returns the project's `bindings.json` (`{agents, skills}`), which restricts the commander's agents-index render and the System A skill render to those ids only. Orphan conversations (no `project_id`) keep legacy global visibility. group_chat threads `projectId` + `projectAllowedSkillIds` through `ChatOptions` → `LocalToolsOpts` / `FileToolsOpts` / `ImageGenToolOpts` / `getSystemPromptBlock`. **Do not** re-read the conv index or bindings per tool call — the resolved values travel 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.
@@ -228,10 +228,12 @@ Sources = `src/builtin/skills/` (git-tracked, hash-synced into `data/builtin/ski
**Per-user enable/disable** (shared by agent + skill, stored at `<uid>/cloud/config/component-enabled.json`, **only `false` is recorded**): the single resolver entrypoint is `features/component_enabled.ts::isAgentEnabled / isSkillEnabled`. **Only 4 filter application sites** (do not add filtering elsewhere):
1. `listAgents() / listSkills()` attaches `enabled` for the UI (no filtering — let the UI render the toggle).
-2. `chats.ts::_buildAgentsIndex` — agent picker list.
+2. `group_chat/bus.ts::buildAgentsIndexBlock` — commander's agent picker list.
3. `chats.ts::stream/sendToConversation` — bound disabled agents return `errors.agent_disabled` directly.
4. `skill-registry.getSystemPromptBlock({disabledIds})` — render-stage filtering.
+**Project scope** is the OUTER intersection — applied BEFORE the 4 enable filters above, NOT a 5th site. The two existing render entry points (`buildAgentsIndexBlock` for agents, `getSystemPromptBlock` for skills) accept an `allowedIds` / `allowlist` parameter; group_chat resolves `projects.resolveProjectScope(uid, projectId)` once at the top of `runTurn` and threads `bindings.agents` into the agent picker call and `bindings.skills` (intersected with `agent.skill_list` for the System A render only) via `ChatOptions.projectAllowedSkillIds`. SkillStore (System B, agent self-evolved skills) is gated by `skillList` alone — project bindings must NOT block an agent from accessing its own evolved skills. Order: `project bindings ∩ skill_list ∩ enabled` for System A; `skill_list ∩ enabled` for System B. Orphan conversations (no `project_id`) skip the project step entirely (legacy behavior).
+
**Write entry points** (rename / URL/dir import): see `features/skills.ts`. Every write entry must call `invalidateSkills()`. The `<<<skill-file>>>` block can only write into the current skill directory (no cross-skill `skill=Y` attribute).
**Two system boundaries (skills have two sets)**:
@@ -340,6 +342,8 @@ The renderer evaluates `<script>`-loaded files where `module` is undefined, so t
- 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.
+- Reintroduce an aggregate `projects/_index.json`. Project existence is the set of `projects/<pid>/project.json` files on disk; listing scans the directory. **Why:** an aggregate index re-creates the multi-device sync conflict surface this round was designed to avoid (every membership change becomes a multi-file transactional write), and once a server-mediated collab story lands, server-side sync of project directories is a directory-level operation — clients only ever scan. See `features/projects.ts` header.
+- Apply the project agent/skill scope as a 5th `component_enabled` filter site. Project scope is an OUTER intersection plumbed through the existing render entry points (`buildAgentsIndexBlock` `allowedIds` / `getSystemPromptBlock` `allowlist`) — see §6.
**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/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index 61fd4ff5..4ddf600c 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -734,6 +734,22 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
if (typeof _pid === 'string' && _pid) turnProjectId = _pid;
} catch { /* default scope */ }
+ // Project bindings (strict scope of agents/skills visible to the LLM).
+ // `null` = orphan conversation OR stale projectId — falls back to legacy
+ // global visibility. Resolved once per turn alongside the workspace
+ // resolver and threaded into commander prompt + agent skillList. See
+ // CLAUDE.md §6: project scope is the outer intersection BEFORE the 4
+ // enable-filter sites; do not add a 5th.
+ let turnProjectScope: import('../projects').ProjectBindings | null = null;
+ if (turnProjectId) {
+ try {
+ const projectsFeat = await import('../projects');
+ turnProjectScope = await projectsFeat.resolveProjectScope(uid, turnProjectId);
+ } catch (err) {
+ log.warn(`resolve project scope cid=${cid} pid=${turnProjectId}: ${(err as Error).message}`);
+ }
+ }
+
// First-turn replay: if the persistent session jsonl doesn't exist yet,
// prepend a `<group-chat-history>` block built from the visibility slice
// so the agent / commander has context. After the first turn, the
@@ -777,8 +793,12 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// Hoisted here so the branch below can read it without re-fetching.
let cliAgent: import('../agents').Agent | null = null;
if (isCommander) {
- systemPrompt = await buildCommanderSystemPrompt(uid, cid);
+ systemPrompt = await buildCommanderSystemPrompt(uid, cid, turnProjectScope?.agents ?? null);
extraTools = await buildCommanderExtraTools(state, w);
+ // skillList stays undefined for commander — the project filter is
+ // applied via `projectAllowedSkillIds` below so the runner can fold
+ // it into `getSystemPromptBlock`'s allowlist without disturbing
+ // SkillStore (System B; commander has none anyway).
} else {
const agent = await agentsFeat.getAgent(actor.id);
if (!agent) {
@@ -811,6 +831,11 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
systemPrompt = ''; // unused on CLI path
} else {
systemPrompt = await buildAgentInGroupSystemPrompt(uid, agent, workingDir);
+ // Pass agent.skill_list verbatim — it carries System A + System B
+ // ids the agent owns. The project filter is applied via
+ // `projectAllowedSkillIds` on the streamChatWithModel call so it
+ // only narrows the System A render block (`getSystemPromptBlock`),
+ // never blocks the agent's own evolved-skill SkillStore (System B).
skillList = Array.isArray(agent.skill_list) ? agent.skill_list : undefined;
}
}
@@ -972,6 +997,7 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
readOnlyExtraRoots: [...skillRoots, ...agentRoots],
...(extraTools.length ? { extraTools } : {}),
...(skillList !== undefined ? { skillList } : {}),
+ ...(turnProjectScope ? { projectAllowedSkillIds: turnProjectScope.skills } : {}),
})) {
// Stream events → process channel.
if (ev.type === 'final') {
@@ -1346,12 +1372,14 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// ── System prompts ───────────────────────────────────────────────────────
-async function buildCommanderSystemPrompt(uid: string, cid: string): Promise<string> {
+async function buildCommanderSystemPrompt(
+ uid: string, cid: string, allowedAgentIds?: readonly string[] | null,
+): Promise<string> {
const { prompts } = await import('../../prompts/loader');
const path_ = await import('node:path');
const paths_ = await import('../../paths');
const plan = await readPlan(uid, cid);
- const allAgentsList = await buildAgentsIndexBlock(uid);
+ const allAgentsList = await buildAgentsIndexBlock(uid, allowedAgentIds);
const { getConversationWorkspacePath } = await import('./conv_workspace');
const workingDir = await getConversationWorkspacePath(uid, cid);
const permState = (() => {
@@ -1429,7 +1457,13 @@ export async function _buildAgentsIndexBlockForTest(uid: string): Promise<string
return buildAgentsIndexBlock(uid);
}
-async function buildAgentsIndexBlock(uid: string): Promise<string> {
+/** Render the agents-index block. When `allowedIds` is provided, only those
+ * agent ids are rendered (project-scoped commander view). `null` /
+ * `undefined` = no filter (legacy global view, used for orphan
+ * conversations). Empty array = render `(no agents)` block — the project
+ * has zero bound agents. Unknown ids in the allowlist are silently
+ * dropped (loader is the source of truth). */
+async function buildAgentsIndexBlock(uid: string, allowedIds?: readonly string[] | null): Promise<string> {
const { getCurrentLang } = await import('../../i18n');
const { pickDescription } = await import('#core-agent');
const lang = getCurrentLang();
@@ -1443,7 +1477,10 @@ async function buildAgentsIndexBlock(uid: string): Promise<string> {
'',
].join('\n');
try {
- const list = (await agentsFeat.listAgents()).filter((a: any) => a.enabled !== false);
+ const allow = (allowedIds === null || allowedIds === undefined) ? null : new Set(allowedIds);
+ const list = (await agentsFeat.listAgents())
+ .filter((a: any) => a.enabled !== false)
+ .filter((a: any) => (allow ? allow.has(a.agent_id) : true));
if (!list.length) return `${header}(no agents)`;
const entries = list.map((a: any) => {
const name = a.name || a.agent_id;
diff --git a/src/main/features/projects.ts b/src/main/features/projects.ts
index 260b2dc1..7f35d9d1 100644
--- a/src/main/features/projects.ts
+++ b/src/main/features/projects.ts
@@ -1,20 +1,36 @@
/**
- * Projects — logical groups of conversations + a scoped workspace.
+ * Projects — logical groups of conversations + a strict scope of agents /
+ * skills the conversations inside the project can use.
*
- * 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: each project is a self-contained directory under
+ * `<uid>/cloud/projects/<pid>/` (cloud-synced):
+ * - `project.json` {project_id, name, owner_uid, timestamps}
+ * - `bindings.json` {agents: string[], skills: string[]} — id refs only,
+ * no spec body copy. Missing file = empty bindings.
*
- * 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).
+ * **No aggregate `_index.json`**. Listing scans `projects/<pid>/project.json`.
+ * **Why:** future server-mediated collaboration adds/removes a project from
+ * a user's view by writing/removing the per-pid directory; an aggregate
+ * index would force every membership change to be a multi-file
+ * transactional update and would conflict on multi-device sync. The
+ * directory's existence on disk is the single source of truth — see
+ * CLAUDE.md §4 / §9.
*
- * 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.
+ * **Membership of a conversation** is still recorded as a `project_id`
+ * field on the conv index entry (`features/chats.ts::Conversation`), NOT
+ * as a path component — `<cid>.jsonl` / `groupChatDir` / `session_id`
+ * paths stay verbatim, so cid uniqueness + §5 isolation are unaffected.
+ *
+ * **Scope semantics** (CLAUDE.md §6, outer intersection BEFORE the 4
+ * enable-filter sites):
+ * conversation in project P → only agents/skills in `bindings.json` are
+ * visible to the LLM. Orphan conversation (no project_id) → unchanged
+ * global visibility. `resolveProjectScope` is the single resolver
+ * threaded through the runTurn pipeline (alongside the workspace
+ * resolver) — do not re-read bindings per tool call.
+ *
+ * **Per-user enable/disable** still applies AFTER project bindings, via
+ * the existing 4 filter sites; do not add a 5th.
*/
import * as crypto from 'node:crypto';
@@ -22,7 +38,12 @@ 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 {
+ userProjectsDir,
+ projectDir,
+ projectMetaFile,
+ projectBindingsFile,
+} from '../paths';
import { nowIso, readJson, writeJson } from '../storage';
import { createLogger } from '../logger';
import * as chats from './chats';
@@ -34,22 +55,31 @@ const log = createLogger('projects');
export interface Project {
project_id: string;
name: string;
+ /** Reserved for future collaboration. Single-machine = active uid. */
+ owner_uid: string;
created_at: string;
updated_at: string;
}
-/** UI-extended project record: index entry + derived counts. */
+/** UI-extended project record: metadata + derived counts. */
export interface ProjectWithStats extends Project {
conv_count: number;
}
+/** Strict scope — only these ids are visible to the LLM inside the project.
+ * Empty arrays = "zero agents / zero skills" (intentional opt-out). */
+export interface ProjectBindings {
+ agents: string[];
+ skills: string[];
+}
+
// ── id helper ─────────────────────────────────────────────────────────────
function genProjectId(): string {
return 'p_' + crypto.randomBytes(6).toString('hex');
}
-// ── index IO ──────────────────────────────────────────────────────────────
+// ── filesystem helpers ────────────────────────────────────────────────────
function ensureProjectsDir(uid: string): string {
const d = userProjectsDir(uid);
@@ -57,18 +87,111 @@ function ensureProjectsDir(uid: string): string {
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 [];
+/** One-shot promotion of legacy `<uid>/cloud/projects/_index.json` to per-pid
+ * `project.json` files. Idempotent: bindings.json is NOT created (empty
+ * bindings on first read of any newly-promoted project — see plan: "no
+ * migration"). */
+async function _ensurePromoted(uid: string): Promise<void> {
+ const legacy = path.join(ensureProjectsDir(uid), '_index.json');
+ if (!fs.existsSync(legacy)) return;
+ let items: any[] = [];
+ try {
+ const data: any = await readJson(legacy);
+ if (Array.isArray(data)) items = data;
+ else if (data && Array.isArray(data.items)) items = data.items;
+ } catch (err) {
+ log.warn(`legacy _index.json read user=${uid}: ${(err as Error).message}`);
+ }
+ let promoted = 0;
+ for (const raw of items) {
+ if (!raw || typeof raw !== 'object') continue;
+ const pid = typeof raw.project_id === 'string' ? raw.project_id : '';
+ if (!pid) continue;
+ const meta = projectMetaFile(uid, pid);
+ if (fs.existsSync(meta)) continue;
+ try {
+ fs.mkdirSync(projectDir(uid, pid), { recursive: true });
+ await writeJson(meta, _normaliseProject(raw, uid, pid));
+ promoted += 1;
+ } catch (err) {
+ log.warn(`legacy promote pid=${pid} user=${uid}: ${(err as Error).message}`);
+ }
+ }
+ try { await fsp.unlink(legacy); }
+ catch (err) {
+ log.warn(`legacy _index.json unlink user=${uid}: ${(err as Error).message}`);
+ }
+ log.info(`legacy _index.json promoted user=${uid} count=${promoted}`);
+}
+
+async function _listProjectIds(uid: string): Promise<string[]> {
+ const dir = ensureProjectsDir(uid);
+ await _ensurePromoted(uid);
+ const out: string[] = [];
+ let entries: fs.Dirent[];
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
+ catch { return out; }
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ // Skip dotfiles / underscore-prefixed (reserved). Matches the
+ // contexts.ts `.kb` hidden-dir convention.
+ if (entry.name.startsWith('.') || entry.name.startsWith('_')) continue;
+ if (fs.existsSync(projectMetaFile(uid, entry.name))) out.push(entry.name);
+ }
+ return out;
+}
+
+function _normaliseProject(raw: any, uid: string, pid: string): Project {
+ const now = nowIso();
+ return {
+ project_id: typeof raw.project_id === 'string' ? raw.project_id : pid,
+ name: typeof raw.name === 'string' ? raw.name : '',
+ owner_uid: typeof raw.owner_uid === 'string' && raw.owner_uid ? raw.owner_uid : uid,
+ created_at: typeof raw.created_at === 'string' ? raw.created_at : now,
+ updated_at: typeof raw.updated_at === 'string' ? raw.updated_at : now,
+ };
+}
+
+async function _readProject(uid: string, pid: string): Promise<Project | null> {
+ const f = projectMetaFile(uid, pid);
+ if (!fs.existsSync(f)) return null;
+ try {
+ const raw: any = await readJson(f);
+ if (!raw || typeof raw !== 'object') return null;
+ return _normaliseProject(raw, uid, pid);
+ } catch (err) {
+ log.warn(`read project user=${uid} pid=${pid}: ${(err as Error).message}`);
+ return null;
+ }
+}
+
+async function _writeProject(uid: string, p: Project): Promise<void> {
+ fs.mkdirSync(projectDir(uid, p.project_id), { recursive: true });
+ await writeJson(projectMetaFile(uid, p.project_id), p);
}
-async function writeIndex(uid: string, items: Project[]): Promise<void> {
- await writeJson(userProjectsIndexFile(uid), items);
+function _normaliseBindings(raw: any): ProjectBindings {
+ if (!raw || typeof raw !== 'object') return { agents: [], skills: [] };
+ const filt = (arr: unknown): string[] =>
+ Array.isArray(arr) ? arr.filter((s) => typeof s === 'string' && !!s) as string[] : [];
+ return { agents: filt(raw.agents), skills: filt(raw.skills) };
+}
+
+async function _readBindings(uid: string, pid: string): Promise<ProjectBindings> {
+ const f = projectBindingsFile(uid, pid);
+ if (!fs.existsSync(f)) return { agents: [], skills: [] };
+ try {
+ const raw: any = await readJson(f);
+ return _normaliseBindings(raw);
+ } catch (err) {
+ log.warn(`read bindings user=${uid} pid=${pid}: ${(err as Error).message}`);
+ return { agents: [], skills: [] };
+ }
+}
+
+async function _writeBindings(uid: string, pid: string, b: ProjectBindings): Promise<void> {
+ fs.mkdirSync(projectDir(uid, pid), { recursive: true });
+ await writeJson(projectBindingsFile(uid, pid), b);
}
// ── Validation ────────────────────────────────────────────────────────────
@@ -84,9 +207,14 @@ function normName(raw: unknown): string | null {
return s;
}
-function isDuplicateName(items: Project[], name: string, excludePid?: string): boolean {
+async function _isDuplicateName(
+ uid: string, name: string, excludePid?: string,
+): Promise<boolean> {
+ const ids = await _listProjectIds(uid);
const lower = name.toLocaleLowerCase();
- for (const p of items) {
+ const projects = await Promise.all(ids.map((pid) => _readProject(uid, pid)));
+ for (const p of projects) {
+ if (!p) continue;
if (excludePid && p.project_id === excludePid) continue;
if ((p.name || '').toLocaleLowerCase() === lower) return true;
}
@@ -97,8 +225,12 @@ function isDuplicateName(items: Project[], name: string, excludePid?: string): b
/** 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 ids = await _listProjectIds(uid);
+ if (!ids.length) return [];
+ const projects = (await Promise.all(ids.map((pid) => _readProject(uid, pid))))
+ .filter((p): p is Project => p !== null);
+ // Newest first — matches the prior `items.unshift(project)` ordering.
+ projects.sort((a, b) => (b.created_at || '').localeCompare(a.created_at || ''));
const convs = await chats.listConversations(uid).catch(() => []);
const counts = new Map<string, number>();
for (const c of convs) {
@@ -111,8 +243,9 @@ export async function listProjects(uid: string): Promise<ProjectWithStats[]> {
/** 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;
+ if (!projectId) return null;
+ await _ensurePromoted(uid);
+ return _readProject(uid, projectId);
}
export type ProjectError = 'name_empty' | 'name_dup' | 'not_found' | 'has_running_conv';
@@ -123,17 +256,16 @@ export async function createProject(
): 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' };
+ if (await _isDuplicateName(uid, name)) return { ok: false, error: 'name_dup' };
const now = nowIso();
const project: Project = {
project_id: genProjectId(),
name,
+ owner_uid: uid,
created_at: now,
updated_at: now,
};
- items.unshift(project);
- await writeIndex(uid, items);
+ await _writeProject(uid, project);
log.info(`created user=${uid} pid=${project.project_id} name="${name}"`);
return { ok: true, project };
}
@@ -145,22 +277,20 @@ export async function renameProject(
): 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);
+ await _ensurePromoted(uid);
+ const cur = await _readProject(uid, projectId);
+ if (!cur) return { ok: false, error: 'not_found' };
+ if (await _isDuplicateName(uid, name, projectId)) return { ok: false, error: 'name_dup' };
+ if (cur.name === name) return { ok: true, project: cur }; // no-op
+ const next: Project = { ...cur, name, updated_at: nowIso() };
+ await _writeProject(uid, next);
log.info(`renamed user=${uid} pid=${projectId} name="${name}"`);
- return { ok: true, project: items[i] };
+ return { ok: true, project: next };
}
/** 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.
+ * group dir / cli sessions), then the project directory 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. */
@@ -168,9 +298,9 @@ 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' };
+ await _ensurePromoted(uid);
+ const cur = await _readProject(uid, projectId);
+ if (!cur) return { ok: false, error: 'not_found' };
const allConvs = await chats.listConversations(uid).catch(() => []);
const owned = allConvs.filter((c) => (c as any).project_id === projectId);
@@ -195,18 +325,15 @@ export async function deleteProject(
}
}
- // 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.
+ // Drop the entire project directory (project.json + bindings.json + any
+ // future per-project assets).
try {
- const d = path.join(userProjectsDir(uid), projectId);
+ const d = projectDir(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}`);
@@ -220,6 +347,85 @@ export async function deleteProject(
* 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);
+ await _ensurePromoted(uid);
+ return fs.existsSync(projectMetaFile(uid, projectId));
+}
+
+// ── Bindings: per-project agent / skill scope ────────────────────────────
+
+/** Read the project's bindings. Missing file or unknown project → empty.
+ * Unknown ids in the file are NOT filtered here — that is the caller's
+ * job (loaders are async). Missing project → returns empty so the LLM
+ * sees nothing rather than leaking global scope. */
+export async function getBindings(uid: string, projectId: string): Promise<ProjectBindings> {
+ if (!projectId) return { agents: [], skills: [] };
+ await _ensurePromoted(uid);
+ if (!fs.existsSync(projectMetaFile(uid, projectId))) return { agents: [], skills: [] };
+ return _readBindings(uid, projectId);
+}
+
+/** Single resolver, threaded through runTurn alongside the workspace lookup.
+ *
+ * - `null` = orphan conversation (no project_id) → no scope filter; legacy
+ * global-visibility behavior.
+ * - present project → returns its bindings (possibly empty arrays).
+ * - stale projectId (project deleted but conv lingers) → returns null so
+ * the LLM falls back to global visibility instead of "zero scope". */
+export async function resolveProjectScope(
+ uid: string,
+ projectId: string | null | undefined,
+): Promise<ProjectBindings | null> {
+ if (!projectId) return null;
+ await _ensurePromoted(uid);
+ if (!fs.existsSync(projectMetaFile(uid, projectId))) return null;
+ return _readBindings(uid, projectId);
+}
+
+async function _mutateBindings(
+ uid: string, projectId: string,
+ fn: (b: ProjectBindings) => ProjectBindings,
+): Promise<{ ok: true; bindings: ProjectBindings } | { ok: false; error: ProjectError }> {
+ await _ensurePromoted(uid);
+ if (!fs.existsSync(projectMetaFile(uid, projectId))) return { ok: false, error: 'not_found' };
+ const cur = await _readBindings(uid, projectId);
+ const next = fn(cur);
+ await _writeBindings(uid, projectId, next);
+ // Touch the project's updated_at so sidebar ordering reflects activity.
+ const p = await _readProject(uid, projectId);
+ if (p) await _writeProject(uid, { ...p, updated_at: nowIso() });
+ return { ok: true, bindings: next };
+}
+
+export async function addAgentBinding(
+ uid: string, projectId: string, agentId: string,
+): Promise<{ ok: true; bindings: ProjectBindings } | { ok: false; error: ProjectError }> {
+ if (!agentId) return { ok: false, error: 'not_found' };
+ return _mutateBindings(uid, projectId, (b) => (
+ b.agents.includes(agentId) ? b : { ...b, agents: [...b.agents, agentId] }
+ ));
+}
+
+export async function removeAgentBinding(
+ uid: string, projectId: string, agentId: string,
+): Promise<{ ok: true; bindings: ProjectBindings } | { ok: false; error: ProjectError }> {
+ return _mutateBindings(uid, projectId, (b) => (
+ { ...b, agents: b.agents.filter((id) => id !== agentId) }
+ ));
+}
+
+export async function addSkillBinding(
+ uid: string, projectId: string, skillId: string,
+): Promise<{ ok: true; bindings: ProjectBindings } | { ok: false; error: ProjectError }> {
+ if (!skillId) return { ok: false, error: 'not_found' };
+ return _mutateBindings(uid, projectId, (b) => (
+ b.skills.includes(skillId) ? b : { ...b, skills: [...b.skills, skillId] }
+ ));
+}
+
+export async function removeSkillBinding(
+ uid: string, projectId: string, skillId: string,
+): Promise<{ ok: true; bindings: ProjectBindings } | { ok: false; error: ProjectError }> {
+ return _mutateBindings(uid, projectId, (b) => (
+ { ...b, skills: b.skills.filter((id) => id !== skillId) }
+ ));
}
diff --git a/src/main/features/search/index.ts b/src/main/features/search/index.ts
index 6d910896..bff9eabb 100644
--- a/src/main/features/search/index.ts
+++ b/src/main/features/search/index.ts
@@ -175,6 +175,8 @@ export async function searchContexts(query: string, userId?: string): Promise<Se
const q = (query || '').trim();
if (!q) return [];
const uid = userId || getActiveUserId();
+ // See `searchChats` for why we reconcile per-query.
+ await indexer.reconcileContextsIndex(uid);
const entry = await indexer.getEntry(userContextsIndexPath(uid), 'context');
const tokens = tokenize(q);
const scores = _scoreIndex(entry.idx as RuntimeIndex, tokens);
@@ -195,37 +197,68 @@ export async function searchContexts(query: string, userId?: string): Promise<Se
export async function searchChats(userId: string, query: string): Promise<SearchResult[]> {
const q = (query || '').trim();
if (!q) return [];
+ // Per the file-header invariant ("every query first calls reconcileX"):
+ // reconcile picks up jsonl files that grew or were created since the last
+ // reconcile (boot or prior query). Bus does NOT live-index — without this
+ // call, conversations created after startup are unsearchable until the
+ // next boot. Cheap: one stat per chat jsonl + re-tokenize only for those
+ // whose mtime/size changed.
+ await indexer.reconcileChatsIndex(userId);
const entry = await indexer.getEntry(userChatsIndexPath(userId), 'chat');
const tokens = tokenize(q);
const scores = _scoreIndex(entry.idx as RuntimeIndex, tokens);
- // Conversation titles for display.
+ // Conversation display data: title + project membership. Read from
+ // `_index.json` once per query so each result row gets cheap O(1) lookups.
const indexFile = path.join(userChatsDir(userId), '_index.json');
const titles: Record<string, string> = {};
+ const cidToPid: Record<string, string> = {};
try {
if (fs.existsSync(indexFile)) {
const items = JSON.parse(fs.readFileSync(indexFile, 'utf8'));
const arr = Array.isArray(items) ? items : (items?.items || []);
- for (const c of arr) titles[c.conversation_id] = c.title || '';
+ for (const c of arr) {
+ titles[c.conversation_id] = c.title || '';
+ if (c.project_id) cidToPid[c.conversation_id] = c.project_id;
+ }
}
} catch { /* ignore */ }
+ // Project name lookup — cheap (a few file reads). Only build when at
+ // least one indexed conv has a project_id.
+ const pidToName: Record<string, string> = {};
+ if (Object.keys(cidToPid).length) {
+ try {
+ const projects = await import('../projects');
+ const list = await projects.listProjects(userId);
+ for (const p of list) pidToName[p.project_id] = p.name || '';
+ } catch { /* ignore — chip just won't show */ }
+ }
+
const cache = _makeSourceCache();
return _topN<SearchResult>(scores, MAX_PER_KIND, (docId, score) => {
const doc = entry.idx.docs[docId] as Doc & { cid?: string; msg_index?: number; role?: string; time?: string };
if (!doc) return null;
const file = path.join(userChatsDir(userId), `${doc.cid}.jsonl`);
const msg = cache.jsonlMessage(file, Number(doc.msg_index));
- return {
+ const cid = String(doc.cid);
+ const pid = cidToPid[cid] || '';
+ const result: SearchResult = {
kind: 'chat',
cid: doc.cid,
msg_index: doc.msg_index,
- conv_title: titles[String(doc.cid)] || t('chat.default_title'),
+ conv_title: titles[cid] || t('chat.default_title'),
role: doc.role,
time: doc.time,
snippet: _makeSnippet(indexer.readMsgText(msg as any), q),
score,
};
+ if (pid) {
+ (result as any).project_id = pid;
+ const name = pidToName[pid];
+ if (name) (result as any).project_name = name;
+ }
+ return result;
});
}
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts
index 0fc8ab10..2f0771e6 100644
--- a/src/main/ipc/index.ts
+++ b/src/main/ipc/index.ts
@@ -167,6 +167,91 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { deleted_convs: result.deleted_convs };
},
+ 'projects.get': async ({ projectId }, ctx) => {
+ if (!safeId(projectId)) throw new Error('invalid projectId');
+ const project = await projects.getProject(ctx.userId, projectId);
+ if (!project) throw new Error('not_found');
+ return { project };
+ },
+
+ // ── Project bindings (the strict scope of agents/skills visible inside
+ // a project conversation; see CLAUDE.md §6 outer-intersection rule) ──
+ // `bindings.list` returns the bound ids JOINED with name/description so
+ // the renderer can paint the detail page in one round-trip; unknown ids
+ // (referent deleted) are filtered out of the joined view but kept in the
+ // raw `agents` / `skills` arrays so the user can see + clean up stale
+ // bindings.
+ 'projects.bindings.list': async ({ projectId }, ctx) => {
+ if (!safeId(projectId)) throw new Error('invalid projectId');
+ if (!await projects.projectExists(ctx.userId, projectId)) throw new Error('not_found');
+ const bindings = await projects.getBindings(ctx.userId, projectId);
+ const [agentList, skillList] = await Promise.all([
+ agents.listAgents(),
+ skills.listSkills(),
+ ]);
+ const agentById = new Map(agentList.map((a: any) => [a.agent_id, a]));
+ const skillById = new Map(skillList.map((s: any) => [s.id, s]));
+ return {
+ bindings,
+ agentDetails: bindings.agents
+ .map((id) => agentById.get(id))
+ .filter(Boolean),
+ skillDetails: bindings.skills
+ .map((id) => skillById.get(id))
+ .filter(Boolean),
+ };
+ },
+
+ 'projects.bindings.add': async ({ projectId, kind, id }, ctx) => {
+ if (!safeId(projectId)) throw new Error('invalid projectId');
+ if (typeof id !== 'string' || !id) throw new Error('invalid id');
+ let result;
+ if (kind === 'agent') {
+ if (!agents.isValidAgentId(id)) throw new Error('invalid id');
+ result = await projects.addAgentBinding(ctx.userId, projectId, id);
+ } else if (kind === 'skill') {
+ result = await projects.addSkillBinding(ctx.userId, projectId, id);
+ } else {
+ throw new Error('invalid kind');
+ }
+ if (!result.ok) throw new Error((result as { error: string }).error);
+ return { bindings: result.bindings };
+ },
+
+ 'projects.bindings.remove': async ({ projectId, kind, id }, ctx) => {
+ if (!safeId(projectId)) throw new Error('invalid projectId');
+ if (typeof id !== 'string' || !id) throw new Error('invalid id');
+ let result;
+ if (kind === 'agent') {
+ result = await projects.removeAgentBinding(ctx.userId, projectId, id);
+ } else if (kind === 'skill') {
+ result = await projects.removeSkillBinding(ctx.userId, projectId, id);
+ } else {
+ throw new Error('invalid kind');
+ }
+ if (!result.ok) throw new Error((result as { error: string }).error);
+ return { bindings: result.bindings };
+ },
+
+ // Candidates = full [builtin + custom] minus already-bound. Powers the
+ // "Add" picker on the project detail page so the renderer doesn't have
+ // to subtract client-side.
+ 'projects.bindings.candidates': async ({ projectId }, ctx) => {
+ if (!safeId(projectId)) throw new Error('invalid projectId');
+ if (!await projects.projectExists(ctx.userId, projectId)) throw new Error('not_found');
+ const bindings = await projects.getBindings(ctx.userId, projectId);
+ const boundAgents = new Set(bindings.agents);
+ const boundSkills = new Set(bindings.skills);
+ const [agentList, skillList] = await Promise.all([
+ agents.listAgents(),
+ skills.listSkills(),
+ ]);
+ return {
+ agents: agentList.filter((a: any) => !boundAgents.has(a.agent_id)),
+ skills: skillList.filter((s: any) => !boundSkills.has(s.id)),
+ };
+ },
+
// ── Group chat (replaces legacy conversations.send / .stream / .markFormSubmitted) ──
'groupChat.send': async ({ cid, content, attachments }, ctx) => {
if (!safeId(cid)) throw new Error('invalid cid');
diff --git a/src/main/model/client.ts b/src/main/model/client.ts
index 59863e98..b52ca5e9 100644
--- a/src/main/model/client.ts
+++ b/src/main/model/client.ts
@@ -69,6 +69,14 @@ export interface ChatOptions {
* `skill_list: []`. Sourced from the target agent's `skill_list` field
* (see `features/agents.ts`). */
skillList?: string[];
+ /** Project-scope skill allowlist applied ONLY to the System A render
+ * block (`getSystemPromptBlock`). Resolved from the conversation's
+ * project bindings at the top of `runTurn`. The runner intersects this
+ * with `skillList` for prompt rendering but leaves SkillStore (System B,
+ * agent's self-evolved skills) constrained by `skillList` alone — so
+ * agents in projects retain access to their own evolved skills.
+ * Undefined = orphan conversation, no project filter. */
+ projectAllowedSkillIds?: readonly string[];
/** Extra tools merged into core-agent's builtin tool set for this call.
* Currently used by group_chat commander to surface `plan_set` and
* agent-management tools alongside the builtin set. */
diff --git a/src/main/model/core-agent/client.ts b/src/main/model/core-agent/client.ts
index ddb59611..1525cb77 100644
--- a/src/main/model/core-agent/client.ts
+++ b/src/main/model/core-agent/client.ts
@@ -82,6 +82,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
idleTimeout = 600,
abortSignal = null,
skillList,
+ projectAllowedSkillIds,
extraTools,
extraRoots,
readOnlyExtraRoots,
@@ -179,6 +180,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
...(cid ? { cid } : {}),
...(projectId ? { projectId } : {}),
...(skillList !== undefined ? { skillList } : {}),
+ ...(projectAllowedSkillIds !== undefined ? { projectAllowedSkillIds } : {}),
...(extraTools && extraTools.length ? { extraTools } : {}),
...(extraRoots && extraRoots.length ? { extraRoots } : {}),
...(readOnlyExtraRoots && readOnlyExtraRoots.length ? { readOnlyExtraRoots } : {}),
diff --git a/src/main/model/core-agent/runner.ts b/src/main/model/core-agent/runner.ts
index af747831..2bfa12a8 100644
--- a/src/main/model/core-agent/runner.ts
+++ b/src/main/model/core-agent/runner.ts
@@ -67,6 +67,16 @@ async function ca(): Promise<CA> {
/** No-op retained for backward compat; nothing is cached anymore. */
export function invalidateConfig(): void {}
+function _intersectRenderAllowlist(
+ agentList: readonly string[] | undefined,
+ projectList: readonly string[] | undefined,
+): readonly string[] | undefined {
+ if (projectList === undefined) return agentList;
+ if (agentList === undefined) return projectList;
+ const agentSet = new Set(agentList);
+ return projectList.filter((id) => agentSet.has(id));
+}
+
export interface BuildRunnerParams {
sessionId: string;
systemPrompt?: string;
@@ -86,6 +96,13 @@ export interface BuildRunnerParams {
/** Optional subset of skill ids; undefined = full global listing. See
* `skill-registry.getSystemPromptBlock` for the exact semantics. */
skillList?: string[];
+ /** Project-scope skill allowlist applied ONLY to the System A render
+ * block (`getSystemPromptBlock`). When present, the rendered allowlist
+ * is `intersect(skillList, projectAllowedSkillIds)`; SkillStore (System
+ * B, agent self-evolved skills) stays gated by `skillList` alone so
+ * agents in projects retain access to their own evolved skills. See
+ * CLAUDE.md §6 + `features/projects.ts::resolveProjectScope`. */
+ projectAllowedSkillIds?: readonly string[];
/** Extra tools added to core-agent's builtins (e.g. group_chat commander
* gets `plan_set` + agent-management tools). */
extraTools?: AgentTool[];
@@ -155,11 +172,19 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
const earlyUid = params.userId || extractUidFromSessionId(params.sessionId);
const disabledSkillIds = earlyUid ? readDisabledSets(earlyUid).skills : new Set<string>();
+ // System A render allowlist = intersect(skillList, project bindings).
+ // - no project scope (`projectAllowedSkillIds` undefined) → legacy
+ // `skillList`-only behavior
+ // - commander in a project (`skillList` undefined, project list set) →
+ // project list governs the render block
+ // - agent in a project (both set) → intersection
+ // SkillStore (System B) stays gated by `skillList` alone — see line ~429.
+ const renderAllowlist = _intersectRenderAllowlist(params.skillList, params.projectAllowedSkillIds);
const [mod, session, skillsBlock] = await Promise.all([
ca(),
getSession(params.sessionId),
getSystemPromptBlock({
- ...(params.skillList === undefined ? {} : { allowlist: params.skillList }),
+ ...(renderAllowlist === undefined ? {} : { allowlist: [...renderAllowlist] }),
disabledIds: disabledSkillIds,
}),
]);
diff --git a/src/main/paths.ts b/src/main/paths.ts
index e7ab1d42..b8204025 100644
--- a/src/main/paths.ts
+++ b/src/main/paths.ts
@@ -125,16 +125,24 @@ export const userProfileFile = (uid: string) => path.join(userMemoryDir(uid), 'U
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).
+// Per-user projects (logical group of conversations + bindings + scoped
+// workspace). Each project is a self-contained directory:
+// `<pid>/project.json` metadata (project_id, name, owner_uid, timestamps)
+// `<pid>/bindings.json` agent/skill ids the project pins (strict scope)
+// **No aggregate `_index.json`** — listing scans `projects/*/project.json`.
+// **Why:** future server-mediated collaboration adds/removes a project from
+// a user's view by writing/removing the per-pid directory; an aggregate
+// index would force every membership change to be a multi-file
+// transactional update and would conflict on multi-device sync. See
+// `features/projects.ts` and `PC/CLAUDE.md` §4 / §5 / §9.
+//
+// Project membership of a conversation stays 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 projectMetaFile = (uid: string, pid: string) => path.join(projectDir(uid, pid), 'project.json');
+export const projectBindingsFile = (uid: string, pid: string) => path.join(projectDir(uid, pid), 'bindings.json');
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');
diff --git a/src/renderer/index.html b/src/renderer/index.html
index a984c360..14bbf39d 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -101,6 +101,10 @@
<!-- Conversation Detail -->
<section class="panel" id="panel-conversation">
<div class="chat-container">
+ <div id="conv-project-empty-banner" class="conv-project-empty-banner" style="display:none">
+ <span class="muted" data-i18n="project.bindings.empty_in_chat">This project has no agents or skills bound. Open the project page to add some.</span>
+ <button type="button" class="btn btn-sm" id="conv-project-empty-banner-open" data-i18n="project.bindings.open_settings">Open project page</button>
+ </div>
<div id="chat-history" class="chat-history">
<div class="empty" data-i18n="chat.empty">No messages yet...</div>
</div>
@@ -336,6 +340,38 @@
</div>
</section>
+ <!-- Project detail (bindings + future per-project assets) -->
+ <section class="panel" id="panel-project">
+ <div class="project-detail-view">
+ <div class="project-detail-content" id="project-detail-content">
+ <div class="project-detail-header">
+ <h2 class="project-detail-title" id="project-detail-title"></h2>
+ <input type="text" class="project-detail-title-input" id="project-detail-title-input"
+ style="display:none" autocomplete="off" spellcheck="false" />
+ <div class="project-detail-actions">
+ <button type="button" class="btn btn-sm" id="project-action-new-conv" data-i18n="project.action.new_conv">+ New chat</button>
+ <button type="button" class="btn btn-sm" id="project-action-rename" data-i18n="project.action.rename">Rename</button>
+ <button type="button" class="btn btn-sm btn-danger" id="project-action-delete" data-i18n="project.action.delete">Delete</button>
+ </div>
+ </div>
+ <section class="project-detail-card" id="project-detail-agents-section">
+ <div class="project-detail-card-head">
+ <span class="project-detail-card-title" data-i18n="project.bindings.agents_title">Agents</span>
+ <button type="button" class="btn btn-sm" id="project-add-agent-btn" data-i18n="project.bindings.add_agent">+ Add</button>
+ </div>
+ <div class="project-bindings-list" id="project-agents-list"></div>
+ </section>
+ <section class="project-detail-card" id="project-detail-skills-section">
+ <div class="project-detail-card-head">
+ <span class="project-detail-card-title" data-i18n="project.bindings.skills_title">Skills</span>
+ <button type="button" class="btn btn-sm" id="project-add-skill-btn" data-i18n="project.bindings.add_skill">+ Add</button>
+ </div>
+ <div class="project-bindings-list" id="project-skills-list"></div>
+ </section>
+ </div>
+ </div>
+ </section>
+
<!-- Knowledge base -->
<section class="panel" id="panel-contexts">
<div class="contexts-layout">
@@ -784,6 +820,7 @@
<script src="./modules/chat-lightbox.js"></script>
<script src="./modules/strip-structural-blocks.js"></script>
<script src="./modules/projects.js"></script>
+ <script src="./modules/project-detail.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 4ce49a4d..6518f96e 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -577,6 +577,30 @@
"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",
+ "project.back": "Back",
+ "project.detail_load_failed": "Failed to load project, it may have been deleted.",
+ "project.action.new_conv": "New chat",
+ "project.action.rename": "Rename",
+ "project.action.delete": "Delete",
+ "project.bindings.picker_search_placeholder": "Search by name or description",
+ "project.bindings.picker_no_match": "No matches found.",
+ "project.bindings.agents_title": "Agents",
+ "project.bindings.skills_title": "Skills",
+ "project.bindings.agents_desc": "Add agents to make them available inside this project.",
+ "project.bindings.skills_desc": "Add skills to extend the project's capabilities.",
+ "project.bindings.add_agent": "Add",
+ "project.bindings.add_skill": "Add",
+ "project.bindings.picker_title_agents": "Add agents to project",
+ "project.bindings.picker_title_skills": "Add skills to project",
+ "project.bindings.picker_close": "Close",
+ "project.bindings.remove": "Remove",
+ "project.bindings.empty_agents": "No agents bound. Add one to use it inside this project.",
+ "project.bindings.empty_skills": "No skills bound. Add one to use it inside this project.",
+ "project.bindings.candidates_empty_agents": "No agents available to add.",
+ "project.bindings.candidates_empty_skills": "No skills available to add.",
+ "project.bindings.stale": "Removed",
+ "project.bindings.empty_in_chat": "This project has no agents or skills bound. Open the project page to add some.",
+ "project.bindings.open_settings": "Open project page",
"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 e809f149..d497d7ef 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -577,6 +577,30 @@
"project.delete_danger_label_empty": "删除项目",
"project.has_running_conv": "该项目下有对话正在生成,请先停止再删除",
"project.delete_failed_generic": "删除项目失败,请重试",
+ "project.back": "返回",
+ "project.detail_load_failed": "加载项目失败,可能已被删除。",
+ "project.action.new_conv": "新对话",
+ "project.action.rename": "重命名",
+ "project.action.delete": "删除",
+ "project.bindings.picker_search_placeholder": "按名称或描述搜索",
+ "project.bindings.picker_no_match": "没有匹配结果。",
+ "project.bindings.agents_title": "智能体",
+ "project.bindings.skills_title": "技能",
+ "project.bindings.agents_desc": "添加可在本项目中使用的智能体。",
+ "project.bindings.skills_desc": "添加可扩展项目能力的技能。",
+ "project.bindings.add_agent": "添加",
+ "project.bindings.add_skill": "添加",
+ "project.bindings.picker_title_agents": "添加智能体到项目",
+ "project.bindings.picker_title_skills": "添加技能到项目",
+ "project.bindings.picker_close": "关闭",
+ "project.bindings.remove": "移除",
+ "project.bindings.empty_agents": "尚未挂载任何智能体。添加后才能在本项目中使用。",
+ "project.bindings.empty_skills": "尚未挂载任何技能。添加后才能在本项目中使用。",
+ "project.bindings.candidates_empty_agents": "没有可添加的智能体。",
+ "project.bindings.candidates_empty_skills": "没有可添加的技能。",
+ "project.bindings.stale": "已删除",
+ "project.bindings.empty_in_chat": "本项目尚未挂载任何智能体或技能。请打开项目页面进行配置。",
+ "project.bindings.open_settings": "打开项目页面",
"search.history_title": "搜索历史",
"search.history_clear": "清空",
"search.failed": "搜索失败: {msg}",
diff --git a/src/renderer/modules/boot.js b/src/renderer/modules/boot.js
index 6bae8e85..0e16bf80 100644
--- a/src/renderer/modules/boot.js
+++ b/src/renderer/modules/boot.js
@@ -102,6 +102,16 @@ function _restoreLastView() {
setView('conversation', cid);
return;
}
+ // Project detail page: cid slot carries the pid (see boot.js setView).
+ // Verify the project still exists (might have been deleted on another
+ // device since last save) before restoring; fall through to new-chat
+ // otherwise.
+ if (view === 'project' && cid
+ && Array.isArray(_projectsCache)
+ && _projectsCache.some((p) => p && p.project_id === cid)) {
+ setView('project', cid);
+ return;
+ }
if (view === 'agents' || view === 'skills' || view === 'contexts' || view === 'new-chat') {
setView(view);
return;
@@ -136,6 +146,7 @@ function setView(view, cid, opts = {}) {
: view === 'skills' ? 'panel-skills'
: view === 'contexts' ? 'panel-contexts'
: view === 'settings' ? 'panel-settings'
+ : view === 'project' ? 'panel-project'
: 'panel-conversation';
document.getElementById(panelId).classList.add('active');
@@ -215,6 +226,11 @@ function setView(view, cid, opts = {}) {
} else if (view === 'settings') {
currentCid = null;
loadSettings();
+ } else if (view === 'project') {
+ // `cid` arg is repurposed as `pid` for this view (single second-arg
+ // slot kept; the function only inspects it for 'conversation' above).
+ currentCid = null;
+ if (typeof loadProjectDetail === 'function') loadProjectDetail(cid || '');
} else {
currentCid = null;
}
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index ed3f63ff..30ba7dd7 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -294,6 +294,11 @@ function onEnterConversationView() {
// 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();
+ // Empty-bindings banner: when this conv belongs to a project and the
+ // project has zero agents + zero skills bound, surface a one-line
+ // notice + "Open project page" affordance. Cheap IPC; only fires for
+ // in-project conversations.
+ if (typeof refreshConvProjectEmptyBanner === 'function') refreshConvProjectEmptyBanner(currentCid);
// 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
diff --git a/src/renderer/modules/project-detail.js b/src/renderer/modules/project-detail.js
new file mode 100644
index 00000000..61eed2be
--- /dev/null
+++ b/src/renderer/modules/project-detail.js
@@ -0,0 +1,452 @@
+// ─── Project detail panel ───────────────────────────────────────────────
+// Drives `#panel-project`: shows the project's bindings (agents + skills)
+// and exposes Add / Remove for each. Opened by clicking a project row in
+// the sidebar (`projects.js::_renderProjectRow` — single click both
+// expands the row and switches view here).
+//
+// Header carries 3 actions: + New chat / Rename / Delete. The "Back" button
+// was intentionally removed — the sidebar IS the back navigation.
+//
+// Add picker is a centered modal (`.modal-overlay`) — reuses the existing
+// dialog overlay shell so it doesn't get clipped at the panel edge.
+
+const _projectDetailLog = createLogger('project-detail');
+
+let _projectDetailPid = ''; // pid currently rendered in the panel
+let _projectDetailMeta = null; // { project, bindings, agentDetails, skillDetails }
+
+// ── Public: navigate-into ──────────────────────────────────────────────
+
+/** Called by boot.js setView('project', pid) on entry. */
+async function loadProjectDetail(pid) {
+ _projectDetailPid = pid || '';
+ if (!_projectDetailPid) {
+ _renderProjectDetailEmpty();
+ return;
+ }
+ try {
+ const [getRes, listRes] = await Promise.all([
+ window.orkas.invoke('projects.get', { projectId: pid }),
+ window.orkas.invoke('projects.bindings.list', { projectId: pid }),
+ ]);
+ if (!getRes?.ok || !listRes?.ok) {
+ throw new Error((getRes && getRes.error) || (listRes && listRes.error) || 'load_failed');
+ }
+ _projectDetailMeta = {
+ project: getRes.project,
+ bindings: listRes.bindings || { agents: [], skills: [] },
+ agentDetails: Array.isArray(listRes.agentDetails) ? listRes.agentDetails : [],
+ skillDetails: Array.isArray(listRes.skillDetails) ? listRes.skillDetails : [],
+ };
+ _renderProjectDetail();
+ } catch (err) {
+ _projectDetailLog.warn('load project detail failed', err);
+ if (typeof setView === 'function') setView('new-chat');
+ if (typeof uiAlert === 'function') uiAlert(t('project.detail_load_failed'));
+ }
+}
+
+function _renderProjectDetailEmpty() {
+ const titleEl = document.getElementById('project-detail-title');
+ if (titleEl) titleEl.textContent = '';
+ document.getElementById('project-agents-list').innerHTML = '';
+ document.getElementById('project-skills-list').innerHTML = '';
+}
+
+function _renderProjectDetail() {
+ if (!_projectDetailMeta) { _renderProjectDetailEmpty(); return; }
+ const { project, bindings, agentDetails, skillDetails } = _projectDetailMeta;
+
+ const titleEl = document.getElementById('project-detail-title');
+ if (titleEl) titleEl.textContent = project?.name || '';
+
+ // Stale ids (binding referent missing — agent / skill was deleted).
+ const agentValidIds = new Set(agentDetails.map((a) => a.agent_id));
+ const skillValidIds = new Set(skillDetails.map((s) => s.id));
+ const staleAgents = (bindings.agents || []).filter((id) => !agentValidIds.has(id));
+ const staleSkills = (bindings.skills || []).filter((id) => !skillValidIds.has(id));
+
+ document.getElementById('project-agents-list').innerHTML = _renderBindingsRows(
+ 'agent', agentDetails, staleAgents,
+ );
+ document.getElementById('project-skills-list').innerHTML = _renderBindingsRows(
+ 'skill', skillDetails, staleSkills,
+ );
+
+ applyDomI18n();
+ _bindRemoveButtons();
+}
+
+function _renderBindingsRows(kind, items, staleIds) {
+ const lang = _activeLang();
+ const removeLabel = escapeHtml(t('project.bindings.remove'));
+ const rows = [];
+ for (const it of items) {
+ const id = (kind === 'agent') ? it.agent_id : it.id;
+ const name = escapeHtml(it.name || id);
+ const desc = _pickItemDescription(it, lang);
+ const descHtml = desc ? `<div class="project-binding-desc muted">${escapeHtml(desc)}</div>` : '';
+ const sourceTag = it.source ? `<span class="project-binding-source">${escapeHtml(it.source)}</span>` : '';
+ rows.push(`
+ <div class="project-binding-row" data-kind="${kind}" data-id="${escapeHtml(id)}">
+ <div class="project-binding-main">
+ <div class="project-binding-head">
+ <span class="project-binding-name">${name}</span>
+ ${sourceTag}
+ </div>
+ ${descHtml}
+ </div>
+ <button type="button" class="btn btn-sm btn-danger" data-action="remove">${removeLabel}</button>
+ </div>
+ `);
+ }
+ for (const id of staleIds) {
+ rows.push(`
+ <div class="project-binding-row project-binding-row--stale" data-kind="${kind}" data-id="${escapeHtml(id)}">
+ <div class="project-binding-main">
+ <div class="project-binding-head">
+ <span class="project-binding-name">${escapeHtml(id)}</span>
+ <span class="project-binding-source project-binding-source--stale" data-i18n="project.bindings.stale">Removed</span>
+ </div>
+ </div>
+ <button type="button" class="btn btn-sm" data-action="remove">${removeLabel}</button>
+ </div>
+ `);
+ }
+ if (!rows.length) {
+ const emptyKey = kind === 'agent' ? 'project.bindings.empty_agents' : 'project.bindings.empty_skills';
+ return `<div class="empty" data-i18n="${emptyKey}">${escapeHtml(t(emptyKey))}</div>`;
+ }
+ return rows.join('');
+}
+
+function _activeLang() {
+ if (typeof getLang === 'function') return getLang();
+ return 'en';
+}
+
+function _pickItemDescription(item, lang) {
+ // Centralised across the renderer: `utils.js::pickDesc` does the
+ // cross-locale fallback (zh ?? en ?? '') so a one-language entry never
+ // renders blank. Don't duplicate the rule here.
+ return (typeof pickDesc === 'function') ? pickDesc(item, lang) : '';
+}
+
+function _bindRemoveButtons() {
+ document.querySelectorAll('#project-detail-content [data-action="remove"]').forEach((btn) => {
+ btn.addEventListener('click', async (e) => {
+ e.stopPropagation();
+ const row = btn.closest('.project-binding-row');
+ if (!row) return;
+ const kind = row.dataset.kind;
+ const id = row.dataset.id;
+ try {
+ await window.orkas.invoke('projects.bindings.remove', {
+ projectId: _projectDetailPid, kind, id,
+ });
+ await loadProjectDetail(_projectDetailPid);
+ } catch (err) {
+ _projectDetailLog.warn('remove binding failed', err);
+ }
+ });
+ });
+}
+
+// ── Add picker (centered modal with search) ───────────────────────────
+
+async function _openAddPicker(kind) {
+ // Dispose any previously-open picker so re-clicks don't stack.
+ document.getElementById('project-binding-picker-overlay')?.remove();
+
+ let candidates;
+ try {
+ const res = await window.orkas.invoke('projects.bindings.candidates', {
+ projectId: _projectDetailPid,
+ });
+ if (!res?.ok) throw new Error(res?.error || 'load_failed');
+ candidates = (kind === 'agent') ? (res.agents || []) : (res.skills || []);
+ } catch (err) {
+ _projectDetailLog.warn('load candidates failed', err);
+ return;
+ }
+
+ const titleKey = kind === 'agent' ? 'project.bindings.picker_title_agents' : 'project.bindings.picker_title_skills';
+ const emptyKey = kind === 'agent' ? 'project.bindings.candidates_empty_agents' : 'project.bindings.candidates_empty_skills';
+ const closeText = escapeHtml(t('project.bindings.picker_close'));
+ const searchPh = escapeHtml(t('project.bindings.picker_search_placeholder'));
+
+ const overlay = document.createElement('div');
+ overlay.id = 'project-binding-picker-overlay';
+ overlay.className = 'modal-overlay open';
+ overlay.innerHTML = `
+ <div class="modal project-binding-picker-modal" role="dialog" aria-modal="true">
+ <div class="project-binding-picker-header">
+ <span class="project-binding-picker-title" data-i18n="${titleKey}">${escapeHtml(t(titleKey))}</span>
+ <button type="button" class="project-binding-picker-close" data-action="close" aria-label="${closeText}">×</button>
+ </div>
+ <div class="project-binding-picker-search">
+ <input type="text" id="project-binding-picker-search-input"
+ placeholder="${searchPh}" autocomplete="off" spellcheck="false" />
+ </div>
+ <div class="project-binding-picker-body">
+ <div class="project-binding-picker-list" id="project-binding-picker-list"></div>
+ <div class="empty muted" id="project-binding-picker-empty" style="display:none"></div>
+ </div>
+ </div>
+ `;
+ document.body.appendChild(overlay);
+
+ const listEl = overlay.querySelector('#project-binding-picker-list');
+ const emptyEl = overlay.querySelector('#project-binding-picker-empty');
+ const searchEl = overlay.querySelector('#project-binding-picker-search-input');
+
+ // Render current candidate set, applying the search filter. Re-rendered
+ // on every keystroke + after each successful add.
+ const render = () => {
+ const lang = _activeLang();
+ const q = (searchEl.value || '').trim().toLocaleLowerCase();
+ const filtered = !q ? candidates : candidates.filter((c) => {
+ const id = (kind === 'agent') ? c.agent_id : c.id;
+ const name = (c.name || '').toLocaleLowerCase();
+ const desc = (_pickItemDescription(c, lang) || '').toLocaleLowerCase();
+ return name.includes(q) || desc.includes(q) || (id || '').toLocaleLowerCase().includes(q);
+ });
+ if (!filtered.length) {
+ listEl.innerHTML = '';
+ const noMatch = q ? t('project.bindings.picker_no_match') : t(emptyKey);
+ emptyEl.textContent = noMatch;
+ emptyEl.style.display = '';
+ return;
+ }
+ emptyEl.style.display = 'none';
+ listEl.innerHTML = filtered.map((c) => {
+ const id = (kind === 'agent') ? c.agent_id : c.id;
+ const name = escapeHtml(c.name || id);
+ const desc = _pickItemDescription(c, lang);
+ const descHtml = desc ? `<div class="project-binding-desc muted">${escapeHtml(desc)}</div>` : '';
+ const source = c.source ? `<span class="project-binding-source">${escapeHtml(c.source)}</span>` : '';
+ return `
+ <div class="project-binding-picker-item" data-kind="${kind}" data-id="${escapeHtml(id)}">
+ <div class="project-binding-main">
+ <div class="project-binding-head">
+ <span class="project-binding-name">${name}</span>
+ ${source}
+ </div>
+ ${descHtml}
+ </div>
+ <button type="button" class="btn btn-sm" data-action="pick" aria-label="Add">+</button>
+ </div>
+ `;
+ }).join('');
+ // Only the `+` button adds — clicking the row body itself is a no-op
+ // (per design: explicit confirm, no accidental adds when scanning the
+ // description).
+ listEl.querySelectorAll('.project-binding-picker-item [data-action="pick"]').forEach((btn) => {
+ btn.addEventListener('click', async (e) => {
+ e.stopPropagation();
+ const row = btn.closest('.project-binding-picker-item');
+ if (!row) return;
+ const id = row.dataset.id;
+ const k = row.dataset.kind;
+ try {
+ const res = await window.orkas.invoke('projects.bindings.add', {
+ projectId: _projectDetailPid, kind: k, id,
+ });
+ if (!res?.ok) throw new Error(res?.error || 'add_failed');
+ // Drop the picked id from the local candidate set so it
+ // disappears from subsequent renders without a server round-trip.
+ candidates = candidates.filter((c) => {
+ const cid = (k === 'agent') ? c.agent_id : c.id;
+ return cid !== id;
+ });
+ render();
+ // Background refresh of the detail page list so newly-bound
+ // items appear in the rail behind the modal.
+ loadProjectDetail(_projectDetailPid).catch((err) => _projectDetailLog.warn('refresh failed', err));
+ } catch (err) {
+ _projectDetailLog.warn('add binding failed', err);
+ }
+ });
+ });
+ };
+
+ searchEl.addEventListener('input', render);
+ searchEl.addEventListener('keydown', (e) => {
+ // IME guard (CLAUDE.md §8) — Esc while composing should commit the
+ // candidate, not close the modal.
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Escape') { e.preventDefault(); close(); }
+ });
+
+ const close = () => {
+ overlay.remove();
+ document.removeEventListener('keydown', onKey, true);
+ };
+ const onKey = (e) => {
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Escape' && document.activeElement !== searchEl) close();
+ };
+ overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
+ overlay.querySelector('[data-action="close"]')?.addEventListener('click', close);
+ document.addEventListener('keydown', onKey, true);
+
+ render();
+ setTimeout(() => searchEl.focus(), 0);
+}
+
+// ── Header actions: New chat / Rename / Delete ────────────────────────
+
+function _onNewConvAction() {
+ if (!_projectDetailPid) return;
+ // Pin pid into the commander chip's localStorage key so the new-chat
+ // panel mounts with this project pre-selected. Mirrors
+ // `projects.js::_newConvWithProject` semantics — keep the key in sync.
+ try { localStorage.setItem('commander.lastProject', _projectDetailPid); } catch (_) {}
+ if (typeof setView === 'function') setView('new-chat');
+}
+
+function _onRenameAction() {
+ if (!_projectDetailMeta) return;
+ const titleEl = document.getElementById('project-detail-title');
+ const inputEl = document.getElementById('project-detail-title-input');
+ if (!titleEl || !inputEl) return;
+ inputEl.value = _projectDetailMeta.project?.name || '';
+ titleEl.style.display = 'none';
+ inputEl.style.display = '';
+ inputEl.focus();
+ inputEl.select();
+}
+
+async function _commitRename(newName) {
+ if (!_projectDetailPid || !_projectDetailMeta) return;
+ const old = _projectDetailMeta.project?.name || '';
+ const trimmed = (newName || '').trim();
+ // No change OR empty → revert silently.
+ if (!trimmed || trimmed === old) {
+ _exitRenameMode();
+ return;
+ }
+ let code = '';
+ try {
+ const res = await window.orkas.invoke('projects.rename', {
+ projectId: _projectDetailPid, name: trimmed,
+ });
+ if (!res || !res.ok) {
+ code = (res && res.error) || 'generic';
+ } else {
+ _projectDetailMeta.project = res.project;
+ if (typeof loadProjects === 'function') loadProjects(true);
+ _exitRenameMode();
+ _renderProjectDetail();
+ return;
+ }
+ } catch (err) {
+ code = (err && err.message) || 'generic';
+ }
+ if (code === 'name_dup') {
+ await uiAlert(t('project.name_dup_inline'));
+ } else if (code === 'name_empty') {
+ await uiAlert(t('project.name_empty'));
+ } else if (code) {
+ await uiAlert(t('project.error.generic'));
+ }
+ _exitRenameMode();
+}
+
+function _exitRenameMode() {
+ const titleEl = document.getElementById('project-detail-title');
+ const inputEl = document.getElementById('project-detail-title-input');
+ if (titleEl) titleEl.style.display = '';
+ if (inputEl) inputEl.style.display = 'none';
+}
+
+async function _onDeleteAction() {
+ if (!_projectDetailPid || !_projectDetailMeta) return;
+ // Reuse the sidebar's delete confirm flow so the danger label / count
+ // wording stays in one place. `_confirmDeleteProject` is defined in
+ // `projects.js` and runs the IPC + post-delete cleanup. The sidebar
+ // handler doesn't navigate away on its own when the user is on the
+ // project detail panel (currentCid is null there), so we check post-hoc:
+ // if the project disappeared from the cache, jump to new-chat.
+ const targetPid = _projectDetailPid;
+ if (typeof _confirmDeleteProject === 'function') {
+ await _confirmDeleteProject(targetPid);
+ }
+ const stillExists = Array.isArray(_projectsCache)
+ && _projectsCache.some((p) => p && p.project_id === targetPid);
+ if (!stillExists && currentView === 'project') {
+ if (typeof setView === 'function') setView('new-chat');
+ }
+}
+
+// ── Empty-bindings banner inside in-project conversations ─────────────
+
+async function refreshConvProjectEmptyBanner(cid) {
+ const banner = document.getElementById('conv-project-empty-banner');
+ if (!banner) return;
+ let pid = '';
+ if (typeof conversations !== 'undefined' && Array.isArray(conversations)) {
+ const conv = conversations.find((c) => c && c.conversation_id === cid);
+ if (conv && conv.project_id) pid = conv.project_id;
+ }
+ if (!pid) {
+ banner.style.display = 'none';
+ delete banner.dataset.pid;
+ return;
+ }
+ try {
+ const res = await window.orkas.invoke('projects.bindings.list', { projectId: pid });
+ const b = res && res.bindings ? res.bindings : { agents: [], skills: [] };
+ const isEmpty = !(b.agents || []).length && !(b.skills || []).length;
+ banner.style.display = isEmpty ? '' : 'none';
+ banner.dataset.pid = pid;
+ } catch (_) {
+ banner.style.display = 'none';
+ }
+}
+
+// ── Boot wiring ────────────────────────────────────────────────────────
+
+document.addEventListener('DOMContentLoaded', () => {
+ document.getElementById('project-add-agent-btn')?.addEventListener('click', (e) => {
+ e.stopPropagation();
+ _openAddPicker('agent');
+ });
+ document.getElementById('project-add-skill-btn')?.addEventListener('click', (e) => {
+ e.stopPropagation();
+ _openAddPicker('skill');
+ });
+ document.getElementById('project-action-new-conv')?.addEventListener('click', (e) => {
+ e.stopPropagation();
+ _onNewConvAction();
+ });
+ document.getElementById('project-action-rename')?.addEventListener('click', (e) => {
+ e.stopPropagation();
+ _onRenameAction();
+ });
+ document.getElementById('project-action-delete')?.addEventListener('click', (e) => {
+ e.stopPropagation();
+ _onDeleteAction();
+ });
+ // Inline rename input handlers.
+ const inputEl = document.getElementById('project-detail-title-input');
+ if (inputEl) {
+ inputEl.addEventListener('keydown', (e) => {
+ // IME guard (CLAUDE.md §8) — Enter while composing must commit
+ // the candidate, not the rename.
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Enter') { e.preventDefault(); _commitRename(inputEl.value); }
+ else if (e.key === 'Escape') { e.preventDefault(); _exitRenameMode(); }
+ });
+ inputEl.addEventListener('blur', () => _commitRename(inputEl.value));
+ }
+ // In-conv empty-bindings banner action.
+ document.getElementById('conv-project-empty-banner-open')?.addEventListener('click', () => {
+ const banner = document.getElementById('conv-project-empty-banner');
+ const pid = banner?.dataset?.pid || '';
+ if (pid && typeof setView === 'function') setView('project', pid);
+ });
+ window.addEventListener('i18n-change', () => {
+ if (currentView === 'project' && _projectDetailMeta) _renderProjectDetail();
+ });
+});
diff --git a/src/renderer/modules/projects.js b/src/renderer/modules/projects.js
index 9057c1b1..51c68eb4 100644
--- a/src/renderer/modules/projects.js
+++ b/src/renderer/modules/projects.js
@@ -5,7 +5,8 @@
// 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
+// Storage layout (cloud-synced): `<uid>/cloud/projects/<pid>/{project.json,
+// bindings.json}` — no aggregate index, list = directory scan. See
// `features/projects.ts`. The renderer never persists projects state directly —
// every mutation goes through `projects.*` IPC channels.
//
@@ -203,9 +204,9 @@ function _bindProjectsHandlers(container) {
_bindInlineRenameInput(input);
});
- // Project rows: caret / icon / name → toggle expand;
- // ⋯ button → open menu (stopPropagation);
- // .project-rename-input → swallow click (don't toggle).
+ // Project rows: any click → BOTH open the detail page AND toggle the
+ // expand state of nested conversations (per design — single click does
+ // both). Exceptions: ⋯ opens its menu; rename input swallows click.
container.querySelectorAll('.project-row[data-pid]').forEach((row) => {
const pid = row.dataset.pid;
row.addEventListener('click', (e) => {
@@ -219,6 +220,7 @@ function _bindProjectsHandlers(container) {
return;
}
_toggleProjectExpand(pid);
+ if (typeof setView === 'function') setView('project', pid);
});
});
diff --git a/src/renderer/modules/search.js b/src/renderer/modules/search.js
index 20b9cede..057766c1 100644
--- a/src/renderer/modules/search.js
+++ b/src/renderer/modules/search.js
@@ -223,12 +223,16 @@ function _renderSearchRow(r, dataIdx, query) {
const label = metaCfg.labelKey ? t(metaCfg.labelKey) : r.kind;
const roleLabel = (role) => (role === 'user' ? t('search.role.user') : t('search.role.ai'));
let title = ''; let sub = '';
+ let projectChip = '';
if (r.kind === 'context') {
title = r.title || r.path;
sub = r.path;
} else if (r.kind === 'chat') {
title = r.conv_title || t('chat.new_conv_title');
sub = `${roleLabel(r.role)} · ${formatTime(r.time || '')}`;
+ if (r.project_name) {
+ projectChip = `<span class="search-result-project" title="${escapeHtml(r.project_name)}">${escapeHtml(r.project_name)}</span>`;
+ }
} else if (r.kind === 'agent' || r.kind === 'skill') {
title = r.name || r.id;
const srcKey = _SEARCH_SOURCE_LABEL[r.source] || '';
@@ -240,6 +244,7 @@ function _renderSearchRow(r, dataIdx, query) {
<div class="search-result-head">
<span class="search-result-kind ${metaCfg.cls}">${escapeHtml(label)}</span>
<span class="search-result-title">${escapeHtml(title)}</span>
+ ${projectChip}
<span class="search-result-meta">${escapeHtml(sub)}</span>
</div>
<div class="search-result-snippet">${_highlightSnippet(r.snippet, query)}</div>
diff --git a/src/renderer/style.css b/src/renderer/style.css
index b72e5447..78a6e7f0 100644
--- a/src/renderer/style.css
+++ b/src/renderer/style.css
@@ -303,6 +303,19 @@ body {
color: #94a3b8;
flex-shrink: 0;
}
+.search-result-project {
+ font-size: 10.5px;
+ padding: 1px 6px;
+ border-radius: 4px;
+ background: #f0fdf4;
+ color: #047857;
+ flex-shrink: 0;
+ font-weight: 500;
+ max-width: 140px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
.search-result-snippet {
font-size: 12px;
color: #64748b;
@@ -557,6 +570,224 @@ body {
color: #94a3b8;
}
+/* ── Project detail panel ─────────────────────────────────────────────── */
+
+.project-detail-view {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ overflow: hidden;
+ background: #f5f6f8; /* page-tinted, lets card sections pop */
+}
+.project-detail-content {
+ flex: 1;
+ overflow-y: auto;
+ padding: 22px 32px 32px 32px;
+ max-width: 880px;
+ width: 100%;
+ margin: 0 auto;
+ box-sizing: border-box;
+}
+.project-detail-header {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ margin-bottom: 22px;
+}
+.project-detail-title {
+ flex: 1;
+ font-size: 22px;
+ font-weight: 600;
+ color: var(--text);
+ margin: 0;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.project-detail-title-input {
+ flex: 1;
+ font-size: 22px;
+ font-weight: 600;
+ color: var(--text);
+ border: 1px solid var(--primary);
+ border-radius: 6px;
+ padding: 4px 10px;
+ font-family: inherit;
+ background: #fff;
+ outline: none;
+}
+.project-detail-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-shrink: 0;
+}
+
+/* Card-style section. Mirrors the look in shipping-product references —
+ white card on neutral page bg, rounded corners, subtle border. */
+.project-detail-card {
+ background: #fff;
+ border: 1px solid #e5e7eb;
+ border-radius: 12px;
+ padding: 16px 18px;
+ margin-bottom: 14px;
+ box-shadow: 0 1px 2px rgba(15, 23, 42, 0.03);
+}
+.project-detail-card-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+}
+.project-detail-card-title {
+ font-size: 15px;
+ font-weight: 600;
+ color: var(--text);
+}
+.project-detail-card-desc {
+ font-size: 12.5px;
+ margin-top: 6px;
+ line-height: 1.5;
+}
+
+.project-bindings-list {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin-top: 12px;
+}
+.project-binding-row {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 10px;
+ padding: 10px 12px;
+ background: #f8fafc;
+ border: 1px solid #eef2f7;
+ border-radius: 8px;
+}
+.project-binding-row--stale { opacity: 0.6; }
+.project-binding-main { flex: 1; min-width: 0; }
+.project-binding-head {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+.project-binding-name {
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--text);
+}
+.project-binding-source {
+ font-size: 11px;
+ color: #64748b;
+ background: #e2e8f0;
+ padding: 1px 6px;
+ border-radius: 4px;
+}
+.project-binding-source--stale { color: #b45309; background: #fef3c7; }
+.project-binding-desc {
+ font-size: 12px;
+ margin-top: 4px;
+ line-height: 1.4;
+}
+
+/* Modal picker for "+ Add agent / skill". Reuses .modal-overlay shell so
+ it sits above the panel + dims the rest of the UI; never gets clipped
+ at the panel edge like the prior popover. */
+.project-binding-picker-modal {
+ width: 560px;
+ max-width: 92vw;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ max-height: 80vh;
+}
+.project-binding-picker-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 12px 14px 10px 14px;
+ border-bottom: 1px solid #eef2f7;
+}
+.project-binding-picker-title {
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--text);
+}
+.project-binding-picker-close {
+ background: transparent;
+ border: none;
+ font-size: 20px;
+ color: #94a3b8;
+ cursor: pointer;
+ padding: 0 4px;
+ line-height: 1;
+}
+.project-binding-picker-close:hover { color: var(--text); }
+.project-binding-picker-search {
+ padding: 10px 14px 6px 14px;
+}
+.project-binding-picker-search input {
+ width: 100%;
+ box-sizing: border-box;
+ padding: 7px 10px;
+ font-size: 13px;
+ font-family: inherit;
+ color: var(--text);
+ background: #f8fafc;
+ border: 1px solid #e2e8f0;
+ border-radius: 6px;
+ outline: none;
+ transition: border-color 0.12s, background 0.12s;
+}
+.project-binding-picker-search input:focus {
+ border-color: var(--primary);
+ background: #fff;
+}
+.project-binding-picker-body {
+ flex: 1;
+ overflow-y: auto;
+ padding: 6px 14px 14px 14px;
+}
+.project-binding-picker-list {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+.project-binding-picker-item {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 10px;
+ padding: 9px 12px;
+ border: 1px solid #eef2f7;
+ border-radius: 8px;
+ background: #fff;
+}
+/* Clamp picker descriptions to 3 lines so a long builtin description
+ (Software Implementation Engineer etc.) doesn't blow the row height
+ and force the user to scroll past one card to see the next. */
+.project-binding-picker-item .project-binding-desc {
+ display: -webkit-box;
+ -webkit-line-clamp: 3;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+
+/* Empty-bindings banner inside an in-project conversation. */
+.conv-project-empty-banner {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 8px 14px;
+ background: #fef3c7;
+ border-bottom: 1px solid #fde68a;
+ font-size: 12.5px;
+}
+
/* Danger-styled confirm modal ornaments. */
.ui-dialog-title {
font-size: 14px;
diff --git a/test/main/features/projects.test.ts b/test/main/features/projects.test.ts
index be9815d8..5840f8ee 100644
--- a/test/main/features/projects.test.ts
+++ b/test/main/features/projects.test.ts
@@ -40,19 +40,22 @@ async function loadChats() {
}
describe('projects › createProject', () => {
- it('persists `_index.json` with name + project_id starting with p_', async () => {
+ it('persists per-pid project.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.owner_uid).toBe(TEST_UID);
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);
+ // Per-pid metadata file is the source of truth — no aggregate _index.json.
+ const metaFile = path.join(tmpDir, TEST_UID, 'cloud', 'projects', r.project.project_id, 'project.json');
+ const meta = JSON.parse(fs.readFileSync(metaFile, 'utf-8'));
+ expect(meta.project_id).toBe(r.project.project_id);
+ expect(meta.owner_uid).toBe(TEST_UID);
+ expect(fs.existsSync(path.join(tmpDir, TEST_UID, 'cloud', 'projects', '_index.json'))).toBe(false);
});
it('rejects empty / whitespace-only names with name_empty', async () => {
@@ -262,3 +265,142 @@ describe('projects › projectExists', () => {
expect(await projects.projectExists(TEST_UID, '')).toBe(false);
});
});
+
+describe('projects › bindings CRUD', () => {
+ it('add / remove agent bindings round-trip; bindings.json starts empty', async () => {
+ const projects = await loadProjects();
+ const p = await projects.createProject(TEST_UID, 'WithBindings');
+ if (!p.ok) throw new Error('precondition');
+ const pid = p.project.project_id;
+
+ // Initial state — no bindings file written yet, but read returns empty.
+ const empty = await projects.getBindings(TEST_UID, pid);
+ expect(empty).toEqual({ agents: [], skills: [] });
+ const bindingsFile = path.join(tmpDir, TEST_UID, 'cloud', 'projects', pid, 'bindings.json');
+ expect(fs.existsSync(bindingsFile)).toBe(false);
+
+ // Add one agent.
+ const a1 = await projects.addAgentBinding(TEST_UID, pid, 'agent-foo');
+ expect(a1.ok).toBe(true);
+ if (a1.ok) expect(a1.bindings.agents).toEqual(['agent-foo']);
+ // Now the file exists.
+ expect(fs.existsSync(bindingsFile)).toBe(true);
+
+ // Re-add same → idempotent (no duplicate).
+ const a2 = await projects.addAgentBinding(TEST_UID, pid, 'agent-foo');
+ if (a2.ok) expect(a2.bindings.agents).toEqual(['agent-foo']);
+
+ // Add skill.
+ const s1 = await projects.addSkillBinding(TEST_UID, pid, 'skill-bar');
+ if (s1.ok) expect(s1.bindings.skills).toEqual(['skill-bar']);
+
+ // Remove agent.
+ const r1 = await projects.removeAgentBinding(TEST_UID, pid, 'agent-foo');
+ if (r1.ok) {
+ expect(r1.bindings.agents).toEqual([]);
+ expect(r1.bindings.skills).toEqual(['skill-bar']);
+ }
+ });
+
+ it('returns not_found when binding into a non-existent project', async () => {
+ const projects = await loadProjects();
+ const r = await projects.addAgentBinding(TEST_UID, 'p_nosuch00', 'a');
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toBe('not_found');
+ });
+});
+
+describe('projects › resolveProjectScope', () => {
+ it('returns null for null / empty projectId (orphan conversation)', async () => {
+ const projects = await loadProjects();
+ expect(await projects.resolveProjectScope(TEST_UID, null)).toBeNull();
+ expect(await projects.resolveProjectScope(TEST_UID, undefined)).toBeNull();
+ expect(await projects.resolveProjectScope(TEST_UID, '')).toBeNull();
+ });
+
+ it('returns null for stale projectId (project deleted) so caller falls back to global', async () => {
+ const projects = await loadProjects();
+ expect(await projects.resolveProjectScope(TEST_UID, 'p_deleted0')).toBeNull();
+ });
+
+ it('returns empty bindings when project exists but no bindings have been added', async () => {
+ const projects = await loadProjects();
+ const p = await projects.createProject(TEST_UID, 'Fresh');
+ if (!p.ok) throw new Error('precondition');
+ const scope = await projects.resolveProjectScope(TEST_UID, p.project.project_id);
+ expect(scope).toEqual({ agents: [], skills: [] });
+ });
+
+ it('returns the bindings as written', async () => {
+ const projects = await loadProjects();
+ const p = await projects.createProject(TEST_UID, 'Bound');
+ if (!p.ok) throw new Error('precondition');
+ const pid = p.project.project_id;
+ await projects.addAgentBinding(TEST_UID, pid, 'a1');
+ await projects.addAgentBinding(TEST_UID, pid, 'a2');
+ await projects.addSkillBinding(TEST_UID, pid, 's1');
+ const scope = await projects.resolveProjectScope(TEST_UID, pid);
+ expect(scope).toEqual({ agents: ['a1', 'a2'], skills: ['s1'] });
+ });
+});
+
+describe('projects › legacy _index.json promotion', () => {
+ it('migrates a pre-existing _index.json into per-pid project.json + deletes the legacy file on first read', async () => {
+ const projects = await loadProjects();
+ // Seed the legacy shape directly on disk (pre-rework user state).
+ const projDir = path.join(tmpDir, TEST_UID, 'cloud', 'projects');
+ fs.mkdirSync(projDir, { recursive: true });
+ const legacy = [
+ { project_id: 'p_legacy01', name: 'Old A', created_at: '2026-04-01T10:00:00Z', updated_at: '2026-04-01T10:00:00Z' },
+ { project_id: 'p_legacy02', name: 'Old B', created_at: '2026-04-02T10:00:00Z', updated_at: '2026-04-02T10:00:00Z' },
+ ];
+ fs.writeFileSync(path.join(projDir, '_index.json'), JSON.stringify(legacy), 'utf-8');
+
+ // First read triggers promotion.
+ const list = await projects.listProjects(TEST_UID);
+ expect(list).toHaveLength(2);
+ const ids = list.map((p) => p.project_id).sort();
+ expect(ids).toEqual(['p_legacy01', 'p_legacy02']);
+
+ // Per-pid metadata files exist; legacy index gone.
+ expect(fs.existsSync(path.join(projDir, 'p_legacy01', 'project.json'))).toBe(true);
+ expect(fs.existsSync(path.join(projDir, 'p_legacy02', 'project.json'))).toBe(true);
+ expect(fs.existsSync(path.join(projDir, '_index.json'))).toBe(false);
+
+ // owner_uid backfilled to the calling uid.
+ const meta = JSON.parse(fs.readFileSync(path.join(projDir, 'p_legacy01', 'project.json'), 'utf-8'));
+ expect(meta.owner_uid).toBe(TEST_UID);
+
+ // Bindings file is NOT created (per plan: "no migration"). Empty
+ // bindings = strict isolation, user re-binds explicitly.
+ expect(fs.existsSync(path.join(projDir, 'p_legacy01', 'bindings.json'))).toBe(false);
+ });
+
+ it('promotion preserves existing per-pid files (legacy entry is the loser on collision)', async () => {
+ const projects = await loadProjects();
+ const projDir = path.join(tmpDir, TEST_UID, 'cloud', 'projects');
+ fs.mkdirSync(path.join(projDir, 'p_collide00'), { recursive: true });
+ // Pre-existing per-pid file with a different name.
+ fs.writeFileSync(
+ path.join(projDir, 'p_collide00', 'project.json'),
+ JSON.stringify({
+ project_id: 'p_collide00',
+ name: 'Per-pid wins',
+ owner_uid: TEST_UID,
+ created_at: '2026-04-10T10:00:00Z',
+ updated_at: '2026-04-10T10:00:00Z',
+ }),
+ 'utf-8',
+ );
+ fs.writeFileSync(
+ path.join(projDir, '_index.json'),
+ JSON.stringify([{ project_id: 'p_collide00', name: 'Legacy loser', created_at: '2026-04-01T00:00:00Z', updated_at: '2026-04-01T00:00:00Z' }]),
+ 'utf-8',
+ );
+
+ const list = await projects.listProjects(TEST_UID);
+ expect(list).toHaveLength(1);
+ expect(list[0].name).toBe('Per-pid wins');
+ expect(fs.existsSync(path.join(projDir, '_index.json'))).toBe(false);
+ });
+});