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.

Per-conversation workspace subdirectories to avoid -N suffix accumulation

claw2952c52973f27
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index 5d6e24f0..34a79e27 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -45,7 +45,6 @@ import {
import * as planExecutor from './plan_executor';
import { userChatsDir, BUILTIN_SKILLS_DIR, userSkillsDir } from '../../paths';
import * as agentsFeat from '../agents';
-import * as userWorkspace from '../user_workspace';
import { isAgentEnabled } from '../component_enabled';
import { buildLanguageDirective, t } from '../../i18n';
@@ -710,7 +709,14 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
const sessionId = actorSessionId(uid, cid, actor);
const isCommander = actor.kind === 'commander';
- const workingDir = userWorkspace.getWorkspacePath(uid);
+ // Per-conv subdir under the user's root workspace — keeps repeat
+ // agent runs writing the same basename grouped together instead of
+ // littering the root with `requirements-2.md / -3.md / ...`. Lazy:
+ // first call mkdirs + persists `state.json::workspace_dir`. Old convs
+ // with no `workspace_dir` field fall back to the root workspace, so
+ // there's no migration story.
+ const { getConversationWorkspacePath } = await import('./conv_workspace');
+ const workingDir = await getConversationWorkspacePath(uid, cid);
// First-turn replay: if the persistent session jsonl doesn't exist yet,
// prepend a `<group-chat-history>` block built from the visibility slice
@@ -1202,7 +1208,8 @@ async function buildCommanderSystemPrompt(uid: string, cid: string): Promise<str
const paths_ = await import('../../paths');
const plan = await readPlan(uid, cid);
const allAgentsList = await buildAgentsIndexBlock(uid);
- const workingDir = userWorkspace.getWorkspacePath(uid);
+ const { getConversationWorkspacePath } = await import('./conv_workspace');
+ const workingDir = await getConversationWorkspacePath(uid, cid);
const permState = (() => {
try {
const s = require('../permissions').getLocalExecState() as { granted: boolean };
diff --git a/src/main/features/group_chat/conv_workspace.ts b/src/main/features/group_chat/conv_workspace.ts
new file mode 100644
index 00000000..9a3d2782
--- /dev/null
+++ b/src/main/features/group_chat/conv_workspace.ts
@@ -0,0 +1,197 @@
+/**
+ * Per-conversation workspace subdirectory resolver.
+ *
+ * Background: every main conversation used to share one root `userWorkSpace/`,
+ * which meant repeated agent runs writing the same basename (`requirements.md`)
+ * piled up `requirements-2.md / -3.md / ...` via `util/uniquify-path`. The
+ * uniquify itself is correct (don't silently overwrite the prior run's
+ * artifact), but the workspace clutter is bad UX. Scoping the cwd to a
+ * conversation-specific subdir keeps the lineage grouped and the root tidy.
+ *
+ * Semantics:
+ * - Lazy: subdir is resolved + mkdir'd on the first call from `bus.ts`,
+ * which only fires when there's actual conversation activity. Old convs
+ * that never call this stay at the root workspace (= legacy behaviour).
+ * - Frozen: once chosen and persisted to `state.json::workspace_dir`, the
+ * subdir basename is never re-derived. Renaming the conv title later
+ * does NOT move the directory.
+ * - No sandbox change: the existing path-sandbox (`util/path-sandbox`)
+ * still allows the entire user workspace tree, so cross-conv reads via
+ * absolute path remain possible.
+ *
+ * Slug rules — see `slugifyConvTitle()` body. Goal: human-readable Finder
+ * navigation (CJK preserved, English lowercased, no opaque cid hex).
+ *
+ * Placeholder fallback: when the title is missing / equals the i18n
+ * placeholder ("新对话" / "New conversation") / slug-ifies to empty / hits
+ * a Windows reserved name, we fall back to `chat-{YYYY-MM-DD}-{N}`. The
+ * fallback is also frozen on first use, so a write that fired before the
+ * conv got its real auto-generated title locks in the date-based name —
+ * that's the accepted cost of lazy resolution.
+ */
+
+import * as fs from 'node:fs';
+import * as fsp from 'node:fs/promises';
+import * as path from 'node:path';
+
+import { getWorkspacePath } from '../user_workspace';
+import { getConversation } from '../chats';
+import { readState, setWorkspaceDirOnce } from './state';
+import { createLogger } from '../../logger';
+
+const log = createLogger('group_chat.conv_workspace');
+
+const MAX_SLUG_LEN = 32;
+
+// Match the literal default titles `chats.createConversation` writes when
+// no title is supplied (currently '新对话') AND any zh / en variant we may
+// localize into. Match by string equality, not lang lookup, because state
+// can carry whatever the conv was named at creation regardless of current
+// UI language.
+const PLACEHOLDER_TITLES: ReadonlySet<string> = new Set([
+ '新对话',
+ 'New conversation',
+ 'New Conversation',
+ 'New chat',
+ 'New Chat',
+]);
+
+// Windows reserved device names (case-insensitive). A directory bearing
+// any of these names cannot be created on Windows — fall back rather than
+// fight the OS.
+const WINDOWS_RESERVED: ReadonlySet<string> = new Set([
+ 'con', 'prn', 'aux', 'nul',
+ 'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9',
+ 'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9',
+]);
+
+const ILLEGAL_CHARS_RE = /[\\/:*?"<>|]/g;
+
+/** Pure slug derivation. Returns empty string on placeholder / unusable input;
+ * callers fall back to the date-based name. Exported for unit testing. */
+export function slugifyConvTitle(rawTitle: string | undefined | null): string {
+ if (!rawTitle) return '';
+ let s = rawTitle.trim();
+ if (!s) return '';
+ if (PLACEHOLDER_TITLES.has(s)) return '';
+
+ // 1. Replace Windows-illegal punctuation with '-' so it shows up as a
+ // separator instead of disappearing.
+ s = s.replace(ILLEGAL_CHARS_RE, '-');
+
+ // 2. Collapse any whitespace (incl. newlines / tabs) to single '-'.
+ s = s.replace(/\s+/g, '-');
+
+ // 3. Drop control + ASCII punctuation we don't want to keep. Allowlist:
+ // [a-zA-Z0-9_-] ASCII alnum + underscore + hyphen
+ // \p{L} any-language Unicode letter (covers CJK, Cyrillic, Arabic, …)
+ // \p{N} any-language Unicode number
+ s = s.replace(/[^\p{L}\p{N}_\-]/gu, '');
+
+ // 4. ASCII letters → lowercase (FS portability). Non-ASCII letters have
+ // no case to lose.
+ s = s.replace(/[A-Z]/g, (c) => c.toLowerCase());
+
+ // 5. Collapse runs of '-' and trim leading/trailing '-' or '.'.
+ s = s.replace(/-+/g, '-');
+ s = s.replace(/^[-.]+|[-.]+$/g, '');
+
+ // 6. Length cap.
+ if (s.length > MAX_SLUG_LEN) s = s.slice(0, MAX_SLUG_LEN).replace(/-+$/, '');
+
+ if (!s) return '';
+ if (WINDOWS_RESERVED.has(s.toLowerCase())) return '';
+ return s;
+}
+
+/** Pick a date-based fallback slug, scanning sibling dirs to find the next
+ * unused suffix (`chat-YYYY-MM-DD-1` → `-2` → ...). Stable across calls
+ * within the same day (next call gets the next free N). */
+function pickFallbackSlug(workspaceRoot: string): string {
+ const today = new Date();
+ const yyyy = today.getFullYear().toString().padStart(4, '0');
+ const mm = (today.getMonth() + 1).toString().padStart(2, '0');
+ const dd = today.getDate().toString().padStart(2, '0');
+ const base = `chat-${yyyy}-${mm}-${dd}`;
+ for (let n = 1; n < 10000; n++) {
+ const candidate = `${base}-${n}`;
+ if (!fs.existsSync(path.join(workspaceRoot, candidate))) return candidate;
+ }
+ // 10000 chats produced on a single day is well past pathological — caller
+ // sees a unique-but-suffixed name rather than an exception.
+ return `${base}-${Date.now()}`;
+}
+
+/** Return a slug with collisions resolved by `-2` / `-3` / ... suffixing.
+ * Treats an existing dir of the same name as a collision (likely produced
+ * by a different conv with the same title). */
+function uniquifySlug(workspaceRoot: string, slug: string): string {
+ if (!fs.existsSync(path.join(workspaceRoot, slug))) return slug;
+ for (let n = 2; n < 10000; n++) {
+ const candidate = `${slug}-${n}`;
+ if (!fs.existsSync(path.join(workspaceRoot, candidate))) return candidate;
+ }
+ return `${slug}-${Date.now()}`;
+}
+
+/**
+ * Resolve the absolute working directory for `(uid, cid)`. Lazy + frozen:
+ * - if `state.json::workspace_dir` is already set → return `<workspace>/<dir>`
+ * (mkdir if the dir got deleted in the meantime; hot path is the existence-
+ * check fast path)
+ * - else if the conv has no entry yet (genuinely a legacy conv without a
+ * conversation record, or `state.json` not yet written) → return the
+ * user-level workspace verbatim, do NOT persist anything (legacy behaviour)
+ * - else → derive slug from current title, fall back to date-based name on
+ * placeholder, uniquify against sibling dirs, mkdir, persist to
+ * `state.json::workspace_dir`, return the absolute path
+ */
+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) {
+ const abs = path.join(root, cur.workspace_dir);
+ try { await fsp.mkdir(abs, { recursive: true }); } catch { /* race with self / fs hiccup */ }
+ return abs;
+ }
+
+ // 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.
+ let title = '';
+ try {
+ const conv = await getConversation(uid, cid);
+ if (conv) title = conv.title || '';
+ else {
+ log.warn(`no conv record for cid=${cid} — falling back to root workspace`);
+ return root;
+ }
+ } catch (err) {
+ log.warn(`getConversation failed cid=${cid}: ${(err as Error).message} — falling back to root`);
+ return root;
+ }
+
+ let slug = slugifyConvTitle(title);
+ if (!slug) slug = pickFallbackSlug(root);
+ else slug = uniquifySlug(root, slug);
+
+ const abs = path.join(root, slug);
+ try { await fsp.mkdir(abs, { recursive: true }); }
+ catch (err) {
+ log.warn(`mkdir ${abs} failed: ${(err as Error).message} — falling back to root`);
+ return root;
+ }
+
+ // Persist the choice. setWorkspaceDirOnce is idempotent: if a concurrent
+ // call beat us to it, our slug is dropped and we re-read the winner —
+ // mkdir is forgiving about the duplicate dir.
+ const persisted = await setWorkspaceDirOnce(uid, cid, slug);
+ const finalSlug = persisted.workspace_dir || slug;
+ log.info(`cid=${cid} workspace_dir=${finalSlug} (title="${title}")`);
+ return path.join(root, finalSlug);
+}
diff --git a/src/main/features/group_chat/state.ts b/src/main/features/group_chat/state.ts
index f3b804bc..c41969fe 100644
--- a/src/main/features/group_chat/state.ts
+++ b/src/main/features/group_chat/state.ts
@@ -56,6 +56,14 @@ export interface StateFile {
last_active_at: string;
/** Actor ids currently running their worker loop. */
in_flight: string[];
+ /** Per-conversation workspace subdirectory basename (relative to the
+ * user's root workspace). Lazily filled by `conv_workspace.ts` on the
+ * first write_file in this conversation; **empty / missing → legacy
+ * conversations stay at the root workspace** (no migration). Once set
+ * it is **frozen** — renaming the conv title afterwards does not move
+ * the directory or update this field. See `conv_workspace.ts` for the
+ * slug rules and the placeholder fallback. */
+ workspace_dir?: string;
}
export const COMMANDER_ID = 'commander';
@@ -204,6 +212,9 @@ export async function readState(uid: string, cid: string): Promise<StateFile> {
status: (data.status as GroupStatus) || 'idle',
last_active_at: typeof data.last_active_at === 'string' ? data.last_active_at : nowIso(),
in_flight: Array.isArray(data.in_flight) ? data.in_flight.filter((s: unknown) => typeof s === 'string') : [],
+ ...(typeof data.workspace_dir === 'string' && data.workspace_dir
+ ? { workspace_dir: data.workspace_dir }
+ : {}),
};
}
} catch (err) {
@@ -288,6 +299,20 @@ export async function markInFlight(uid: string, cid: string, actorId: string, ru
});
}
+/** Atomically lock in the per-conversation workspace subdirectory basename.
+ * No-op if the field is already set (frozen-on-first-write semantics — see
+ * `conv_workspace.ts`). Returns the resulting state. */
+export async function setWorkspaceDirOnce(uid: string, cid: string, dir: string): Promise<StateFile> {
+ return _stateLock(uid, cid).runExclusive(async () => {
+ const s = await readState(uid, cid);
+ if (s.workspace_dir) return s;
+ s.workspace_dir = dir;
+ s.last_active_at = nowIso();
+ await writeStateRaw(uid, cid, s);
+ return s;
+ });
+}
+
/** Drop the whole group dir (called from chats.deleteConversation). */
export async function purgeGroupDir(uid: string, cid: string): Promise<void> {
const dir = groupChatDir(uid, cid);
diff --git a/src/main/prompts/chat_shared_rules.md b/src/main/prompts/chat_shared_rules.md
index d1b8c0dc..67d1e075 100644
--- a/src/main/prompts/chat_shared_rules.md
+++ b/src/main/prompts/chat_shared_rules.md
@@ -15,7 +15,9 @@ To generate a PDF you **must** use `markdown_to_pdf` (pure markdown) or `html_to
## File output + chat-media usage
-**Writing artifacts**: intermediate and final artifacts **all go under `$working_dir`**, using relative paths. Outputs from `write_file` / `markdown_to_pdf` / `html_to_pdf` automatically appear in the group chat as **clickable chips that include the filename** (clicking a chip opens the file's location in Finder / File Explorer).
+**Writing artifacts**: intermediate and final artifacts **all go under `$working_dir`**, using relative paths. `$working_dir` is the per-conversation subdirectory the system has set up for you, so when the user asks you to redo / refine the same task multiple times you can just **write the same filename again** (e.g. `requirements.md`); the system uniquifies only on real external conflicts, so you do **not** need to manually version basenames to `requirements-v2.md` / `report-final.md` etc. Outputs from `write_file` / `markdown_to_pdf` / `html_to_pdf` automatically appear in the group chat as **clickable chips that include the filename** (clicking a chip opens the file's location in Finder / File Explorer).
+
+**Reading is unrestricted within the user's workspace**: `read_file` / `search_files` / `grep_files` / `bash` / `ls` etc. can still reach files anywhere in the workspace (including artifacts other conversations have produced) when the user references them by absolute path or you locate them through search. The conversation-scoped `$working_dir` only changes where **your own writes land by default**, not what you can read.
**Don't paste absolute paths in your reply**: the chip already gives the user "filename + click to open"; in your text, a single line saying "produced `<filename>`" is enough. **Do not** write the full absolute path (`/Users/xxx/...` etc.) — it's redundant, leaks the home directory, and visually noisy.