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(signals skill metrics + project workspace polish + sidebar/project rail UI)

wytadbf7e4032eb
diff --git a/CLAUDE.md b/CLAUDE.md
index 4d889d37..5d809d76 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -150,7 +150,7 @@ Top-level three-way split: **cloud** (user-private, synced across devices) / **l
- **`LOCAL_DATA_VERSION` data-version gate** (`features/sync/data_version.ts`): every PC build carries an integer schema-version constant; on each pass the engine compares it to `manifest.data_version` post-fetch and aborts with `pause_reason = 'version_outdated'` when `remote > LOCAL_DATA_VERSION` (Server mirrors the same gate on commit → `client_outdated` / 50404, which the engine handles as a sticky pause rather than a retry-able error). **When to bump + when NOT to + bumping procedure** are the MUST / MUST-NOT checklists in `data_version.ts`'s header comment — that file is the single source of truth for the call; don't restate the criteria elsewhere. **Why a third version field** when `manifest_v` and per-entry `schema_v` exist: they answer different questions — `manifest_v` is the manifest JSON's own structure, `schema_v` is per-file content format (with consumption logic still TODO in `merge/`), and `data_version` is the *global* application-data contract gate. Don't conflate them.
8. **`<uid>/local/cache/<bucket>/` is the user-clearable cache umbrella**. Anything dropped under `cache/` is fair game for the "clear cache" UI button (`features/cache_clearable.ts::clearAllClearable`). Distinct from `config/` (user prefs — never auto-cleared) and `biz/` (server-sourced reference data — refresh-on-need but not user-clearable). The marketplace content cache lives at `cache/marketplace/{agents,skills}/<id>/` with a per-entry `_cache.json` carrying `(server_id, version, published_at, fetched_at, last_used_at)`; entry-time sweep evicts entries idle > 7d AND LRU-trims when total > 100 MB (see `features/marketplace_cache.ts::sweepIfNeeded`, called once per `openMarketplace`). **Note**: `local/marketplace/{agents,skills}/<id>/` (the install target — constraint 2) is NOT under `cache/` and is NOT user-clearable; only the staging cache for browsing detail is. Future migration: `file_cache/` and `tool-results/` will move under `cache/` so a single "clear cache" hits all of them — DON'T yet rely on this; each owner module updates its path helper before the move.
-9. **`<uid>/local/signals/<yyyy-mm-dd>.jsonl` is the expert-signal stream** (T0/T1 user-behavior records — retry / skip / form_left_blank / silence / tool_failure / accept / correction / reject / edit / skill_advertised / skill_invoked / agent_dispatched). Local-only, append-only, daily-rotated. **Sole writer for the features layer = `features/expert_signals/emitSignal`**; chokepoint sites are `features/group_chat/bus.ts::runTurn` end + `_enqueueBody` USER_ID branch + `features/group_chat/index.ts::{retryStep, skipStep, markFormSubmittedAndDispatch}` + `features/group_chat/plan_executor.ts::dispatchReady`. **Model-layer signals route through `ChatOptions.{onSkillAdvertised, onSkillInvoked}` callbacks** drained at bus turn-end (`expert_signals/turn_hooks.ts::createSkillTurnBuffer`); **the model layer must never `import { emitSignal }` directly** (would reverse-import features/ and violate §3 layering). **Why centralized**: scattered `emitSignal` across `features/*` (or, post-callback, scattered model-layer imports) violates the single-dispatch-primitive rule (§5) and produces signals whose order disagrees with turn order — downstream reflection / patch suggester / critic (phase 1+) all assume turn-aligned causality. **`turn_id` convention**: every signal's `turn_id` is the agent msg id the signal reacts to or is produced by (agent-side = self; user-reaction = previous agent msg; retry/skip = `step.output_msg_id`; agent_dispatched = synthetic `<cid>:plan:dispatch:<ts>:<i>` since no commander msg id is plumbed through plan_executor yet). Direct JOIN on `turn_id` recovers cross-signal causality (skill_invoked × correction, retry × tool_failure). Phase 0 has NO redaction layer (see §10). Plans: `docs/plans/expert-signals-phase-0.md`, `docs/plans/expert-signals-skill-attribution.md` (phase 0 follow-up for skill / agent attribution).
+9. **`<uid>/local/signals/<yyyy-mm-dd>.jsonl` is the expert-signal stream** (T0/T1 user-behavior records — retry / skip / form_left_blank / silence / tool_failure / accept / correction / reject / edit / skill_advertised / skill_invoked / skill_ineffective / agent_dispatched). Local-only, append-only, daily-rotated. **Sole writer for the features layer = `features/expert_signals/emitSignal`**; chokepoint sites are `features/group_chat/bus.ts::runTurn` end + `_enqueueBody` USER_ID branch + `features/group_chat/index.ts::{retryStep, skipStep, markFormSubmittedAndDispatch}` + `features/group_chat/plan_executor.ts::dispatchReady`. **Model-layer signals route through `ChatOptions.{onSkillAdvertised, onSkillInvoked}` callbacks** drained at bus turn-end (`expert_signals/turn_hooks.ts::createSkillTurnBuffer`); **the model layer must never `import { emitSignal }` directly** (would reverse-import features/ and violate §3 layering). **Why centralized**: scattered `emitSignal` across `features/*` (or, post-callback, scattered model-layer imports) violates the single-dispatch-primitive rule (§5) and produces signals whose order disagrees with turn order — downstream reflection / patch suggester / critic (phase 1+) all assume turn-aligned causality. **`turn_id` convention**: every signal's `turn_id` is the agent msg id the signal reacts to or is produced by (agent-side = self; user-reaction = previous agent msg; retry/skip = `step.output_msg_id`; agent_dispatched = synthetic `<cid>:plan:dispatch:<ts>:<i>` since no commander msg id is plumbed through plan_executor yet). Direct JOIN on `turn_id` recovers cross-signal causality (skill_invoked × correction, retry × tool_failure). Phase 0 has NO redaction layer (see §10). Plans: `docs/plans/expert-signals-phase-0.md`, `docs/plans/expert-signals-skill-attribution.md` (phase 0 follow-up for skill / agent attribution).
**uid lifecycle** (`features/users.ts`): on startup, `initActiveUser()` reads or creates `users.json` and calls `activateUser(uid)` (skeleton mkdir + injecting `process.env.CORE_AGENT_AUTH_DIR` + clearing caches + running migrations including `migrateLegacySessionIds`). All user-scoped features get the uid via `getActiveUserId()` (throws if not activated). One active uid at a time for now. **uid shape is unconstrained** — OrkasOpen first-boot generates 8-digit numeric via `genUserId()`; Hosted Orkas reconciles the local uid with the OAuth-issued user_id via `reconcileDevUid`, which today carries through whatever the server emits (UUID with dashes is real). Code that uses `<uid>/...` as a path segment is fine with any shape (single segment, no parsing). Code that USED to embed `<uid>-` into session_id has been removed (§5 — session_id is now `<kind>-<tail>`); never reintroduce that pattern.
diff --git a/bin/run-skill.cjs b/bin/run-skill.cjs
index ef370b77..4047dba1 100755
--- a/bin/run-skill.cjs
+++ b/bin/run-skill.cjs
@@ -14,16 +14,19 @@
* .sh — spawn `bash`, inherit stdio, exit with child's code.
* .rb — spawn `ruby`, inherit stdio, exit with child's code.
*
- * Resolution order:
- * 1. <uid>/cloud/skills/<id>/scripts/<basename>.<ext> (custom)
- * 2. data/builtin/skills/<id>/scripts/<basename>.<ext> (builtin runtime)
- * 3. <PC>/src/builtin/skills/<id>/scripts/<basename>.<ext> (dev / asar.unpacked)
+ * Resolution order (matches SkillRegistry — see model/core-agent/skill-registry.ts):
+ * 1. <uid>/cloud/skills/<id>/scripts/<basename>.<ext> (custom)
+ * 2. <uid>/local/marketplace/skills/<id>/scripts/<basename>.<ext> (installed)
+ * 3. <PC>/src/builtin/skills/<id>/scripts/<basename>.<ext> (dev / asar.unpacked)
* For each candidate dir we try ts → mjs → js → py → sh → rb in order.
*
* Env inputs:
- * ORKAS_PC_DIR — points at PC root (or asar.unpacked equivalent).
- * ORKAS_WS_ROOT — optional override for data/ root.
- * ELECTRON_RUN_AS_NODE — set to 1 when running through Electron binary.
+ * ORKAS_PC_DIR — points at PC root (or asar.unpacked equivalent).
+ * ORKAS_WORKSPACE_ROOT — canonical workspace-data root (set by main process
+ * in install-data-root.ts). ORKAS_WS_ROOT is honoured
+ * as a back-compat alias. When neither is set the
+ * platform default ~/.orkas/data is used.
+ * ELECTRON_RUN_AS_NODE — set to 1 when running through Electron binary.
*
* This file is CommonJS so it can be required directly without import-hook
* gymnastics. .ts skill scripts use ESM-style default export.
@@ -58,23 +61,33 @@ function parseArgs(argv) {
return { skillId, scriptBase, scriptArgs };
}
+// Sibling directories of WS_ROOT that are NOT user-id dirs. See paths.ts —
+// users.json / window-state.json are files (filtered by isDirectory above);
+// these are the directories we must not treat as uids.
+const RESERVED_WS_DIRS = new Set([
+ 'logs', 'config', 'user_workspaces', 'builtin',
+]);
+
function locateSkillScript(skillId, scriptBase) {
- const wsRoot = process.env.ORKAS_WS_ROOT
- || (process.env.ORKAS_PC_DIR ? path.join(process.env.ORKAS_PC_DIR, 'data') : null)
- || path.join(require('os').homedir(), 'Library', 'Application Support', 'Orkas', 'data');
- // Candidate skill dirs — match SkillRegistry's [<uid>/cloud/skills, data/builtin/skills]
- // resolution, plus a dev/source-tree fallback for builtins.
+ const wsRoot = process.env.ORKAS_WORKSPACE_ROOT
+ || process.env.ORKAS_WS_ROOT
+ || path.join(require('os').homedir(), '.orkas', 'data');
+ // Candidate skill dirs — mirror SkillRegistry's
+ // [<uid>/cloud/skills, <uid>/local/marketplace/skills] resolution, with a
+ // dev/source-tree fallback for unpacked builtins.
const skillDirs = [];
- // Custom skills live under data/<uid>/cloud/skills/<id>/. We don't know the
- // active uid here, so scan every uid dir we can find. In practice there's
- // one active user so this is a 1-element scan.
+ // Per-user skills live under <ws>/<uid>/cloud/skills/<id> and
+ // <ws>/<uid>/local/marketplace/skills/<id>. uid can be numeric or a UUID,
+ // so we scan every non-reserved subdirectory rather than regex-matching.
try {
for (const entry of fs.readdirSync(wsRoot, { withFileTypes: true })) {
- if (!entry.isDirectory() || !/^\d+$/.test(entry.name)) continue;
+ if (!entry.isDirectory()) continue;
+ if (entry.name.startsWith('.')) continue;
+ if (RESERVED_WS_DIRS.has(entry.name)) continue;
skillDirs.push(path.join(wsRoot, entry.name, 'cloud', 'skills', skillId));
+ skillDirs.push(path.join(wsRoot, entry.name, 'local', 'marketplace', 'skills', skillId));
}
} catch { /* no data dir yet */ }
- skillDirs.push(path.join(wsRoot, 'builtin', 'skills', skillId));
if (process.env.ORKAS_PC_DIR) {
skillDirs.push(path.join(process.env.ORKAS_PC_DIR, 'src', 'builtin', 'skills', skillId));
}
@@ -93,7 +106,7 @@ function locateSkillScript(skillId, scriptBase) {
}
die(66, `skill script not found: ${skillId}/${scriptBase}.{${SCRIPT_EXTS.join(',')}}`, {
searched: candidates,
- hint: 'check skill id and script name; ORKAS_PC_DIR / ORKAS_WS_ROOT env',
+ hint: 'check skill id and script name; ORKAS_PC_DIR / ORKAS_WORKSPACE_ROOT env',
});
}
diff --git a/src/main/features/agents.ts b/src/main/features/agents.ts
index 58ab5827..a60ee08a 100644
--- a/src/main/features/agents.ts
+++ b/src/main/features/agents.ts
@@ -176,11 +176,8 @@ export interface Agent {
* unless the user has explicitly disabled the agent. Don't write this
* field back to disk. */
enabled: boolean;
- /** Author uid for `source==='builtin'` (marketplace-installed) agents — read from the
- * install dir's `_install.json`. `"0"` = official-platform marker; non-zero = community
- * uploader. Empty string for `source==='custom'` (no marketplace install meta). Renderer
- * uses this to show the author badge (label `marketplace.author_platform` / `_user`)
- * instead of a generic platform chip on the detail / card. */
+ /** Marketplace author uid. Kept optional for install/reconcile compatibility; global UI
+ * surfaces must not render it. */
create_uid?: string;
/** Marketplace install version for `source==='builtin'`. Read from `_install.json` so the
* agents-tab card can render a `v1.0.0` chip alongside the category. Custom agents leave
@@ -807,15 +804,14 @@ export async function listAgents(): Promise<Agent[]> {
continue;
}
seen.add(norm.agent_id);
- // Marketplace-installed agents carry an `_install.json` sidecar with `create_uid` +
- // `version`. Read it lazily here so the UI can show the author badge and the version
- // chip without an extra IPC round-trip. Custom agents skip — they have no install meta.
+ // Marketplace-installed agents carry an `_install.json` sidecar with `version`.
+ // Author uid may also be present there for install/reconcile compatibility, but the
+ // global UI intentionally does not surface it.
if (source === 'builtin') {
try {
const metaFile = path.join(dir, e.name, '_install.json');
if (fs.existsSync(metaFile)) {
const meta = JSON.parse(fs.readFileSync(metaFile, 'utf8'));
- if (meta && typeof meta.create_uid === 'string') norm.create_uid = meta.create_uid;
if (meta && typeof meta.version === 'string') norm.version = meta.version;
}
} catch { /* corrupt _install.json → leave fields undefined */ }
diff --git a/src/main/features/chats.ts b/src/main/features/chats.ts
index e20a7aff..0ce6a522 100644
--- a/src/main/features/chats.ts
+++ b/src/main/features/chats.ts
@@ -60,6 +60,9 @@ export interface Conversation {
* `<cid>.jsonl`, `groupChatDir`, `chat_attachments`, and `session_id`
* paths stay verbatim, so cid uniqueness + §5 isolation are unaffected. */
project_id?: string;
+ /** Optional sidebar pin timestamp. Pinned conversations sort to the top of
+ * whichever sidebar list currently contains them (project or unprojected). */
+ pinned_at?: string;
created_at: string;
updated_at: string;
/** Derived from group_chat state.json at read time; never persisted on
@@ -136,7 +139,17 @@ export async function listConversations(userId: string): Promise<Conversation[]>
const lastActiveAt = lastActiveMs ? new Date(lastActiveMs).toISOString() : (c.updated_at || c.created_at || '');
out.push({ ...c, processing, processing_since: since, last_active_at: lastActiveAt });
}
- out.sort((a, b) => (b.last_active_at || '').localeCompare(a.last_active_at || ''));
+ out.sort((a, b) => {
+ const ap = a.pinned_at || '';
+ const bp = b.pinned_at || '';
+ if (ap && !bp) return -1;
+ if (!ap && bp) return 1;
+ if (ap && bp) {
+ const pinCmp = bp.localeCompare(ap);
+ if (pinCmp) return pinCmp;
+ }
+ return (b.last_active_at || '').localeCompare(a.last_active_at || '');
+ });
return out;
}
@@ -232,6 +245,22 @@ export async function updateConversation(
return items[i];
}
+export async function setConversationPinned(
+ userId: string, cid: string, pinned: boolean,
+): Promise<Conversation | null> {
+ if (!safeId(cid)) return null;
+ const items = await _readRawConversations(userId);
+ const i = items.findIndex((c) => c.conversation_id === cid);
+ if (i < 0) return null;
+ if (pinned) {
+ if (!items[i].pinned_at) items[i].pinned_at = nowIso();
+ } else {
+ delete items[i].pinned_at;
+ }
+ await saveConversations(userId, items);
+ return getConversation(userId, cid);
+}
+
/** Drop a session jsonl + its in-memory cache entry. Routes through
* resolveSessionPath so kind (cloud vs local) is respected. */
function purgeSession(userId: string, sessionId: string): void {
@@ -360,9 +389,38 @@ export async function deleteConversationsByAgent(agentId: string): Promise<numbe
return total;
}
+// Filler-word prefixes commonly written before the actual ask. Ordered
+// longest-first within each regex so JS regex alternation (left-biased)
+// doesn't match a shorter prefix when a longer one is also valid. Single-
+// character fillers (e.g. bare `请`) are intentionally NOT listed — too
+// likely to clip real content like `请教...`.
+const ZH_FILLER_RE = /^(帮我看一下|可不可以|帮我看下|帮我看看|麻烦你|帮我看|我想要|想问问|能不能|可以不|可以吗|请帮我|看一下|麻烦|帮我|我想|想问|请问|看下|看看)\s*/;
+const EN_FILLER_RE = /^(could you|would you|can you|help me|i'?d like to|i want to|please)\s+/i;
+const CLAUSE_RE = /[,。?!;;,.?!]/;
+const TITLE_MAX = 30;
+
export function autoTitle(content: string): string {
- let text = (content || '').trim().replace(/\n/g, ' ');
- if (text.length > 40) text = text.slice(0, 40) + '…';
+ const raw = (content || '').trim().replace(/\s+/g, ' ');
+ if (!raw) return t('chat.default_title');
+ let text = raw;
+ // Strip stacked fillers ("请帮我看下..." → "请帮我" first, then "看下");
+ // cap iterations so a pathological self-similar prefix can't loop.
+ for (let i = 0; i < 5; i++) {
+ const before = text;
+ text = text.replace(ZH_FILLER_RE, '').replace(EN_FILLER_RE, '');
+ if (text === before) break;
+ }
+ text = text.trim();
+ // Take the first clause IF it's long enough on its own — guards against
+ // clipping "AI,怎么样" down to bare "AI" which loses all signal.
+ const clauseIdx = text.search(CLAUSE_RE);
+ if (clauseIdx >= 4) text = text.slice(0, clauseIdx);
+ text = text.trim();
+ // If stripping killed everything (input was pure filler), fall back to
+ // the original trimmed input so the sidebar still shows what the user
+ // actually typed.
+ if (!text) text = raw;
+ if (text.length > TITLE_MAX) text = text.slice(0, TITLE_MAX) + '…';
return text || t('chat.default_title');
}
diff --git a/src/main/features/expert_signals/extractors/event.ts b/src/main/features/expert_signals/extractors/event.ts
index 6837203f..74499609 100644
--- a/src/main/features/expert_signals/extractors/event.ts
+++ b/src/main/features/expert_signals/extractors/event.ts
@@ -160,6 +160,37 @@ export function buildSkillAdvertisedSignal(args: {
};
}
+/** Emitted at turn-end when a `skill_invoked` happened AND the turn ended
+ * with a non-transient, non-aborted error. One signal per (turn, system,
+ * skill_id) — same granularity as `skill_invoked` so consumers can JOIN
+ * the two directly. `error_kind` is hardcoded `'permanent'` for v0; a
+ * future session-jsonl scanner could refine to `'mixed'` when some tool
+ * calls in the same turn succeeded. */
+export function buildSkillIneffectiveSignal(args: {
+ cid: string;
+ aid: string | null;
+ turn_id: string;
+ system: SkillSystem;
+ skill_id: string;
+ error_excerpt: string;
+ msg_ids?: string[];
+}): SignalInput {
+ return {
+ type: 'skill_ineffective',
+ source: 'event',
+ cid: args.cid,
+ aid: args.aid,
+ turn_id: args.turn_id,
+ context_ref: { msg_ids: args.msg_ids || [] },
+ extractor_version: EXTRACTOR_VERSION.skill_attribution,
+ delta: { system: args.system, skill_id: args.skill_id },
+ metadata: {
+ error_excerpt: args.error_excerpt.slice(0, 200),
+ error_kind: 'permanent',
+ },
+ };
+}
+
/** Emitted when the agent's `read_file` resolves to a SKILL.md path inside
* one of the three skill roots. Same turn can produce multiple invoked
* signals for distinct skills; consumers de-dup by (turn_id, system, skill_id). */
diff --git a/src/main/features/expert_signals/turn_hooks.ts b/src/main/features/expert_signals/turn_hooks.ts
index 7ca7d7ec..40863cf4 100644
--- a/src/main/features/expert_signals/turn_hooks.ts
+++ b/src/main/features/expert_signals/turn_hooks.ts
@@ -14,7 +14,9 @@
import { emitSignal } from './index';
import { extractTextSignals } from './extractors/text';
+import { isTransientError } from '../../util/transient-errors';
import {
+ buildSkillIneffectiveSignal,
buildToolFailureSignal,
buildSkillAdvertisedSignal,
buildSkillInvokedSignal,
@@ -67,7 +69,19 @@ function _key(uid: string, cid: string): string { return `${uid}:${cid}`; }
export interface SkillTurnBuffer {
recordAdvertised(skill_id: string, system: SkillSystem): void;
recordInvoked(skill_id: string, system: SkillSystem, trigger: SkillInvokeTrigger): void;
- drainAndEmit(args: { uid: string; cid: string; aid: string | null; turn_id: string; msg_ids: string[] }): void;
+ /** Drain the buffer at turn-end.
+ * - `errText` / `aborted`: when provided, the buffer emits one
+ * `skill_ineffective` per invoked (system, skill_id) iff `errText`
+ * is non-empty, NOT classified transient (network-class blip
+ * excluded), AND `!aborted` (user-stopped turns aren't the skill's
+ * fault). Omitting both keeps the legacy advertised+invoked emit
+ * behaviour. */
+ drainAndEmit(args: {
+ uid: string; cid: string; aid: string | null;
+ turn_id: string; msg_ids: string[];
+ errText?: string;
+ aborted?: boolean;
+ }): void;
}
export function createSkillTurnBuffer(): SkillTurnBuffer {
@@ -95,7 +109,7 @@ export function createSkillTurnBuffer(): SkillTurnBuffer {
if (!skill_id) return;
invoked.add(enc(system, skill_id));
},
- drainAndEmit({ uid, cid, aid, turn_id, msg_ids }) {
+ drainAndEmit({ uid, cid, aid, turn_id, msg_ids, errText, aborted }) {
if (!turn_id) {
// Without a turn id (= agent msg id) the signal can't be joined to
// anything else — drop instead of emitting a useless record.
@@ -126,6 +140,27 @@ export function createSkillTurnBuffer(): SkillTurnBuffer {
cid, aid, turn_id, system, skill_id, trigger: 'read_file', msg_ids,
}));
}
+ // skill_ineffective: skill was loaded and the turn ended with a
+ // non-transient, non-aborted error. One signal per invoked skill
+ // — over-attribute on purpose when multiple skills loaded in the
+ // same failing turn; downstream consumers (skill_metrics) can
+ // weight or filter. See `expert-signals-skill-ineffective.md`.
+ const errExcerpt = (errText || '').trim();
+ if (
+ errExcerpt
+ && !aborted
+ && !isTransientError(errExcerpt)
+ && invoked.size > 0
+ ) {
+ for (const k of invoked) {
+ const { system, skill_id } = dec(k);
+ emitSignal(uid, buildSkillIneffectiveSignal({
+ cid, aid, turn_id, system, skill_id,
+ error_excerpt: errExcerpt,
+ msg_ids,
+ }));
+ }
+ }
advertised.clear();
invoked.clear();
},
diff --git a/src/main/features/expert_signals/types.ts b/src/main/features/expert_signals/types.ts
index 2fc3e766..a789bcf2 100644
--- a/src/main/features/expert_signals/types.ts
+++ b/src/main/features/expert_signals/types.ts
@@ -25,6 +25,7 @@ export type SignalType =
| 'edit' // T1: user message token-diffed significantly from agent's last text
| 'skill_advertised' // T0: skills entered system prompt index at turn start (per system)
| 'skill_invoked' // T0: agent read_file'd a SKILL.md body during the turn
+ | 'skill_ineffective' // T0: skill_invoked in a turn that ended with a non-transient, non-aborted error
| 'agent_dispatched'; // T0: commander dispatched ready plan steps (candidates + dispatched)
/** Which skill catalog produced a `skill_advertised` / `skill_invoked` signal.
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index eab44d8e..79bcb962 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -54,7 +54,7 @@ import { isAgentEnabled } from '../component_enabled';
import { buildLanguageDirective, descriptionLang, t } from '../../i18n';
import * as marketplaceFeat from '../marketplace';
import { readInstalls } from '../marketplace_installs';
-import { createSkillTurnBuffer } from '../expert_signals/turn_hooks';
+import { createSkillTurnBuffer, onAgentTurnEnd, onUserMessage } from '../expert_signals/turn_hooks';
const log = createLogger('group_chat.bus');
@@ -722,6 +722,16 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro
// echo and the downstream dispatch, which is exactly how form submissions
// ended up as fake loading bubbles until history polling caught up.
if (fromActorId === USER_ID) {
+ // Phase-0 chokepoint (was lost from commit 76358a8e per
+ // `docs/plans/expert-signals-phase0-wiring-gaps.md`): cancels pending
+ // silence check + extracts text-class signals (accept / correction /
+ // reject / edit) against the cached last agent message. Fire-and-
+ // forget; correctionDetected return value is intentionally unused
+ // here (runner.ts:665 does its own detectUserCorrection for
+ // RunMetrics — acceptable double-judgment for v0).
+ onUserMessage({ uid, cid, userMsg: { id: msgId, text: rewrittenText } })
+ .catch((err) => log.warn(`onUserMessage threw cid=${cid}: ${(err as Error).message}`));
+
await planExecutor.reconcile(uid, cid, {
finishedActorId: USER_ID,
finishedMessage: { id: msgId, text: rewrittenText, files: [], failed: false },
@@ -1649,6 +1659,20 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
aid: actor.kind === 'commander' ? null : actor.id,
turn_id: persistedMsg.id,
msg_ids: [persistedMsg.id],
+ errText: errText || undefined,
+ aborted,
+ });
+ // Phase-0 chokepoint (was lost from commit 76358a8e per
+ // `docs/plans/expert-signals-phase0-wiring-gaps.md`): caches agent msg
+ // for the next user-reply text-signal JOIN, emits tool_failure when
+ // errText is set, schedules silence check (cancelled by onUserMessage
+ // when the user replies). Sync + self-guarded against errors.
+ onAgentTurnEnd({
+ uid, cid,
+ actorId: actor.id,
+ isCommander: actor.kind === 'commander',
+ agentMsg: { id: persistedMsg.id, text: persistedMsg.text || '' },
+ errText: errText || undefined,
});
}
diff --git a/src/main/features/group_chat/plan_executor.ts b/src/main/features/group_chat/plan_executor.ts
index 1129ae4e..be7c65f1 100644
--- a/src/main/features/group_chat/plan_executor.ts
+++ b/src/main/features/group_chat/plan_executor.ts
@@ -29,6 +29,7 @@ import { createLogger } from '../../logger';
import { t } from '../../i18n';
import { userChatsDir } from '../../paths';
import { readJsonl } from '../../storage';
+import { isTransientError } from '../../util/transient-errors';
import { COMMANDER_ID, USER_ID, readMembers } from './state';
import {
readPlan, updateStep, markPlanCompletedSignaled,
@@ -69,10 +70,11 @@ const USER_ALIASES = new Set(['user', '用户']);
* (fresh stream, fresh provider connection). Capped to avoid infinite
* loops when the user is just genuinely offline.
*
- * IMPORTANT — never include `aborted` or `cancelled` in this pattern:
- * user-initiated abort must not be silently retried; the literal string
- * `'aborted by user'` is also explicitly excluded by the guard. */
-const TRANSIENT_ERR_PATTERNS = /\b(terminated|fetch failed|ECONNRESET|ETIMEDOUT|ECONNREFUSED|EAI_AGAIN|socket hang up|EPIPE|network error|Connection closed)\b/i;
+ * Pattern lives in `util/transient-errors.ts` as a shared classifier
+ * — `features/expert_signals/turn_hooks.ts` is the second consumer
+ * (skill_ineffective skips transient-class errors so we don't blame
+ * skills for network blips). Single source of truth for "is this
+ * a network blip" semantics. */
const MAX_TRANSIENT_RETRIES = 2;
/** Returns true when `reason` matches a transient network-error pattern AND
@@ -84,7 +86,7 @@ async function maybeRetryTransient(
): Promise<boolean> {
if (!reason) return false;
if (reason === 'aborted by user') return false;
- if (!TRANSIENT_ERR_PATTERNS.test(reason)) return false;
+ if (!isTransientError(reason)) return false;
const attempts = step.transient_attempts ?? 0;
if (attempts >= MAX_TRANSIENT_RETRIES) return false;
await updateStep(uid, cid, step.index, 'pending', {
diff --git a/src/main/features/skill_metrics.ts b/src/main/features/skill_metrics.ts
new file mode 100644
index 00000000..14707e10
--- /dev/null
+++ b/src/main/features/skill_metrics.ts
@@ -0,0 +1,192 @@
+/**
+ * Skill metrics — phase 1 consumer of expert_signals.
+ *
+ * Aggregates the four skill-related signal kinds emitted in phase 0
+ * (`skill_advertised` / `skill_invoked` / `correction` + `edit` /
+ * `skill_ineffective`) into a per-skill dashboard row. Surfaces three
+ * indicators per CLAUDE.md docs/evaluation/skill_dynamic_evaluation.md:
+ *
+ * - **invocation_rate** = invoked / advertised
+ * "When the skill is in the system prompt, how often does the agent
+ * actually read it?"
+ * - **modified_after_hit_rate** = mod / invoked
+ * "When the skill is read, how often does the user react with a
+ * correction / edit in the same turn?"
+ * - **ineffective_rate** = ineffective / invoked
+ * "When the skill is read, how often does the turn end with a
+ * non-transient error?" (negative-transfer proxy via the new T0
+ * `skill_ineffective` signal — `expert-signals-skill-ineffective.md`.)
+ *
+ * Aggregation key is `(skill_id, skill_system)` — v0 ignores `aid`
+ * (per-agent drill-down deferred). Rationale: the user's primary
+ * question is "is this skill paying off?", which is a per-skill answer.
+ * Per-agent breakdown can be re-added when actually requested.
+ *
+ * Display name resolution falls through `listSkills()` (covers A.custom +
+ * A.platform via the SkillLoader cache); B-system skills (agent self-
+ * evolved) fall back to `skill_id` since their id == name by convention
+ * (CLAUDE.md §6).
+ */
+
+import { querySignals } from './expert_signals';
+import { listSkills } from './skills';
+import type { Signal } from './expert_signals/types';
+import type { SkillSystem } from './expert_signals/types';
+import { createLogger } from '../logger';
+
+const log = createLogger('skill-metrics');
+
+const DEFAULT_DAYS = 7;
+const QUERY_HARD_LIMIT = 10_000;
+
+export interface SkillMetricRow {
+ skill_id: string;
+ skill_system: SkillSystem;
+ display_name: string;
+ advertised: number;
+ invoked: number;
+ invocation_rate: number; // invoked / max(advertised, 1)
+ modified_after_hit: number;
+ modified_after_hit_rate: number; // modified_after_hit / max(invoked, 1)
+ ineffective: number;
+ ineffective_rate: number; // ineffective / max(invoked, 1)
+}
+
+export interface SkillMetricsReport {
+ range: { since: string; until: string };
+ rows: SkillMetricRow[];
+ total_signals_scanned: number;
+}
+
+export interface SkillMetricsOpts {
+ /** Window size in days ending now. Defaults to 7. */
+ sinceDays?: number;
+}
+
+export async function aggregateSkillMetrics(
+ opts: SkillMetricsOpts = {},
+): Promise<SkillMetricsReport> {
+ const days = Math.max(1, opts.sinceDays ?? DEFAULT_DAYS);
+ const until = new Date();
+ const since = new Date(until.getTime() - days * 24 * 60 * 60 * 1000);
+ const sinceIso = since.toISOString();
+ const untilIso = until.toISOString();
+
+ let signals: Signal[];
+ try {
+ signals = await querySignals({
+ since: sinceIso,
+ until: untilIso,
+ types: ['skill_advertised', 'skill_invoked', 'correction', 'edit', 'skill_ineffective'],
+ limit: QUERY_HARD_LIMIT,
+ });
+ } catch (err) {
+ log.warn(`querySignals failed: ${(err as Error).message}`);
+ return { range: { since: sinceIso, until: untilIso }, rows: [], total_signals_scanned: 0 };
+ }
+
+ // Per-skill counts keyed by `${system}::${skill_id}` — `::` is safe
+ // because neither system labels (A.custom / A.platform / B) nor skill
+ // ids (kebab / snake / 12-hex per CLAUDE.md §6) contain it.
+ const advert = new Map<string, number>();
+ const invoke = new Map<string, number>();
+ const ineffective = new Map<string, number>();
+ // Per-turn JOIN side: which skills were invoked, and did the user
+ // react with a correction/edit?
+ const turnInvokes = new Map<string, Set<string>>();
+ const turnHadReaction = new Set<string>();
+
+ for (const sig of signals) {
+ if (sig.type === 'skill_advertised') {
+ const system = sig.delta?.system;
+ const ids = sig.delta?.skill_ids;
+ if (!system || !ids) continue;
+ for (const id of ids) {
+ const k = `${system}::${id}`;
+ advert.set(k, (advert.get(k) || 0) + 1);
+ }
+ } else if (sig.type === 'skill_invoked') {
+ const system = sig.delta?.system;
+ const id = sig.delta?.skill_id;
+ if (!system || !id) continue;
+ const k = `${system}::${id}`;
+ invoke.set(k, (invoke.get(k) || 0) + 1);
+ // Buffer for the per-turn JOIN below.
+ let set = turnInvokes.get(sig.turn_id);
+ if (!set) { set = new Set(); turnInvokes.set(sig.turn_id, set); }
+ set.add(k);
+ } else if (sig.type === 'correction' || sig.type === 'edit') {
+ turnHadReaction.add(sig.turn_id);
+ } else if (sig.type === 'skill_ineffective') {
+ const system = sig.delta?.system;
+ const id = sig.delta?.skill_id;
+ if (!system || !id) continue;
+ const k = `${system}::${id}`;
+ ineffective.set(k, (ineffective.get(k) || 0) + 1);
+ }
+ }
+
+ // Modified-after-hit JOIN: a turn with both `skill_invoked` and one
+ // of (correction | edit) credits every skill invoked in that turn.
+ // Over-attributes on purpose when multiple skills load in one turn —
+ // the alternative is causal attribution we don't have.
+ const modifiedAfterHit = new Map<string, number>();
+ for (const [turn_id, keys] of turnInvokes) {
+ if (!turnHadReaction.has(turn_id)) continue;
+ for (const k of keys) {
+ modifiedAfterHit.set(k, (modifiedAfterHit.get(k) || 0) + 1);
+ }
+ }
+
+ // Display-name lookup — listSkills() is mtime-cached per directory
+ // (features/skills.ts:_skillDirStamp) so this is cheap. Returns the
+ // SKILL.md frontmatter `name`; falls back to skill_id when the entry
+ // is missing (B-system skills, freshly-uninstalled platform skills).
+ const nameMap = new Map<string, string>();
+ try {
+ const skills = await listSkills();
+ for (const s of skills) nameMap.set(s.id, s.name || s.id);
+ } catch (err) {
+ log.warn(`listSkills failed (display names will fall back to ids): ${(err as Error).message}`);
+ }
+
+ const keys = new Set<string>([...advert.keys(), ...invoke.keys(), ...ineffective.keys()]);
+ const rows: SkillMetricRow[] = [];
+ for (const k of keys) {
+ const [system, id] = _decodeKey(k);
+ const ad = advert.get(k) || 0;
+ const iv = invoke.get(k) || 0;
+ const moh = modifiedAfterHit.get(k) || 0;
+ const ineff = ineffective.get(k) || 0;
+ rows.push({
+ skill_id: id,
+ skill_system: system,
+ display_name: nameMap.get(id) || id,
+ advertised: ad,
+ invoked: iv,
+ invocation_rate: ad > 0 ? iv / ad : 0,
+ modified_after_hit: moh,
+ modified_after_hit_rate: iv > 0 ? moh / iv : 0,
+ ineffective: ineff,
+ ineffective_rate: iv > 0 ? ineff / iv : 0,
+ });
+ }
+
+ // Sort heuristic: surface "dead weight" first (advertised a lot,
+ // invoked little). Ties broken by skill_id for deterministic output.
+ rows.sort((a, b) =>
+ (b.advertised - b.invoked) - (a.advertised - a.invoked)
+ || a.skill_id.localeCompare(b.skill_id)
+ );
+
+ return {
+ range: { since: sinceIso, until: untilIso },
+ rows,
+ total_signals_scanned: signals.length,
+ };
+}
+
+function _decodeKey(k: string): [SkillSystem, string] {
+ const i = k.indexOf('::');
+ return [k.slice(0, i) as SkillSystem, k.slice(i + 2)];
+}
diff --git a/src/main/features/skills.ts b/src/main/features/skills.ts
index 3e746385..bf9cf1d4 100644
--- a/src/main/features/skills.ts
+++ b/src/main/features/skills.ts
@@ -98,9 +98,8 @@ export interface SkillListing {
* `features/component_enabled.ts`. Defaults to true unless the user has
* explicitly disabled the skill. */
enabled: boolean;
- /** Author uid for `source==='builtin'` (marketplace-installed) skills — read from
- * `_install.json`. `"0"` = official-platform marker; empty for `source==='custom'`. Renderer
- * uses this to show the author badge (label `marketplace.author_platform` / `_user`). */
+ /** Marketplace author uid. Kept optional for install/reconcile compatibility; global UI
+ * surfaces must not render it. */
create_uid?: string;
/** Marketplace install version for `source==='builtin'`. Read from `_install.json` so the
* skills-tab card can render a `v1.0.0` chip. Undefined for custom skills. */
@@ -356,7 +355,6 @@ export async function listSkills(): Promise<SkillListing[]> {
let displayName = name;
let descPair = { description_zh: '', description_en: '' };
let category = '';
- let createUid: string | undefined;
let version: string | undefined;
if (fs.existsSync(skillMd)) {
try {
@@ -366,19 +364,19 @@ export async function listSkills(): Promise<SkillListing[]> {
category = (meta.category as string) || '';
} catch { /* ignore */ }
}
- // Marketplace-installed skills carry `_install.json` with `create_uid` + `version` —
- // read it so the UI can show the author badge + version chips without an extra IPC. Custom skills skip.
+ // Marketplace-installed skills carry `_install.json` with `version`. Author uid may also
+ // be present for install/reconcile compatibility, but the global UI intentionally does
+ // not surface it.
if (source === 'builtin') {
try {
const metaFile = path.join(baseDir, name, '_install.json');
if (fs.existsSync(metaFile)) {
const meta = JSON.parse(fs.readFileSync(metaFile, 'utf8'));
- if (meta && typeof meta.create_uid === 'string') createUid = meta.create_uid;
if (meta && typeof meta.version === 'string') version = meta.version;
}
} catch { /* corrupt _install.json — leave fields undefined */ }
}
- out.push({ id: name, name: displayName, source, ...descPair, category, enabled: true, create_uid: createUid, version });
+ out.push({ id: name, name: displayName, source, ...descPair, category, enabled: true, create_uid: undefined, version });
}
}
_skillListCache = { stamp, data: out };
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts
index d291018d..e11ed467 100644
--- a/src/main/ipc/index.ts
+++ b/src/main/ipc/index.ts
@@ -159,6 +159,13 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { deleted: ok };
},
+ 'conversations.pin': async ({ cid, pinned }, ctx) => {
+ if (!safeId(cid)) throw new Error('invalid cid');
+ const conv = await chats.setConversationPinned(ctx.userId, cid, !!pinned);
+ if (!conv) throw new Error('conversation not found');
+ return { conversation: conv };
+ },
+
'conversations.deleteAll': async (_args, ctx) => {
const deleted = await chats.deleteAllConversations(ctx.userId);
return { deleted };
@@ -1160,6 +1167,28 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { ok: true, path: target };
},
+ // Dev-only debug panel data. All handlers no-op in packaged builds
+ // (return empty list / null / 0) so the renderer-side panel gracefully
+ // shows "nothing to show here".
+ 'devtools.listArchives': async () => devtools.listArchives(),
+ 'devtools.readArchive': async ({ id }) => devtools.readArchive(String(id || '')),
+ 'devtools.clearArchives': async () => devtools.clearArchives(),
+ 'devtools.getNativeSearchEnabled': async () => ({ enabled: devtools.isNativeSearchEnabled() }),
+ 'devtools.setNativeSearchEnabled': async ({ enabled }) => {
+ devtools.setNativeSearchEnabled(!!enabled);
+ return { enabled: devtools.isNativeSearchEnabled() };
+ },
+ // Skill metrics — phase-1 consumer of expert_signals. Aggregates the
+ // last N days of skill_advertised / skill_invoked / correction / edit /
+ // skill_ineffective into a per-skill dashboard row. UI lives in the
+ // devtools panel for v0; not dev-only at the backend (data is general
+ // user-private signals, surfaced inside devtools per plan §3.3
+ // "先给专家自己看").
+ 'devtools.skillMetricsReport': async ({ sinceDays } = {}) => {
+ const { aggregateSkillMetrics } = await import('../features/skill_metrics');
+ return aggregateSkillMetrics({ sinceDays: Number.isFinite(sinceDays) ? Number(sinceDays) : undefined });
+ },
+
// Local CLI agent discovery (claude / codex / openclaw / opencode / hermes).
// Discovery + model catalogs only; actual spawning happens inside group_chat
// dispatch via `features/local_agents/runner.ts`, never as a standalone IPC.
diff --git a/src/main/util/transient-errors.ts b/src/main/util/transient-errors.ts
new file mode 100644
index 00000000..d8ccfcf7
--- /dev/null
+++ b/src/main/util/transient-errors.ts
@@ -0,0 +1,30 @@
+/**
+ * Shared classifier for "transient network-class error" vs everything else.
+ *
+ * Two consumers as of 2026-05-20:
+ * - `features/group_chat/plan_executor.ts::maybeRetryTransient` — caps
+ * plan-step retries to network blips, NEVER retries permanent errors
+ * (would mask config / spec / sandbox issues + send the user-facing
+ * failure bubble into a silent retry loop).
+ * - `features/expert_signals/turn_hooks.ts::SkillTurnBuffer.drainAndEmit`
+ * — `skill_ineffective` is only emitted when a turn's errText is
+ * non-transient, so we don't blame skills for network blips.
+ *
+ * IMPORTANT — never include `aborted` or `cancelled` in this pattern:
+ * user-initiated abort must not be silently retried; the literal string
+ * `'aborted by user'` is also explicitly excluded by the guard at the
+ * caller site (see `plan_executor.ts::maybeRetryTransient`).
+ *
+ * Pattern is intentionally narrow: undici / fetch / DNS / socket-layer
+ * signals only. Spec-missing / LLM gibberish / parse failures / sandbox
+ * rejections are all permanent by construction — they don't go away on
+ * retry, and they ARE the failures where a loaded skill might have
+ * misled the model (the signal that `skill_ineffective` exists to catch).
+ */
+
+const TRANSIENT_ERR_PATTERNS = /\b(terminated|fetch failed|ECONNRESET|ETIMEDOUT|ECONNREFUSED|EAI_AGAIN|socket hang up|EPIPE|network error|Connection closed)\b/i;
+
+export function isTransientError(reason: string | null | undefined): boolean {
+ if (!reason) return false;
+ return TRANSIENT_ERR_PATTERNS.test(reason);
+}
diff --git a/src/renderer/index.html b/src/renderer/index.html
index 56708b15..dca54216 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -25,12 +25,12 @@
</span>
</button>
<div class="sidebar-actions">
- <button class="sidebar-btn primary" id="new-chat-btn" data-i18n="sidebar.new_chat">Commander</button>
- <button class="sidebar-btn" id="agents-btn" data-i18n="sidebar.agents">Agents</button>
- <button class="sidebar-btn" id="skills-btn" data-i18n="sidebar.skills">Skills</button>
- <button class="sidebar-btn" id="connectors-btn" data-i18n="sidebar.connectors">Connectors</button>
- <button class="sidebar-btn" id="contexts-btn" data-i18n="sidebar.contexts">Knowledge</button>
- <button class="sidebar-btn" id="apps-btn" data-i18n="sidebar.apps">My Apps</button>
+ <button class="sidebar-btn primary" id="new-chat-btn"><span data-ui-icon="message-square" data-ui-icon-class="sidebar-btn-icon"></span><span data-i18n="sidebar.new_chat">Commander</span></button>
+ <button class="sidebar-btn" id="agents-btn"><span data-ui-icon="users" data-ui-icon-class="sidebar-btn-icon"></span><span data-i18n="sidebar.agents">Agents</span></button>
+ <button class="sidebar-btn" id="skills-btn"><span data-ui-icon="sparkles" data-ui-icon-class="sidebar-btn-icon"></span><span data-i18n="sidebar.skills">Skills</span></button>
+ <button class="sidebar-btn" id="connectors-btn"><span data-ui-icon="plug" data-ui-icon-class="sidebar-btn-icon"></span><span data-i18n="sidebar.connectors">Connectors</span></button>
+ <button class="sidebar-btn" id="contexts-btn"><span data-ui-icon="book-open" data-ui-icon-class="sidebar-btn-icon"></span><span data-i18n="sidebar.contexts">Knowledge</span></button>
+ <button class="sidebar-btn" id="apps-btn"><span data-ui-icon="layout-grid" data-ui-icon-class="sidebar-btn-icon"></span><span data-i18n="sidebar.apps">My Apps</span></button>
</div>
<div class="sidebar-conversation-nav">
<div class="sidebar-section sidebar-projects-section">
@@ -60,6 +60,10 @@
<span data-i18n="sidebar.devtools">Devtools</span>
</button>
</div>
+ <div class="sidebar-resize-handle" id="sidebar-resize-handle"
+ role="separator" aria-orientation="vertical"
+ data-i18n-title="sidebar.resize_title"
+ title="Drag to resize · double-click to reset"></div>
</aside>
<main class="main-content">
@@ -77,7 +81,7 @@
<div class="chat-input-overlay">
<div class="chat-attachments" id="new-chat-attachments" style="display:none"></div>
</div>
- <textarea id="new-chat-input" data-i18n-placeholder="new_chat.input_placeholder" placeholder="Type a message. Use @ to call agents, skills, connectors." rows="2"></textarea>
+ <textarea id="new-chat-input" data-i18n-placeholder="new_chat.input_placeholder" placeholder="Type @ to choose agents, skills, connectors." rows="2"></textarea>
<div class="chat-bottom-bar">
<button type="button" class="chat-attach-btn" id="new-chat-attach-btn" data-i18n-title="new_chat.attach_title" title="Upload attachment (text / PDF / Word / image / video)">+</button>
<!-- Voice-to-text mic button (stripped in OrkasOpen — see OpenSource/SyncCode/strip-rules.json). -->
@@ -167,7 +171,7 @@
<div class="chat-attachments" id="chat-attachments" style="display:none"></div>
</div>
<div class="chat-quote-preview" id="chat-quote-preview" style="display:none"></div>
- <textarea id="chat-input" data-i18n-placeholder="chat.input_placeholder" placeholder="Continue the conversation. Use @ to call agents, skills, connectors." rows="2"></textarea>
+ <textarea id="chat-input" data-i18n-placeholder="chat.input_placeholder" placeholder="Type @ to choose agents, skills, connectors." rows="2"></textarea>
<div class="chat-bottom-bar">
<button type="button" class="chat-attach-btn" id="chat-attach-btn" data-i18n-title="chat.attach_title" title="Upload attachment (text / PDF / Word / image / video)">+</button>
<!-- Voice-to-text mic button (stripped in OrkasOpen — see OpenSource/SyncCode/strip-rules.json). -->
@@ -875,6 +879,118 @@
</div>
</section>
+ <!-- Devtools (dev-only) -->
+ <section class="panel" id="panel-devtools">
+ <div class="devtools-container">
+ <div class="devtools-header">
+ <h2 data-i18n="devtools.title">Devtools</h2>
+ <div class="devtools-sub" data-i18n="devtools.subtitle">Dev mode only</div>
+ </div>
+
+ <!-- System info -->
+ <div class="devtools-card" id="devtools-card-sysinfo">
+ <div class="devtools-card-header">
+ <span class="devtools-card-title" data-i18n="devtools.sysinfo_title">System info</span>
+ <span class="devtools-card-actions">
+ <button class="btn btn-sm" id="devtools-sysinfo-copy-btn" data-i18n-title="devtools.copy_title" title="Copy as text" data-i18n="devtools.copy">Copy</button>
+ </span>
+ </div>
+ <div class="devtools-sysinfo-grid" id="devtools-sysinfo-grid"></div>
+ </div>
+
+ <!-- Refresh / Relaunch -->
+ <div class="devtools-card" id="devtools-card-relaunch">
+ <div class="devtools-card-header">
+ <span class="devtools-card-title" data-i18n="devtools.relaunch_title">Relaunch</span>
+ <span class="devtools-card-sub" data-i18n="devtools.relaunch_sub">Relaunch the Orkas process so local code changes take effect</span>
+ </div>
+ <div class="devtools-relaunch-row">
+ <button class="btn btn-sm btn-primary" id="devtools-relaunch-btn" data-i18n="devtools.relaunch_btn">Relaunch (Cmd/Ctrl + Shift + R)</button>
+ </div>
+ </div>
+
+ <!-- Model-native web search toggle -->
+ <div class="devtools-card" id="devtools-card-native-search">
+ <div class="devtools-card-header">
+ <span class="devtools-card-title" data-i18n="devtools.native_search_title">Model native web search</span>
+ <span class="devtools-card-sub" data-i18n="devtools.native_search_sub">When enabled, injects model server-side search tool on supported models. In-memory only, defaults on after restart.</span>
+ </div>
+ <label class="devtools-toggle-row">
+ <input type="checkbox" id="devtools-native-search-toggle" checked />
+ <span data-i18n="devtools.native_search_toggle">Enable model-native web search (OpenAI / Anthropic / Google)</span>
+ </label>
+ </div>
+
+ <!-- Skill metrics dashboard -->
+ <div class="devtools-card devtools-card-skill-metrics" id="devtools-card-skill-metrics">
+ <div class="devtools-card-header">
+ <span class="devtools-card-title" data-i18n="devtools.skill_metrics.title">Skill metrics</span>
+ <span class="devtools-card-sub" data-i18n="devtools.skill_metrics.sub">Aggregated from expert signals — invocation rate / modified-after-hit / negative transfer per skill</span>
+ <span class="devtools-card-actions">
+ <span class="devtools-skill-metrics-days" id="devtools-skill-metrics-days" role="group">
+ <button class="btn btn-sm" data-days="1" data-i18n="devtools.skill_metrics.days_1">1d</button>
+ <button class="btn btn-sm active" data-days="7" data-i18n="devtools.skill_metrics.days_7">7d</button>
+ <button class="btn btn-sm" data-days="30" data-i18n="devtools.skill_metrics.days_30">30d</button>
+ </span>
+ <button class="btn btn-sm" id="devtools-skill-metrics-refresh-btn" data-i18n="devtools.refresh">Refresh</button>
+ </span>
+ </div>
+ <div class="devtools-skill-metrics-summary" id="devtools-skill-metrics-summary"></div>
+ <div class="devtools-skill-metrics-body" id="devtools-skill-metrics-body">
+ <div class="devtools-empty" data-i18n="devtools.skill_metrics.empty">(no signals in the selected range)</div>
+ </div>
+ </div>
+
+ <!-- LLM call archives -->
+ <div class="devtools-card devtools-card-archives" id="devtools-card-archives">
+ <div class="devtools-card-header">
+ <span class="devtools-card-title" data-i18n="devtools.archives_title">LLM call archives</span>
+ <span class="devtools-card-sub" data-i18n="devtools.archives_sub">The last 30 streamChatWithModel calls with full input / output / events</span>
+ <span class="devtools-card-actions">
+ <button class="btn btn-sm" id="devtools-archives-refresh-btn" data-i18n="devtools.refresh">Refresh</button>
+ <button class="btn btn-sm btn-danger" id="devtools-archives-clear-btn" data-i18n="devtools.clear">Clear</button>
+ </span>
+ </div>
+ <div class="devtools-body">
+ <div class="devtools-list-col">
+ <div class="devtools-list" id="devtools-list">
+ <div class="devtools-empty" data-i18n="devtools.archives_empty">(no calls recorded)</div>
+ </div>
+ </div>
+ <div class="devtools-detail-col">
+ <div class="devtools-detail-empty" id="devtools-detail-empty" data-i18n="devtools.archives_detail_empty">Pick a call on the left to see details</div>
+ <div class="devtools-detail" id="devtools-detail" style="display:none">
+ <div class="devtools-detail-meta" id="devtools-detail-meta"></div>
+ <div class="devtools-detail-section">
+ <div class="devtools-section-title" data-i18n="devtools.input_title">User input</div>
+ <pre class="devtools-section-body" id="devtools-detail-input"></pre>
+ </div>
+ <div class="devtools-detail-section">
+ <div class="devtools-section-title">System Prompt</div>
+ <pre class="devtools-section-body" id="devtools-detail-sysprompt"></pre>
+ </div>
+ <div class="devtools-detail-section">
+ <div class="devtools-section-title" data-i18n="devtools.context_title">Context</div>
+ <pre class="devtools-section-body" id="devtools-detail-context"></pre>
+ </div>
+ <div class="devtools-detail-section">
+ <div class="devtools-section-title"><span data-i18n="devtools.tools_title">Available tools</span>(<span id="devtools-detail-tools-count">0</span>)</div>
+ <pre class="devtools-section-body" id="devtools-detail-tools"></pre>
+ </div>
+ <div class="devtools-detail-section">
+ <div class="devtools-section-title"><span data-i18n="devtools.events_title">Stream events</span>(<span id="devtools-detail-events-count">0</span>)</div>
+ <pre class="devtools-section-body" id="devtools-detail-events"></pre>
+ </div>
+ <div class="devtools-detail-section">
+ <div class="devtools-section-title" data-i18n="devtools.output_title">Model output</div>
+ <pre class="devtools-section-body" id="devtools-detail-output"></pre>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </section>
</main>
</div>
@@ -1136,6 +1252,7 @@
<script src="./modules/strip-structural-blocks.js"></script>
<script src="./modules/projects.js"></script>
<script src="./modules/project-detail.js"></script>
+ <script src="./modules/conv-bucket.js"></script>
<script src="./modules/conversation.js"></script>
<script src="./modules/chat-artifact.js"></script>
<script src="./modules/plan-rail.js"></script>
@@ -1201,10 +1318,12 @@
<script src="./modules/sync_settings.js"></script>
<script src="./modules/sync_refresh.js"></script>
<script src="./modules/sidebar_status.js"></script>
+ <script src="./modules/sidebar-resize.js"></script>
<script src="./modules/devtools-sysinfo.js"></script>
<script src="./modules/devtools-relaunch.js"></script>
<script src="./modules/devtools-native-search.js"></script>
<script src="./modules/devtools-archives.js"></script>
+ <script src="./modules/devtools-skill-metrics.js"></script>
<script src="./modules/devtools.js"></script>
</body>
</html>
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index c8af29a2..24ca6c11 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -101,21 +101,29 @@
"agents.output_format_artifact": "Artifact (Dashboard + HTML)",
"sidebar.conversations": "Chats",
"sidebar.conv_empty": "No conversations yet",
+ "sidebar.bucket.today": "Today",
+ "sidebar.bucket.yesterday": "Yesterday",
+ "sidebar.bucket.last7": "Last 7 days",
+ "sidebar.bucket.last30": "Last 30 days",
+ "sidebar.bucket.older": "Older",
"sidebar.projects": "Projects",
"sidebar.project_create_title": "New project",
"sidebar.project_create_placeholder": "Enter project name",
"sidebar.project_conv_empty": "(no conversations)",
"sidebar.settings": "Settings",
"sidebar.settings_title": "Settings",
+ "sidebar.resize_title": "Drag to resize · double-click to reset",
+ "sidebar.devtools": "Devtools",
+ "sidebar.devtools_title": "Visible in dev mode only",
"new_chat.title": "Command agents to get things done",
"new_chat.subtitle": "Type your question or task",
- "new_chat.input_placeholder": "Type a message. Use @ to call agents, skills, connectors.",
+ "new_chat.input_placeholder": "Type @ to choose agents, skills, connectors.",
"new_chat.attach_title": "Upload attachment (text / PDF / Word / image / video)",
"new_chat.send_title": "Send",
"chat.empty": "No messages yet...",
"chat.queue_label": "Queued",
"chat.queue_hint": "Drag to reorder · Edit · Delete",
- "chat.input_placeholder": "Continue the conversation. Use @ to call agents, skills, connectors.",
+ "chat.input_placeholder": "Type @ to choose agents, skills, connectors.",
"chat.recipient_label": "To: ",
"chat.recipient_commander": "Commander",
"chat.recipient_commander_hint": "Default recipient, no @ needed",
@@ -139,6 +147,8 @@
"chat.attach_upload_generic_fail": "Upload failed",
"chat.attach_rejected_prefix": "The following files could not be uploaded:\n\n{list}",
"chat.new_conv_title": "New conversation",
+ "chat.conv_pin_title": "Pin",
+ "chat.conv_unpin_title": "Unpin",
"chat.conv_del_title": "Delete",
"chat.conv_del_confirm": "Delete this conversation?",
"chat.loading": "Loading...",
@@ -792,6 +802,26 @@
"devtools.native_search_toggle": "Enable model-native web search (OpenAI / Anthropic / Google)",
"devtools.archives_title": "LLM call archives",
"devtools.archives_sub": "The last 30 streamChatWithModel calls with full input / output / events",
+ "devtools.skill_metrics.title": "Skill metrics",
+ "devtools.skill_metrics.sub": "Aggregated from expert signals — invocation rate / modified-after-hit / negative transfer per skill",
+ "devtools.skill_metrics.empty": "(no signals in the selected range)",
+ "devtools.skill_metrics.summary": "scanned {total} signals · {since} → {until}",
+ "devtools.skill_metrics.days_1": "1d",
+ "devtools.skill_metrics.days_7": "7d",
+ "devtools.skill_metrics.days_30": "30d",
+ "devtools.skill_metrics.col_skill": "Skill",
+ "devtools.skill_metrics.col_system": "System",
+ "devtools.skill_metrics.col_advertised": "Advertised",
+ "devtools.skill_metrics.col_invoked": "Invoked",
+ "devtools.skill_metrics.col_invocation_rate": "Inv. rate",
+ "devtools.skill_metrics.col_modified": "Mod after hit",
+ "devtools.skill_metrics.col_mod_rate": "Mod rate",
+ "devtools.skill_metrics.col_ineffective": "Ineffective",
+ "devtools.skill_metrics.col_ineff_rate": "Ineff. rate",
+ "devtools.skill_metrics.system_a_custom": "custom",
+ "devtools.skill_metrics.system_a_platform": "platform",
+ "devtools.skill_metrics.system_b": "evolved",
+ "devtools.skill_metrics.system_unknown": "?",
"devtools.refresh": "Refresh",
"devtools.clear": "Clear",
"devtools.archives_empty": "(no calls recorded)",
diff --git a/src/renderer/locales/ja.json b/src/renderer/locales/ja.json
index 6c07024e..0404fc2d 100644
--- a/src/renderer/locales/ja.json
+++ b/src/renderer/locales/ja.json
@@ -96,23 +96,29 @@
"common.loading": "読み込み中…",
"sidebar.conversations": "チャット",
"sidebar.conv_empty": "会話はまだありません",
+ "sidebar.bucket.today": "今日",
+ "sidebar.bucket.yesterday": "昨日",
+ "sidebar.bucket.last7": "7日以内",
+ "sidebar.bucket.last30": "30日以内",
+ "sidebar.bucket.older": "それ以前",
"sidebar.projects": "プロジェクト",
"sidebar.project_create_title": "新規プロジェクト",
"sidebar.project_create_placeholder": "プロジェクト名を入力",
"sidebar.project_conv_empty": "(会話なし)",
"sidebar.settings": "設定",
"sidebar.settings_title": "設定",
+ "sidebar.resize_title": "ドラッグで幅変更・ダブルクリックでリセット",
"sidebar.devtools": "開発ツール",
"sidebar.devtools_title": "開発モードでのみ表示",
"new_chat.title": "エージェントに指示して作業を進める",
"new_chat.subtitle": "質問やタスクを入力",
- "new_chat.input_placeholder": "メッセージを入力。@ でエージェント、スキル、コネクターを呼び出せます。",
+ "new_chat.input_placeholder": "@ を入力してエージェント、スキル、コネクターを選択",
"new_chat.attach_title": "添付ファイルをアップロード(テキスト / PDF / Word / 画像 / 動画)",
"new_chat.send_title": "送信",
"chat.empty": "メッセージはまだありません...",
"chat.queue_label": "キュー",
"chat.queue_hint": "ドラッグで並べ替え・編集・削除",
- "chat.input_placeholder": "会話を続ける。@ でエージェント、スキル、コネクターを呼び出せます。",
+ "chat.input_placeholder": "@ を入力してエージェント、スキル、コネクターを選択",
"chat.recipient_label": "宛先: ",
"chat.recipient_commander": "コマンダー",
"chat.recipient_commander_hint": "デフォルトの宛先です。@ は不要です",
@@ -136,6 +142,8 @@
"chat.attach_upload_generic_fail": "アップロードに失敗しました",
"chat.attach_rejected_prefix": "次のファイルはアップロードできませんでした:\n\n{list}",
"chat.new_conv_title": "新規会話",
+ "chat.conv_pin_title": "固定",
+ "chat.conv_unpin_title": "固定解除",
"chat.conv_del_title": "削除",
"chat.conv_del_confirm": "この会話を削除しますか?",
"chat.loading": "読み込み中...",
@@ -786,6 +794,26 @@
"devtools.native_search_toggle": "モデルネイティブ Web 検索を有効化(OpenAI / Anthropic / Google)",
"devtools.archives_title": "LLM 呼び出しアーカイブ",
"devtools.archives_sub": "直近 30 件の streamChatWithModel 呼び出し(入力 / 出力 / イベントを含む)",
+ "devtools.skill_metrics.title": "スキル指標",
+ "devtools.skill_metrics.sub": "エキスパートシグナルの集計 — スキルごとの呼び出し率/修正率/負転移率",
+ "devtools.skill_metrics.empty": "(選択範囲にシグナルなし)",
+ "devtools.skill_metrics.summary": "{total} 件のシグナル · {since} → {until}",
+ "devtools.skill_metrics.days_1": "1日",
+ "devtools.skill_metrics.days_7": "7日",
+ "devtools.skill_metrics.days_30": "30日",
+ "devtools.skill_metrics.col_skill": "スキル",
+ "devtools.skill_metrics.col_system": "種別",
+ "devtools.skill_metrics.col_advertised": "提示",
+ "devtools.skill_metrics.col_invoked": "呼出",
+ "devtools.skill_metrics.col_invocation_rate": "呼出率",
+ "devtools.skill_metrics.col_modified": "修正回数",
+ "devtools.skill_metrics.col_mod_rate": "修正率",
+ "devtools.skill_metrics.col_ineffective": "負転移",
+ "devtools.skill_metrics.col_ineff_rate": "負転移率",
+ "devtools.skill_metrics.system_a_custom": "カスタム",
+ "devtools.skill_metrics.system_a_platform": "プラットフォーム",
+ "devtools.skill_metrics.system_b": "進化",
+ "devtools.skill_metrics.system_unknown": "?",
"devtools.refresh": "更新",
"devtools.clear": "クリア",
"devtools.archives_empty": "(記録された呼び出しはありません)",
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index e02c1f4b..27cfad68 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -101,21 +101,29 @@
"agents.output_format_artifact": "Artifact(含 Dashboard + HTML)",
"sidebar.conversations": "对话",
"sidebar.conv_empty": "暂无对话",
+ "sidebar.bucket.today": "今天",
+ "sidebar.bucket.yesterday": "昨天",
+ "sidebar.bucket.last7": "7 天内",
+ "sidebar.bucket.last30": "30 天内",
+ "sidebar.bucket.older": "更早",
"sidebar.projects": "项目",
"sidebar.project_create_title": "新建项目",
"sidebar.project_create_placeholder": "输入项目名",
"sidebar.project_conv_empty": "(暂无对话)",
"sidebar.settings": "设置",
"sidebar.settings_title": "设置",
+ "sidebar.resize_title": "拖动调整宽度,双击恢复默认",
+ "sidebar.devtools": "调试",
+ "sidebar.devtools_title": "仅开发环境可见",
"new_chat.title": "指挥智能体为你干活",
"new_chat.subtitle": "输入你的问题或任务",
- "new_chat.input_placeholder": "输入消息。使用 @ 调用智能体、技能、连接器。",
+ "new_chat.input_placeholder": "输入 @ 选择智能体、技能、连接器",
"new_chat.attach_title": "上传附件(文本/PDF/Word/图片/视频)",
"new_chat.send_title": "发送",
"chat.empty": "无对话记录...",
"chat.queue_label": "待发送",
"chat.queue_hint": "可拖动排序 · 编辑 · 删除",
- "chat.input_placeholder": "继续对话。使用 @ 调用智能体、技能、连接器。",
+ "chat.input_placeholder": "输入 @ 选择智能体、技能、连接器",
"chat.recipient_label": "给:",
"chat.recipient_commander": "指挥官",
"chat.recipient_commander_hint": "默认接收者,无需 @",
@@ -139,6 +147,8 @@
"chat.attach_upload_generic_fail": "上传失败",
"chat.attach_rejected_prefix": "以下文件未能上传:\n\n{list}",
"chat.new_conv_title": "新对话",
+ "chat.conv_pin_title": "置顶",
+ "chat.conv_unpin_title": "取消置顶",
"chat.conv_del_title": "删除",
"chat.conv_del_confirm": "删除这个对话?",
"chat.loading": "加载中...",
@@ -792,6 +802,26 @@
"devtools.native_search_toggle": "启用模型原生 web search(OpenAI / Anthropic / Google)",
"devtools.archives_title": "LLM 调用存档",
"devtools.archives_sub": "最近 30 次 streamChatWithModel 的完整输入输出与过程事件",
+ "devtools.skill_metrics.title": "技能指标",
+ "devtools.skill_metrics.sub": "汇总自专家信号 —— 每个技能的引用率 / 命中后修改率 / 负迁移频次",
+ "devtools.skill_metrics.empty": "(所选时间段内无信号)",
+ "devtools.skill_metrics.summary": "扫描 {total} 条信号 · {since} → {until}",
+ "devtools.skill_metrics.days_1": "1 天",
+ "devtools.skill_metrics.days_7": "7 天",
+ "devtools.skill_metrics.days_30": "30 天",
+ "devtools.skill_metrics.col_skill": "技能",
+ "devtools.skill_metrics.col_system": "来源",
+ "devtools.skill_metrics.col_advertised": "曝光",
+ "devtools.skill_metrics.col_invoked": "调用",
+ "devtools.skill_metrics.col_invocation_rate": "引用率",
+ "devtools.skill_metrics.col_modified": "命中后被改",
+ "devtools.skill_metrics.col_mod_rate": "改写率",
+ "devtools.skill_metrics.col_ineffective": "负迁移",
+ "devtools.skill_metrics.col_ineff_rate": "负迁移率",
+ "devtools.skill_metrics.system_a_custom": "自定义",
+ "devtools.skill_metrics.system_a_platform": "平台",
+ "devtools.skill_metrics.system_b": "演进",
+ "devtools.skill_metrics.system_unknown": "?",
"devtools.refresh": "刷新",
"devtools.clear": "清空",
"devtools.archives_empty": "(暂无调用记录)",
diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.js
index 5485faee..21d4c6cf 100644
--- a/src/renderer/modules/agents.js
+++ b/src/renderer/modules/agents.js
@@ -41,10 +41,10 @@ function _isReservedAgentName(name) {
return _RESERVED_AGENT_NAMES.has(key);
}
-/** Version + category + author chips for a marketplace-installed agent. Mirrors the
+/** Version + category chips for a marketplace-installed agent. Mirrors the
* marketplace card footer so users see the same metadata in the agents grid.
* `_mpCategoriesCache` is a module-level variable in `marketplace.js` (flat top-level
- * scope per CLAUDE.md §8). Author chip: `create_uid='0'` → 官方 badge; non-zero → user badge. */
+ * scope per CLAUDE.md §8). */
function _agentPlatformChipsHtml(a) {
const lang = getLang();
const parts = [];
@@ -56,12 +56,6 @@ function _agentPlatformChipsHtml(a) {
const catLabel = _resolveCategoryLabel(a.category, lang);
parts.push(`<span class="agent-card-chip">${escapeHtml(catLabel)}</span>`);
}
- if (a.create_uid) {
- const isPlatform = String(a.create_uid) === '0';
- const label = isPlatform ? t('marketplace.author_platform') : t('marketplace.author_user').replace('{uid}', String(a.create_uid));
- const cls = isPlatform ? 'agent-card-chip is-platform' : 'agent-card-chip is-user';
- parts.push(`<span class="${cls}">${escapeHtml(label)}</span>`);
- }
return parts.join('');
}
@@ -493,11 +487,9 @@ async function selectAgent(agentId) {
}
// Render the header meta strip for a single agent / skill detail. Used by both
-// `agents.js::_renderAgentDetail` and `skills.js::useSkill`. Three forms:
+// `agents.js::_renderAgentDetail` and `skills.js::useSkill`. Two forms:
// - custom item: single "自定义" chip (kept for symmetry with prior chrome)
-// - marketplace-installed item: category chip + author chip ("官方" if uid=0, else "作者 X")
-// — replaces the old "内置" label which users found unfriendly
-// - unknown create_uid (older `_install.json` pre-author-tracking): only the category chip
+// - marketplace-installed item: category chip, without author uid / official tags
// `item.source` distinguishes custom vs marketplace-installed; `item.category` (code) maps
// to display name via `_mpCategoriesCache` (loaded at marketplace boot, hot in localStorage).
function _renderSourceMetaHtml(item) {
@@ -513,14 +505,6 @@ function _renderSourceMetaHtml(item) {
const label = cat ? (pickLocalizedName(cat, lang) || catCode) : catCode;
parts.push(`<span class="agents-detail-source is-category">${escapeHtml(label)}</span>`);
}
- const uid = String(item.create_uid || '').trim();
- if (uid) {
- if (uid === '0') {
- parts.push(`<span class="agents-detail-source is-platform">${escapeHtml(t('marketplace.author_platform'))}</span>`);
- } else {
- parts.push(`<span class="agents-detail-source is-user">${escapeHtml(t('marketplace.author_user').replace('{uid}', uid))}</span>`);
- }
- }
return parts.join('');
}
@@ -535,8 +519,7 @@ function _renderAgentDetail(agent, editing) {
nameEl.textContent = agent.name || '';
// Header chips: custom = single "自定义" tag; marketplace-installed (source=builtin) drops
- // the "内置" wording entirely and shows {category} + {官方/作者} chips instead — same family
- // as marketplace card meta. Empty category / missing create_uid silently skip.
+ // the "内置" wording entirely and shows category only, without author uid / official tags.
sourceEl.innerHTML = _renderSourceMetaHtml(agent);
// Runtime slot lives at the top of the body now (not the header):
// an always-editable dropdown so the user can flip Orkas ↔ local CLI
@@ -1624,6 +1607,11 @@ async function useAgent(agentId, seedText) {
if (!data.ok) throw new Error(data.error || t('agents.create_conv_failed'));
const conv = data.conversation;
conv.title = _autoTitle(visible);
+ // Same fix as the new-chat path in conversation.js: backend's create
+ // response carries `created_at`/`updated_at` but NOT the derived
+ // `last_active_at`, so `timeBucket` would default this brand-new row to
+ // the 'older' bucket and the user thinks it disappeared.
+ conv.last_active_at = new Date().toISOString();
conversations.unshift(conv);
renderConversationList();
setView('conversation', conv.conversation_id, { skipLoad: true });
@@ -1726,9 +1714,9 @@ if (typeof window !== 'undefined') {
// Set on every `_openAgentPicker`; consumed by `_renderAgentPickerList` and
// the search-input change handler so live filtering stays scoped.
let _pickerBoundAgentIds = null;
-let _pickerBoundSkillIds = null;
let _agentPickerTab = 'agents';
-const _AGENT_PICKER_TABS = new Set(['agents', 'skills', 'connectors']);
+const _AGENT_PICKER_TAB_ORDER = ['agents', 'skills', 'connectors'];
+const _AGENT_PICKER_TABS = new Set(_AGENT_PICKER_TAB_ORDER);
function _normalizeAgentPickerTab(tab) {
return _AGENT_PICKER_TABS.has(tab) ? tab : 'agents';
@@ -1761,6 +1749,13 @@ function _setAgentPickerTab(tab, opts = {}) {
if (opts.focusSearch !== false) setTimeout(() => search?.focus(), 0);
}
+function _moveAgentPickerTab(delta) {
+ const cur = _AGENT_PICKER_TAB_ORDER.indexOf(_agentPickerTab);
+ const idx = cur >= 0 ? cur : 0;
+ const next = (idx + delta + _AGENT_PICKER_TAB_ORDER.length) % _AGENT_PICKER_TAB_ORDER.length;
+ _setAgentPickerTab(_AGENT_PICKER_TAB_ORDER[next]);
+}
+
function _resolveActiveProjectId(anchorId) {
if (anchorId === 'new-chat-recipient-chip') {
return (typeof getCommanderProjectId === 'function') ? getCommanderProjectId() : '';
@@ -1795,18 +1790,16 @@ async function _openAgentPicker(anchorBtn) {
(typeof loadSkills === 'function' ? loadSkills(true) : Promise.resolve()),
(typeof loadConnectors === 'function' ? loadConnectors() : Promise.resolve()),
]);
- // Refresh project-scope bindings on every open so the picker reflects
+ // Refresh project-scoped agent bindings on every open so the picker reflects
// whatever project the user just picked (commander chip) or whatever
- // project the active conv belongs to.
+ // project the active conv belongs to. Skills and connectors stay global.
_pickerBoundAgentIds = null;
- _pickerBoundSkillIds = null;
const pid = _resolveActiveProjectId(anchorBtn.id);
if (pid) {
try {
const res = await window.orkas.invoke('projects.bindings.list', { projectId: pid });
if (res?.ok) {
_pickerBoundAgentIds = new Set((res.bindings && res.bindings.agents) || []);
- _pickerBoundSkillIds = new Set((res.bindings && res.bindings.skills) || []);
}
} catch (_) { /* fall back to global listing */ }
}
@@ -1933,17 +1926,13 @@ function _renderSkillPickerList(listEl, filterText, anchorId) {
const lang = getLang();
const q = (filterText || '').toLowerCase();
let skills = (_skillsCache || []).filter((s) => s.enabled !== false);
- if (_pickerBoundSkillIds) skills = skills.filter((s) => _pickerBoundSkillIds.has(s.id));
const filtered = q
? skills
.filter((s) => _matchPickerItem(q, s.name || s.id, pickDesc(s, lang), s.id))
.sort((a, b) => _pickerMatchScore(q, a.name || a.id) - _pickerMatchScore(q, b.name || b.id))
: skills;
if (!filtered.length) {
- const hint = (!q && _pickerBoundSkillIds && _pickerBoundSkillIds.size === 0)
- ? `<div class="skill-picker-empty-hint">${escapeHtml(t('skills.no_project_skills'))}</div>`
- : '';
- listEl.innerHTML = hint + `<div class="skill-picker-empty">${escapeHtml(t('skills.no_match'))}</div>`;
+ listEl.innerHTML = `<div class="skill-picker-empty">${escapeHtml(t('skills.no_match'))}</div>`;
return;
}
const groups = { custom: [], builtin: [] };
@@ -1961,10 +1950,7 @@ function _renderSkillPickerList(listEl, filterText, anchorId) {
</div>`;
}).join('');
};
- const hint = (!q && _pickerBoundSkillIds && _pickerBoundSkillIds.size === 0)
- ? `<div class="skill-picker-empty-hint">${escapeHtml(t('skills.no_project_skills'))}</div>`
- : '';
- listEl.innerHTML = hint + groupHtml(t('skills.source_custom'), groups.custom) + groupHtml(t('skills.source_builtin'), groups.builtin);
+ listEl.innerHTML = groupHtml(t('skills.source_custom'), groups.custom) + groupHtml(t('skills.source_builtin'), groups.builtin);
_bindAgentPickerListItems(listEl, anchorId);
}
@@ -2128,6 +2114,8 @@ function bindAgentPickers() {
// English candidate would also fire our select-active-item handler.
if (e.isComposing || e.keyCode === 229) return;
if (e.key === 'Escape') { _atKeyMark = null; _closeAgentPicker(); e.preventDefault(); return; }
+ if (e.key === 'ArrowRight') { _moveAgentPickerTab(1); e.preventDefault(); return; }
+ if (e.key === 'ArrowLeft') { _moveAgentPickerTab(-1); e.preventDefault(); return; }
if (e.key === 'ArrowDown') { _moveAgentPickerActive(1); e.preventDefault(); return; }
if (e.key === 'ArrowUp') { _moveAgentPickerActive(-1); e.preventDefault(); return; }
if (e.key === 'Enter') {
diff --git a/src/renderer/modules/conv-bucket.js b/src/renderer/modules/conv-bucket.js
new file mode 100644
index 00000000..1004ab8c
--- /dev/null
+++ b/src/renderer/modules/conv-bucket.js
@@ -0,0 +1,32 @@
+// Time-bucket the sidebar conversation list by `last_active_at` (already
+// computed by features/chats.ts::listConversations as
+// `max(updated_at, created_at)`). Local-time boundaries: today / yesterday /
+// last 7 days / last 30 days / older. Pure helper — `now` is injectable so
+// the fixture tests in test/renderer/conversation-bucket.test.ts can pin
+// DST-free wall clocks.
+//
+// Kept in its own file (per CLAUDE.md §9 — only pure functions are eligible
+// for the CJS bridge that vitest uses; conversation.js touches createLogger /
+// window / IPC at top level, so it can't be `require()`d directly).
+
+const _BUCKET_ORDER = ['today', 'yesterday', 'last7', 'last30', 'older'];
+
+function timeBucket(iso, now) {
+ if (!now) now = new Date();
+ if (!iso) return 'older';
+ const t = new Date(iso).getTime();
+ if (!Number.isFinite(t)) return 'older';
+ const today = new Date(now);
+ today.setHours(0, 0, 0, 0);
+ const todayMs = today.getTime();
+ const dayMs = 24 * 60 * 60 * 1000;
+ if (t >= todayMs) return 'today';
+ if (t >= todayMs - dayMs) return 'yesterday';
+ if (t >= todayMs - 7 * dayMs) return 'last7';
+ if (t >= todayMs - 30 * dayMs) return 'last30';
+ return 'older';
+}
+
+if (typeof module !== 'undefined' && typeof module.exports === 'object') {
+ module.exports = { timeBucket, _BUCKET_ORDER };
+}
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index 67242b37..aac78309 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -180,7 +180,13 @@ function _initMentionMirror(textarea) {
wrap.appendChild(textarea);
let lastSynced = '';
+ let lastPlaceholder = '';
const sync = () => {
+ const placeholder = textarea.getAttribute('placeholder') || '';
+ if (placeholder !== lastPlaceholder) {
+ lastPlaceholder = placeholder;
+ mirror.dataset.placeholder = placeholder;
+ }
const v = textarea.value || '';
if (v === lastSynced) return;
lastSynced = v;
@@ -436,6 +442,14 @@ function onEnterConversationView() {
// the rail would keep displaying the previous cid's plan content.
if (window.PlanRail) window.PlanRail.bind(currentCid || null);
if (window.ConversationInfo) window.ConversationInfo.bind(currentCid || null);
+ // Returning to a conversation while its original send-stream is still
+ // alive can miss state/process events that fired while another view was
+ // active (the cross-cid guard intentionally drops them). Ask main for the
+ // current in-flight actors so the visible placeholders catch up
+ // immediately, instead of waiting for the next tool event.
+ if (currentCid && isConvPending(currentCid)) {
+ _syncPendingActorsFromRuntime(currentCid, { allowController: true }).catch(() => {});
+ }
// Quote preview is per-cid; rerender so a quote captured in another conv
// doesn't bleed into this one (and a quote left in this conv reappears
// when the user navigates back).
@@ -493,7 +507,7 @@ function _stopRuntimeActorRecovery(cid) {
_runtimeRecoveryTimers.delete(cid);
}
-async function _syncPendingActorsFromRuntime(cid) {
+async function _syncPendingActorsFromRuntime(cid, opts = {}) {
if (!cid || !isConvPending(cid)) return false;
const state = pendingConvs.get(cid);
if (!state || state.aborted) return false;
@@ -501,7 +515,9 @@ async function _syncPendingActorsFromRuntime(cid) {
// cases. A live send-stream controller is already the authoritative event
// source; letting this path finish it can manufacture empty loading bubbles
// or clear pending in the middle of a plan handoff.
- if (state.controller) return false;
+ const allowController = !!opts.allowController;
+ const hasLiveController = !!state.controller && _convChatCtrls.has(cid);
+ if (hasLiveController && !allowController) return false;
const loadingEl = state.loadingEl;
let data = null;
try {
@@ -526,6 +542,13 @@ async function _syncPendingActorsFromRuntime(cid) {
try { window.ConversationInfo.refresh(cid, { silent: true }); } catch (_) {}
}
if (!processing) {
+ if (hasLiveController) {
+ _latestInFlight.set(cid, []);
+ setGroupConversationBusy(cid, false);
+ _updateConvSidebarBadge(cid, false);
+ if (cid === currentCid) _updateConvSendUI(cid);
+ return true;
+ }
_latestInFlight.set(cid, []);
setGroupConversationBusy(cid, false);
_updateConvSidebarBadge(cid, false);
@@ -544,6 +567,14 @@ async function _syncPendingActorsFromRuntime(cid) {
_updateConvSidebarBadge(cid, true);
startPolling(cid);
if (cid === currentCid) _updateConvSendUI(cid);
+ if (!hasLiveController) {
+ // Runtime polling can tell us who is working, but it does not carry
+ // process/delta events. When the local send-stream was lost (refresh,
+ // stale controller state, or reconnect), attach the group event stream
+ // so plan-triggered agents keep streaming instead of only appearing
+ // after the final history poll.
+ _observeConversationRunFromPlanAction(cid, { attachExisting: true });
+ }
if (!inFlight.length) return false;
// Names/avatars are local data; warm members before revealing so the
@@ -1582,53 +1613,116 @@ function startRelayActivitySubscription() {
}
}
+// `timeBucket` + `_BUCKET_ORDER` live in modules/conv-bucket.js (loaded
+// ahead of this file in index.html). Kept as a separate file so its pure
+// helper can be fixture-tested via the §9 CJS bridge without dragging the
+// whole renderer-side global graph (createLogger / IPC) into vitest.
+
// Move a conversation to the top of the sidebar list and re-render.
// Called whenever a non-internal message lands on a cid so the list stays
-// ordered by last activity (matches backend listConversations sort, which
-// reads <cid>.jsonl mtime on the next full reload).
+// ordered by pin state first, then last activity (matches backend
+// listConversations sort on the next full reload).
function _bumpConvToTop(cid) {
if (!cid || !Array.isArray(conversations) || !conversations.length) return;
- const idx = conversations.findIndex((c) => c && c.conversation_id === cid);
- if (idx <= 0) return;
- const [c] = conversations.splice(idx, 1);
+ const c = conversations.find((row) => row && row.conversation_id === cid);
+ if (!c) return;
c.last_active_at = new Date().toISOString();
- conversations.unshift(c);
+ _sortConversationCacheForSidebar();
renderConversationList();
}
-function renderConversationList() {
- const container = document.getElementById('conversation-list');
- // Conversations with a project_id are rendered nested under their project
- // by `projects.js::renderProjectsSection`. The "Conversations" section
- // here only shows the unprojected ones — same data model as the user's
- // mental picture (projected convs live "inside" their project, the rest
- // sit in the catch-all section).
- const unprojected = (conversations || []).filter((c) => !c || !c.project_id);
- if (!unprojected.length) {
- container.innerHTML = `<div class="conv-empty" data-i18n="sidebar.conv_empty">${escapeHtml(t('sidebar.conv_empty'))}</div>`;
- // Still re-render the projects section so its badges refresh (the call
- // is cheap when the cache is already loaded).
- if (typeof renderProjectsSection === 'function') renderProjectsSection();
- return;
+function _compareConversationsForSidebar(a, b) {
+ const ap = (a && a.pinned_at) || '';
+ const bp = (b && b.pinned_at) || '';
+ if (ap && !bp) return -1;
+ if (!ap && bp) return 1;
+ if (ap && bp) {
+ const pinCmp = bp.localeCompare(ap);
+ if (pinCmp) return pinCmp;
}
+ return ((b && b.last_active_at) || '').localeCompare((a && a.last_active_at) || '');
+}
+
+function _sortConversationCacheForSidebar() {
+ if (!Array.isArray(conversations)) return;
+ conversations.sort(_compareConversationsForSidebar);
+}
+
+function _renderConversationSidebarItem(c, opts = {}) {
+ const cid = escapeHtml(c.conversation_id);
+ const title = escapeHtml(c.title || t('chat.new_conv_title'));
+ const isPinned = !!c.pinned_at;
+ const pinTitle = escapeHtml(t(isPinned ? 'chat.conv_unpin_title' : 'chat.conv_pin_title'));
const delTitle = escapeHtml(t('chat.conv_del_title'));
- container.innerHTML = unprojected.map(c => {
- // All conversations are now the single `normal` kind — no type badge.
- const title = escapeHtml(c.title || t('chat.new_conv_title'));
- return `
- <div class="conv-item" data-cid="${c.conversation_id}">
- <div class="conv-item-title" title="${title}">${title}</div>
- <button class="conv-item-del" data-del-cid="${c.conversation_id}" title="${delTitle}">×</button>
- </div>
- `;
- }).join('');
+ const pinIcon = _uiIconHtml('pin', 'conv-item-action-icon');
+ const delIcon = _uiIconHtml('trash', 'conv-item-action-icon') || '×';
+ const classes = [
+ 'conv-item',
+ opts.nested ? 'conv-item-nested' : '',
+ currentCid === c.conversation_id ? 'active' : '',
+ isPinned ? 'is-pinned' : '',
+ ].filter(Boolean).join(' ');
+ return `
+ <div class="${classes}" data-cid="${cid}">
+ <button type="button" class="conv-item-action conv-item-pin${isPinned ? ' is-pinned' : ''}"
+ data-pin-cid="${cid}" data-pin-next="${isPinned ? '0' : '1'}"
+ title="${pinTitle}" aria-label="${pinTitle}">${pinIcon}</button>
+ <div class="conv-item-title" title="${title}">${title}</div>
+ <button type="button" class="conv-item-action conv-item-del"
+ data-del-cid="${cid}" title="${delTitle}" aria-label="${delTitle}">${delIcon}</button>
+ </div>
+ `;
+}
+
+async function _toggleConversationPinned(cid, pinned) {
+ if (!cid || !Array.isArray(conversations)) return;
+ const snapshot = conversations.map((c) => (c ? { ...c } : c));
+ const local = conversations.find((c) => c && c.conversation_id === cid);
+ if (!local) return;
+ if (pinned) local.pinned_at = new Date().toISOString();
+ else delete local.pinned_at;
+ _sortConversationCacheForSidebar();
+ renderConversationList();
- container.querySelectorAll('.conv-item').forEach(el => {
+ try {
+ const res = await apiFetch(`/api/conversations/${encodeURIComponent(cid)}/pin`, {
+ method: 'POST',
+ body: JSON.stringify({ pinned }),
+ });
+ const data = await res.json();
+ if (!data || data.ok === false || !data.conversation) {
+ throw new Error((data && data.error) || 'pin failed');
+ }
+ const idx = conversations.findIndex((c) => c && c.conversation_id === cid);
+ if (idx >= 0) {
+ conversations[idx] = { ...conversations[idx], ...data.conversation };
+ _sortConversationCacheForSidebar();
+ renderConversationList();
+ }
+ } catch (err) {
+ conversations = snapshot;
+ renderConversationList();
+ _convLog.warn('toggle conversation pin failed', err);
+ }
+}
+
+function _bindConversationSidebarItems(container, opts = {}) {
+ if (!container) return;
+ const selector = opts.selector || '.conv-item';
+ container.querySelectorAll(selector).forEach(el => {
el.addEventListener('click', (e) => {
- if (e.target.closest('.conv-item-del')) return;
+ if (e.target.closest('.conv-item-action')) return;
setView('conversation', el.dataset.cid);
});
});
+ container.querySelectorAll('.conv-item-pin').forEach(btn => {
+ btn.addEventListener('click', async (e) => {
+ e.stopPropagation();
+ const cid = btn.dataset.pinCid;
+ const pinned = btn.dataset.pinNext === '1';
+ await _toggleConversationPinned(cid, pinned);
+ });
+ });
container.querySelectorAll('.conv-item-del').forEach(btn => {
btn.addEventListener('click', async (e) => {
e.stopPropagation();
@@ -1636,11 +1730,62 @@ function renderConversationList() {
if (!(await uiConfirm(t('chat.conv_del_confirm')))) return;
abortConvStream(cid);
_forgetConvLocal(cid);
- await apiFetch(`/api/conversations/${cid}`, { method: 'DELETE' });
+ await apiFetch(`/api/conversations/${encodeURIComponent(cid)}`, { method: 'DELETE' });
if (currentCid === cid) setView('new-chat');
await loadConversations();
+ if (typeof opts.afterDelete === 'function') await opts.afterDelete(cid);
});
});
+}
+
+function renderConversationList() {
+ const container = document.getElementById('conversation-list');
+ _sortConversationCacheForSidebar();
+ // Conversations with a project_id are rendered nested under their project
+ // by `projects.js::renderProjectsSection`. The "Conversations" section
+ // here only shows the unprojected ones — same data model as the user's
+ // mental picture (projected convs live "inside" their project, the rest
+ // sit in the catch-all section).
+ const unprojected = (conversations || []).filter((c) => !c || !c.project_id);
+ if (!unprojected.length) {
+ container.innerHTML = `<div class="conv-empty" data-i18n="sidebar.conv_empty">${escapeHtml(t('sidebar.conv_empty'))}</div>`;
+ // Still re-render the projects section so its badges refresh (the call
+ // is cheap when the cache is already loaded).
+ if (typeof renderProjectsSection === 'function') renderProjectsSection();
+ return;
+ }
+ // Pinned convs float to the top of the sidebar (no time header) — they
+ // were pinned because the user wants them visible regardless of recency,
+ // so bucketing them would defeat the feature. The rest get grouped into
+ // today / yesterday / last7 / last30 / older buckets by last activity.
+ const pinned = [];
+ const rest = [];
+ for (const c of unprojected) {
+ if (c && c.pinned_at) pinned.push(c);
+ else rest.push(c);
+ }
+ const now = new Date();
+ const buckets = { today: [], yesterday: [], last7: [], last30: [], older: [] };
+ // Fall back through last_active_at → updated_at → created_at: backend's
+ // `listConversations` always emits last_active_at, but optimistic unshifts
+ // from create/launch paths land here before the next refresh and may
+ // carry only created_at. Without this fallback they'd land in 'older'.
+ for (const c of rest) {
+ const iso = c.last_active_at || c.updated_at || c.created_at || '';
+ buckets[timeBucket(iso, now)].push(c);
+ }
+ const parts = [];
+ for (const c of pinned) parts.push(_renderConversationSidebarItem(c));
+ for (const b of _BUCKET_ORDER) {
+ const items = buckets[b];
+ if (!items.length) continue;
+ const headerKey = `sidebar.bucket.${b}`;
+ parts.push(`<div class="conv-list-section-header" data-i18n="${headerKey}">${escapeHtml(t(headerKey))}</div>`);
+ for (const c of items) parts.push(_renderConversationSidebarItem(c));
+ }
+ container.innerHTML = parts.join('');
+
+ _bindConversationSidebarItems(container);
// Re-render the projects section (it consumes the same `conversations`
// global to group projected items by project).
@@ -1806,7 +1951,10 @@ async function loadConversationHistory(cid) {
startPolling(cid);
if (cid === currentCid) _updateConvSendUI(cid);
}
- if (lastMsg?.role === 'user' && !wasPendingBeforeHistoryRecovery && processingFresh) {
+ const shouldRecoverRunningUi = !wasPendingBeforeHistoryRecovery
+ && processingFresh
+ && (lastMsg?.role === 'user' || inFlightActors.length > 0);
+ if (shouldRecoverRunningUi) {
pollMsgCounts.set(cid, history.length);
const loadingEl = _createStreamingAssistantMessage(container, { hiddenUntilActor: true });
pendingConvs.set(cid, { loadingEl, needsIndicator: false });
@@ -2317,19 +2465,10 @@ function _marketplaceRequestCategoryLabel(code, lang) {
return row[base] || row.en;
}
-function _marketplaceRequestAuthorBadgeHtml(createUid) {
- if (!createUid) return '';
- const label = String(createUid) === '0'
- ? t('marketplace.author_platform')
- : t('marketplace.author_user').replace('{uid}', String(createUid));
- const cls = String(createUid) === '0' ? 'marketplace-card-chip is-platform' : 'marketplace-card-chip is-user';
- return `<span class="${cls}">${escapeHtml(label)}</span>`;
-}
-
async function _hydrateMarketplaceRequestMeta(card, req, cid, msgId) {
if (!card || !req) return;
const hasAvatar = req.kind !== 'agent' || req.icon || req.color;
- const hasCardMeta = req.description_zh || req.description_en || req.category || req.create_uid;
+ const hasCardMeta = req.description_zh || req.description_en || req.category;
if (hasAvatar && hasCardMeta) return;
try {
const q = req.name || req.id || '';
@@ -2342,7 +2481,6 @@ async function _hydrateMarketplaceRequestMeta(card, req, cid, msgId) {
req.description_zh = row.description_zh || '';
req.description_en = row.description_en || '';
req.category = row.category || '';
- req.create_uid = row.create_uid || '';
_renderMarketplaceInstallCard(card, req, cid, msgId);
} catch (_) { /* fallback content is already rendered */ }
}
@@ -2372,7 +2510,6 @@ function _renderMarketplaceInstallCard(card, req, cid, msgId) {
const meta = [
version ? `<span class="marketplace-card-chip is-version">${escapeHtml(version)}</span>` : '',
catLabel ? `<span class="marketplace-card-chip">${escapeHtml(catLabel)}</span>` : '',
- _marketplaceRequestAuthorBadgeHtml(req.create_uid),
].filter(Boolean).join('');
const error = req.error ? `<div class="chat-marketplace-request-error">${escapeHtml(req.error)}</div>` : '';
const iconHtml = kind === 'agent'
@@ -2755,6 +2892,11 @@ async function handleNewChatSubmit() {
// otherwise the optimistic + backend-refreshed titles disagree and
// the sidebar entry flips on the next loadConversations.
conv.title = _autoTitle(raw);
+ // Backend `createConversation` returns `created_at`/`updated_at` but
+ // NOT the derived `last_active_at` (that lives only in `listConversations`'
+ // output). Set it explicitly so `timeBucket` puts the brand-new row in
+ // the 'today' bucket instead of falling through to 'older'.
+ conv.last_active_at = new Date().toISOString();
conversations.unshift(conv);
renderConversationList();
// The new conv may have landed inside a project — refresh the projects
@@ -3039,8 +3181,7 @@ function _makeStreamPaintYield() {
function _observeConversationRunFromPlanAction(cid, opts = {}) {
if (!cid) return null;
const attachExisting = !!opts.attachExisting;
- const existingState = pendingConvs.get(cid);
- if (_convChatCtrls.has(cid) || existingState?.controller) return null;
+ if (_convChatCtrls.has(cid)) return null;
if (!attachExisting && (pendingConvs.has(cid) || isGroupConversationBusy(cid))) return null;
const controller = new AbortController();
@@ -5559,7 +5700,9 @@ function _updateConvSidebarBadge(cid, _unused) {
html += `<span class="conv-status-count">${queued}</span>`;
}
badge.innerHTML = html;
- item.prepend(badge);
+ const title = item.querySelector('.conv-item-title');
+ if (title) item.insertBefore(badge, title);
+ else item.prepend(badge);
}
// Repaint badges on every visible conversation item. Called after re-render
@@ -5624,3 +5767,4 @@ if (typeof window !== 'undefined') {
_initChatSelectionMenu();
}
}
+
diff --git a/src/renderer/modules/icons.js b/src/renderer/modules/icons.js
index 8d0c1c78..253fa28a 100644
--- a/src/renderer/modules/icons.js
+++ b/src/renderer/modules/icons.js
@@ -32,9 +32,18 @@
const UI_ICONS = {
search: '<circle cx="11" cy="11" r="7"></circle><path d="m21 21-4.3-4.3"></path>',
+ 'message-square': '<path d="M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z"></path>',
+ users: '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M22 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path>',
+ sparkles: '<path d="M12 3l1.4 3.6L17 8l-3.6 1.4L12 13l-1.4-3.6L7 8l3.6-1.4z"></path><path d="M19 13l.9 2.1L22 16l-2.1.9L19 19l-.9-2.1L16 16l2.1-.9z"></path><path d="M5 14l.8 1.7L7.5 16.5l-1.7.8L5 19l-.8-1.7-1.7-.8 1.7-.8z"></path>',
+ plug: '<path d="M12 22v-5"></path><path d="M9 8V2"></path><path d="M15 8V2"></path><path d="M6 8h12v4a6 6 0 0 1-12 0z"></path>',
+ 'book-open': '<path d="M12 7v14"></path><path d="M3 5.5A3.5 3.5 0 0 1 6.5 2H12v19H6.5A3.5 3.5 0 0 1 3 17.5z"></path><path d="M21 5.5A3.5 3.5 0 0 0 17.5 2H12v19h5.5a3.5 3.5 0 0 0 3.5-3.5z"></path>',
+ 'layout-grid': '<rect x="3" y="3" width="7" height="7" rx="1.5"></rect><rect x="14" y="3" width="7" height="7" rx="1.5"></rect><rect x="3" y="14" width="7" height="7" rx="1.5"></rect><rect x="14" y="14" width="7" height="7" rx="1.5"></rect>',
settings: '<circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3 1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8 1.7 1.7 0 0 0 1.5 1h.1a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"></path>',
terminal: '<path d="m8 8 4 4-4 4"></path><path d="M14 16h4"></path><rect x="3" y="4" width="18" height="16" rx="3"></rect>',
x: '<path d="M18 6 6 18M6 6l12 12"></path>',
+ trash: '<path d="M3 6h18"></path><path d="M8 6V4h8v2"></path><path d="M19 6l-1 15H6L5 6"></path><path d="M10 11v6M14 11v6"></path>',
+ pin: '<path d="M12 17v5"></path><path d="M5 17h14"></path><path d="M7 3h10l-1 8 3 6H5l3-6z"></path>',
+ 'pin-off': '<path d="M12 17v5"></path><path d="M5 17h12"></path><path d="M7 3h7"></path><path d="M16 11l3 6"></path><path d="M8 11l.6-4.8"></path><path d="M3 3l18 18"></path>',
mic: '<path d="M12 3a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V6a3 3 0 0 0-3-3z"></path><path d="M19 11a7 7 0 0 1-14 0"></path><path d="M12 18v3"></path><path d="M8 21h8"></path>',
send: '<path d="M22 2 11 13"></path><path d="m22 2-7 20-4-9-9-4 20-7z"></path>',
stop: '<rect x="6" y="6" width="12" height="12" rx="2"></rect>',
diff --git a/src/renderer/modules/ipc-shim.js b/src/renderer/modules/ipc-shim.js
index 44ec4182..c674a18f 100644
--- a/src/renderer/modules/ipc-shim.js
+++ b/src/renderer/modules/ipc-shim.js
@@ -59,6 +59,7 @@ const _IPC_ROUTES = [
// Pattern routes (with path parameters)
['DELETE', /^\/api\/conversations\/([^/]+)$/, 'conversations.delete', ['cid']],
+ ['POST', /^\/api\/conversations\/([^/]+)\/pin$/, 'conversations.pin', ['cid']],
['GET', /^\/api\/conversations\/([^/]+)\/history$/, 'conversations.history', ['cid']],
['POST', /^\/api\/conversations\/([^/]+)\/send$/, 'groupChat.send', ['cid']],
['POST', /^\/api\/conversations\/([^/]+)\/send\/stream$/, 'conversations.sendStream', ['cid'], { stream: true }],
diff --git a/src/renderer/modules/marketplace.js b/src/renderer/modules/marketplace.js
index 0f91001f..15216667 100644
--- a/src/renderer/modules/marketplace.js
+++ b/src/renderer/modules/marketplace.js
@@ -741,7 +741,6 @@ function _mpCardHtml(item, lang) {
<div class="marketplace-card-meta">
${item.version ? `<span class="marketplace-card-chip is-version">${escapeHtml(versionLabel)}</span>` : ''}
${catLabel ? `<span class="marketplace-card-chip">${escapeHtml(catLabel)}</span>` : ''}
- ${_mpAuthorBadgeHtml(item.create_uid)}
</div>
<div class="marketplace-card-actions">
<button type="button" class="${btnClass}" ${btnAttrs}>${btnSpinner}${escapeHtml(btnLabel)}</button>
@@ -751,18 +750,6 @@ function _mpCardHtml(item, lang) {
`;
}
-/** Author badge — distinguishes same-name uploads by different authors. uid=0 is the
- * Platform marker (i18n key `marketplace.author_platform`); everything else falls back
- * to a truncated uid. */
-function _mpAuthorBadgeHtml(createUid) {
- if (!createUid) return '';
- const label = String(createUid) === '0'
- ? t('marketplace.author_platform')
- : t('marketplace.author_user').replace('{uid}', String(createUid));
- const cls = String(createUid) === '0' ? 'marketplace-card-chip is-platform' : 'marketplace-card-chip is-user';
- return `<span class="${cls}">${escapeHtml(label)}</span>`;
-}
-
function _mpCategoryLabel(code, lang) {
if (!code) return '';
const c = _mpState.categories.find((x) => x.code === code);
@@ -847,14 +834,13 @@ function _mpRenderDetail() {
avatarSlot.style.display = 'none';
}
}
- // Name + version share a row; category / author chips drop to the meta-row below.
+ // Name + version share a row; category chips drop to the meta-row below.
panel.querySelector('[data-mp-detail-name]').innerHTML = `
${escapeHtml(item.name || item.id)}
<span class="marketplace-detail-version">${escapeHtml(versionLabel)}</span>
`;
panel.querySelector('[data-mp-detail-meta]').innerHTML = [
catLabel ? `<span class="marketplace-card-chip">${escapeHtml(catLabel)}</span>` : '',
- _mpAuthorBadgeHtml(item.create_uid),
].filter(Boolean).join(' ');
// (description used to render in a top-of-body `.marketplace-detail-desc` strip; now it's
// the first section inside body — see `_mpAgentDetailHtml` / `_mpSkillDetailHtml`)
diff --git a/src/renderer/modules/projects.js b/src/renderer/modules/projects.js
index e1df4b0e..62e65253 100644
--- a/src/renderer/modules/projects.js
+++ b/src/renderer/modules/projects.js
@@ -179,15 +179,10 @@ function _renderProjectRow(p, convs) {
if (!convs.length) {
html += `<div class="project-conv-empty">${escapeHtml(t('sidebar.project_conv_empty'))}</div>`;
} else {
- const delTitle = escapeHtml(t('chat.conv_del_title'));
for (const c of convs) {
- const title = escapeHtml(c.title || t('chat.new_conv_title'));
- html += `
- <div class="conv-item conv-item-nested" data-cid="${c.conversation_id}">
- <div class="conv-item-title" title="${title}">${title}</div>
- <button class="conv-item-del" data-del-cid="${c.conversation_id}" title="${delTitle}">×</button>
- </div>
- `;
+ html += (typeof _renderConversationSidebarItem === 'function')
+ ? _renderConversationSidebarItem(c, { nested: true })
+ : `<div class="conv-item conv-item-nested" data-cid="${escapeHtml(c.conversation_id)}"><div class="conv-item-title" title="${escapeHtml(c.title || t('chat.new_conv_title'))}">${escapeHtml(c.title || t('chat.new_conv_title'))}</div></div>`;
}
}
html += '</div>';
@@ -227,28 +222,21 @@ function _bindProjectsHandlers(container) {
});
});
- // Nested conv items.
- container.querySelectorAll('.conv-item-nested').forEach((el) => {
- el.addEventListener('click', (e) => {
- if (e.target.closest('.conv-item-del')) return;
- setView('conversation', el.dataset.cid);
+ if (typeof _bindConversationSidebarItems === 'function') {
+ _bindConversationSidebarItems(container, {
+ selector: '.conv-item-nested',
+ async afterDelete() {
+ // Project conv counts changed → refresh project cache so future reads
+ // (delete confirm body, etc.) see the right number.
+ await loadProjects(true);
+ },
});
- });
- container.querySelectorAll('.conv-item-nested .conv-item-del').forEach((btn) => {
- btn.addEventListener('click', async (e) => {
- e.stopPropagation();
- const cid = btn.dataset.delCid;
- if (!(await uiConfirm(t('chat.conv_del_confirm')))) return;
- if (typeof abortConvStream === 'function') abortConvStream(cid);
- if (typeof _forgetConvLocal === 'function') _forgetConvLocal(cid);
- await apiFetch(`/api/conversations/${cid}`, { method: 'DELETE' });
- if (currentCid === cid) setView('new-chat');
- await loadConversations();
- // Project conv counts changed → refresh project cache so future reads
- // (delete confirm body, etc.) see the right number.
- await loadProjects(true);
+ } else {
+ // Nested conv items.
+ container.querySelectorAll('.conv-item-nested').forEach((el) => {
+ el.addEventListener('click', () => setView('conversation', el.dataset.cid));
});
- });
+ }
}
function _toggleProjectExpand(pid) {
diff --git a/src/renderer/modules/saved-apps.js b/src/renderer/modules/saved-apps.js
index 96d573b8..aa5ac84a 100644
--- a/src/renderer/modules/saved-apps.js
+++ b/src/renderer/modules/saved-apps.js
@@ -139,9 +139,12 @@
} catch (err) { _fail(_t('apps.edit_failed', 'Could not open an edit conversation'), err); return; }
const conv = r.conversation;
if (!conv || !conv.conversation_id) { _fail(_t('apps.edit_failed', 'Could not open an edit conversation')); return; }
- // Add to the sidebar list.
+ // Add to the sidebar list. Set last_active_at explicitly — backend
+ // create response doesn't include the derived field, so timeBucket
+ // would otherwise put this brand-new row in the 'older' bucket.
try {
if (typeof conversations !== 'undefined' && Array.isArray(conversations)) {
+ conv.last_active_at = new Date().toISOString();
conversations.unshift(conv);
if (typeof renderConversationList === 'function') renderConversationList();
}
diff --git a/src/renderer/modules/sidebar-resize.js b/src/renderer/modules/sidebar-resize.js
new file mode 100644
index 00000000..c05e2f61
--- /dev/null
+++ b/src/renderer/modules/sidebar-resize.js
@@ -0,0 +1,100 @@
+/**
+ * Drag-to-resize for the left sidebar.
+ *
+ * Drives `--sidebar-width` on `<html>`; the CSS rule on `.sidebar` consumes it
+ * and clamps with min-width / max-width as a second line of defense. Width
+ * persists in localStorage so it survives reloads on this machine (machine-
+ * local UI preference, not synced across devices — same shape as other layout
+ * prefs like artifact-rail collapse state would be).
+ *
+ * Double-click on the handle resets to the default.
+ */
+(() => {
+ if (typeof window === 'undefined' || typeof document === 'undefined') return;
+
+ const STORAGE_KEY = 'orkas:sidebar-width';
+ const MIN_WIDTH = 180;
+ const MAX_WIDTH = 480;
+ const DEFAULT_WIDTH = 200;
+
+ function clamp(n) {
+ if (!Number.isFinite(n)) return DEFAULT_WIDTH;
+ if (n < MIN_WIDTH) return MIN_WIDTH;
+ if (n > MAX_WIDTH) return MAX_WIDTH;
+ return n;
+ }
+
+ function applyWidth(px) {
+ document.documentElement.style.setProperty('--sidebar-width', px + 'px');
+ }
+
+ function loadSavedWidth() {
+ try {
+ const raw = localStorage.getItem(STORAGE_KEY);
+ if (!raw) return null;
+ const n = parseInt(raw, 10);
+ return Number.isFinite(n) ? clamp(n) : null;
+ } catch (_) { return null; }
+ }
+
+ function saveWidth(px) {
+ try { localStorage.setItem(STORAGE_KEY, String(px)); } catch (_) { /* quota / private mode */ }
+ }
+
+ function init() {
+ const saved = loadSavedWidth();
+ if (saved != null) applyWidth(saved);
+
+ const handle = document.getElementById('sidebar-resize-handle');
+ const sidebar = document.querySelector('.sidebar');
+ if (!handle || !sidebar) return;
+
+ let dragging = false;
+ let startX = 0;
+ let startWidth = 0;
+
+ function onMove(e) {
+ if (!dragging) return;
+ const dx = e.clientX - startX;
+ const next = clamp(startWidth + dx);
+ applyWidth(next);
+ }
+
+ function onUp() {
+ if (!dragging) return;
+ dragging = false;
+ document.body.classList.remove('is-sidebar-resizing');
+ handle.classList.remove('is-active');
+ window.removeEventListener('mousemove', onMove);
+ window.removeEventListener('mouseup', onUp);
+ // Read back from the CSS var so we persist exactly the clamped value
+ // we just rendered (covers the case where the pointer moved past the
+ // limits during the drag).
+ const cur = sidebar.getBoundingClientRect().width;
+ saveWidth(Math.round(cur));
+ }
+
+ handle.addEventListener('mousedown', (e) => {
+ if (e.button !== 0) return;
+ e.preventDefault();
+ dragging = true;
+ startX = e.clientX;
+ startWidth = sidebar.getBoundingClientRect().width;
+ document.body.classList.add('is-sidebar-resizing');
+ handle.classList.add('is-active');
+ window.addEventListener('mousemove', onMove);
+ window.addEventListener('mouseup', onUp);
+ });
+
+ handle.addEventListener('dblclick', () => {
+ applyWidth(DEFAULT_WIDTH);
+ saveWidth(DEFAULT_WIDTH);
+ });
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init, { once: true });
+ } else {
+ init();
+ }
+})();
diff --git a/src/renderer/modules/skills.js b/src/renderer/modules/skills.js
index f6610c47..66708dc4 100644
--- a/src/renderer/modules/skills.js
+++ b/src/renderer/modules/skills.js
@@ -16,9 +16,9 @@ function _skillUiIconHtml(name, className) {
return '';
}
-/** Version + category + author chips for a marketplace-installed skill. Mirrors the
+/** Version + category chips for a marketplace-installed skill. Mirrors the
* marketplace card footer. `_resolveCategoryLabel` is defined in `agents.js` (flat top-level
- * scope per CLAUDE.md §8). Author chip: `create_uid='0'` → 官方 badge; non-zero → user badge. */
+ * scope per CLAUDE.md §8). */
function _skillPlatformChipsHtml(s) {
const lang = getLang();
const parts = [];
@@ -30,12 +30,6 @@ function _skillPlatformChipsHtml(s) {
const catLabel = _resolveCategoryLabel(s.category, lang);
parts.push(`<span class="skill-card-chip">${escapeHtml(catLabel)}</span>`);
}
- if (s.create_uid) {
- const isPlatform = String(s.create_uid) === '0';
- const label = isPlatform ? t('marketplace.author_platform') : t('marketplace.author_user').replace('{uid}', String(s.create_uid));
- const cls = isPlatform ? 'skill-card-chip is-platform' : 'skill-card-chip is-user';
- parts.push(`<span class="${cls}">${escapeHtml(label)}</span>`);
- }
return parts.join('');
}
@@ -705,7 +699,7 @@ async function selectSkillFile(source, id, filepath, nodeEl) {
nameEl.classList.remove('editable');
nameEl.removeAttribute('title');
- // Header chips: custom = "自定义"; marketplace-installed = {category} + {官方/作者}.
+ // Header chips: custom = "自定义"; marketplace-installed = category only.
// Same `_renderSourceMetaHtml` helper as the agent detail page (defined in agents.js,
// shared via the renderer's flat top-level scope per CLAUDE.md §8).
const sourceEl = document.getElementById('skills-detail-source');
@@ -713,7 +707,6 @@ async function selectSkillFile(source, id, filepath, nodeEl) {
sourceEl.innerHTML = _renderSourceMetaHtml({
source,
category: skill?.category || '',
- create_uid: skill?.create_uid || '',
});
// Doc sections (description / external dependencies / dependent
@@ -1083,6 +1076,15 @@ function _scheduleSkillFieldSave(field, value) {
async function _flushSkillFieldSave({ validate = false } = {}) {
clearTimeout(_skillFieldSaveTimer);
_skillFieldSaveTimer = null;
+ // Clicking Done blurs the contenteditable title before the click handler
+ // runs. That blur autosave can clear `_pendingSkillField`; recover the
+ // current DOM value so the explicit commit still performs the dir rename.
+ if (!_pendingSkillField && validate && _selectedSkill?.source === 'custom') {
+ const nameEl = document.getElementById('skills-detail-name');
+ if (nameEl && String(nameEl.innerText || '').trim() !== _selectedSkill.id) {
+ _pendingSkillField = { field: 'name', value: nameEl.innerText };
+ }
+ }
if (!_pendingSkillField || !_selectedSkill) return;
const { field, value } = _pendingSkillField;
if (field === 'name') {
diff --git a/src/renderer/modules/utils.js b/src/renderer/modules/utils.js
index 198a26f8..ccb38592 100644
--- a/src/renderer/modules/utils.js
+++ b/src/renderer/modules/utils.js
@@ -730,9 +730,25 @@ function nowIsoLocal() {
* refreshes with backend's value and the sidebar entry visibly flips.
* Empty input returns '' so the caller can fall back to its own
* placeholder (`t('chat.new_conv_title')` for the conv list). */
+const _AUTO_TITLE_ZH_FILLER = /^(帮我看一下|可不可以|帮我看下|帮我看看|麻烦你|帮我看|我想要|想问问|能不能|可以不|可以吗|请帮我|看一下|麻烦|帮我|我想|想问|请问|看下|看看)\s*/;
+const _AUTO_TITLE_EN_FILLER = /^(could you|would you|can you|help me|i'?d like to|i want to|please)\s+/i;
+const _AUTO_TITLE_CLAUSE = /[,。?!;;,.?!]/;
+const _AUTO_TITLE_MAX = 30;
function _autoTitle(text) {
- let s = String(text == null ? '' : text).trim().replace(/\n/g, ' ');
- if (s.length > 40) s = s.slice(0, 40) + '…';
+ const raw = String(text == null ? '' : text).trim().replace(/\s+/g, ' ');
+ if (!raw) return '';
+ let s = raw;
+ for (let i = 0; i < 5; i++) {
+ const before = s;
+ s = s.replace(_AUTO_TITLE_ZH_FILLER, '').replace(_AUTO_TITLE_EN_FILLER, '');
+ if (s === before) break;
+ }
+ s = s.trim();
+ const clauseIdx = s.search(_AUTO_TITLE_CLAUSE);
+ if (clauseIdx >= 4) s = s.slice(0, clauseIdx);
+ s = s.trim();
+ if (!s) s = raw;
+ if (s.length > _AUTO_TITLE_MAX) s = s.slice(0, _AUTO_TITLE_MAX) + '…';
return s;
}
diff --git a/src/renderer/style.css b/src/renderer/style.css
index 205ee24b..95bb9bbe 100644
--- a/src/renderer/style.css
+++ b/src/renderer/style.css
@@ -81,15 +81,51 @@ body {
/* ─── Sidebar ─── */
.sidebar {
- width: 200px;
+ /* Width is overridden at runtime by sidebar-resize.js via `--sidebar-width`;
+ the 236px fallback (from upstream pre-resize sizing) applies when the
+ custom property hasn't been set. min/max bound the drag-resize range. */
+ width: var(--sidebar-width, 236px);
+ min-width: 180px;
+ max-width: 480px;
background: #fff;
color: var(--text);
display: flex;
flex-direction: column;
flex-shrink: 0;
border-right: 1px solid var(--border);
+ position: relative;
+}
+
+/* Drag handle on the sidebar's right edge. Sits on top of the border so the
+ visible chrome stays the existing 1px line; widens to a 6px hit-zone for
+ the pointer. Double-click resets to default via sidebar-resize.js. */
+.sidebar-resize-handle {
+ position: absolute;
+ top: 0;
+ right: -3px;
+ bottom: 0;
+ width: 6px;
+ cursor: col-resize;
+ z-index: 20;
+ background: transparent;
+ transition: background 0.15s;
+ -webkit-app-region: no-drag;
+}
+.sidebar-resize-handle:hover,
+.sidebar-resize-handle.is-active {
+ background: rgba(59, 130, 246, 0.25);
}
+/* While the user is dragging the handle the whole window adopts a
+ col-resize cursor and we suppress text selection / iframe pointer events so
+ the drag doesn't get hijacked by the chat panel or an artifact iframe. */
+body.is-sidebar-resizing,
+body.is-sidebar-resizing * {
+ cursor: col-resize !important;
+ user-select: none !important;
+}
+body.is-sidebar-resizing iframe { pointer-events: none; }
+
.sidebar-logo {
padding: 10px 16px;
border-bottom: 1px solid var(--border);
@@ -438,6 +474,17 @@ body {
text-align: left;
}
+.sidebar-btn-icon {
+ width: 15px;
+ height: 15px;
+ flex: 0 0 15px;
+ color: #94a3b8;
+}
+
+.sidebar-btn.active .sidebar-btn-icon {
+ color: currentColor;
+}
+
.sidebar-btn:hover {
background: #f1f5f9;
color: var(--text);
@@ -886,6 +933,19 @@ body {
padding-right: 0;
}
+/* Time-bucket headers inside #conversation-list (today / yesterday /
+ last 7 / last 30 / older). Uppercase tracking + muted color so the eye
+ skips them as section labels rather than tappable rows. */
+.conv-list-section-header {
+ padding: 10px 10px 4px 10px;
+ font-size: 10.5px;
+ font-weight: 600;
+ color: #94a3b8;
+ letter-spacing: 0.04em;
+ user-select: none;
+}
+.conv-list-section-header:first-child { padding-top: 4px; }
+
.conv-item {
display: flex;
align-items: center;
@@ -903,6 +963,66 @@ body {
.conv-item:hover { background: #f1f5f9; color: var(--text); }
.conv-item.active { background: #eff6ff; color: var(--primary); }
+.conv-item-action {
+ position: absolute;
+ top: 50%;
+ z-index: 2;
+ width: 20px;
+ height: 20px;
+ border: none;
+ background: transparent;
+ color: #94a3b8;
+ cursor: pointer;
+ border-radius: 4px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0;
+ visibility: hidden;
+ opacity: 0;
+ transform: translateY(-50%);
+ transition: background 0.12s, color 0.12s, opacity 0.12s;
+}
+
+.conv-item-pin { left: 6px; }
+.conv-item-del { right: 6px; }
+
+.conv-item:hover .conv-item-action,
+.conv-item:focus-within .conv-item-action {
+ visibility: visible;
+ opacity: 1;
+}
+
+.conv-item:hover .conv-item-title,
+.conv-item:focus-within .conv-item-title {
+ padding-left: 22px;
+ padding-right: 22px;
+}
+
+.conv-item-action-icon {
+ width: 14px;
+ height: 14px;
+ display: block;
+ transition: transform 0.12s;
+}
+
+.conv-item-pin:not(.is-pinned) .conv-item-action-icon {
+ transform: rotate(35deg);
+}
+
+.conv-item-pin.is-pinned .conv-item-action-icon {
+ transform: rotate(0deg);
+}
+
+.conv-item-pin.is-pinned {
+ color: var(--primary);
+}
+
+.conv-item-pin:hover {
+ background: rgba(37, 99, 235, 0.1);
+ color: var(--primary);
+}
+
.conv-item-title {
flex: 1;
min-width: 0;
@@ -990,22 +1110,6 @@ body {
background: rgba(234, 179, 8, 0.28);
}
-.conv-item-del {
- flex-shrink: 0;
- width: 20px;
- height: 20px;
- border: none;
- background: transparent;
- color: #94a3b8;
- cursor: pointer;
- border-radius: 4px;
- display: none;
- align-items: center;
- justify-content: center;
- font-size: 14px;
-}
-
-.conv-item:hover .conv-item-del { display: flex; }
.conv-item-del:hover { background: rgba(220,38,38,0.1); color: var(--danger); }
.conv-empty {
@@ -2673,6 +2777,11 @@ body.model-not-configured .main-content { flex-direction: column; }
caret-color: var(--text);
-webkit-text-fill-color: transparent;
}
+.chat-input-mirror-wrap textarea::placeholder {
+ color: transparent;
+ opacity: 0;
+ -webkit-text-fill-color: transparent;
+}
.chat-input-mirror {
position: absolute;
inset: 0;
@@ -2693,6 +2802,10 @@ body.model-not-configured .main-content { flex-direction: column; }
tab-size: 4;
box-sizing: border-box;
}
+.chat-input-mirror:empty::before {
+ content: attr(data-placeholder);
+ color: #94a3b8;
+}
.chat-input-mirror .msg-mention {
color: var(--accent, #2563eb);
font-weight: 500;
@@ -7370,6 +7483,88 @@ body.model-not-configured .main-content { flex-direction: column; }
opacity: 0.6;
}
+/* ── Devtools archive list ── */
+.devtools-list-badge {
+ display: inline-block;
+ font-size: 10px;
+ padding: 1px 6px;
+ border-radius: 999px;
+ margin-left: 6px;
+ line-height: 1.5;
+ vertical-align: middle;
+}
+/* Session-kind badges (agent-edit / skill-edit / KB image vision). conv (主对话)
+ intentionally has no badge — it's the default. */
+.devtools-list-badge.is-kind-agent { background: #fef3c7; color: #92400e; }
+.devtools-list-badge.is-kind-skill { background: #ecfccb; color: #4d7c0f; }
+.devtools-list-badge.is-kind-extract-img { background: #fce7f3; color: #9d174d; }
+.devtools-list-badge.is-kind-cli { background: #eef2ff; color: #3730a3; }
+
+/* ── Devtools skill-metrics table ── */
+.devtools-skill-metrics-summary {
+ padding: 6px 14px 8px 14px;
+ font-size: 11px;
+ color: var(--text-muted, #6b7280);
+}
+.devtools-skill-metrics-body {
+ overflow-x: auto;
+ padding: 0 8px 8px 8px;
+}
+.devtools-skill-metrics-table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 12px;
+}
+.devtools-skill-metrics-table th,
+.devtools-skill-metrics-table td {
+ padding: 6px 10px;
+ border-bottom: 1px solid #eef2f7;
+ text-align: left;
+ vertical-align: middle;
+}
+.devtools-skill-metrics-table th {
+ font-weight: 600;
+ font-size: 10.5px;
+ color: #94a3b8;
+ letter-spacing: 0.04em;
+ background: #fafbfc;
+}
+.devtools-skill-metrics-table td.num { text-align: right; font-variant-numeric: tabular-nums; }
+.devtools-skill-metrics-table tbody tr:hover { background: #f8fafc; }
+
+.devtools-skill-cell-name { line-height: 1.3; }
+.devtools-skill-name {
+ display: block;
+ font-weight: 500;
+ color: var(--text, #1f2937);
+}
+.devtools-skill-id,
+.devtools-skill-id-only {
+ display: block;
+ font-size: 10.5px;
+ color: var(--text-muted, #6b7280);
+ font-family: ui-monospace, SFMono-Regular, monospace;
+}
+.devtools-skill-id-only { font-size: 12px; color: var(--text, #1f2937); font-family: inherit; }
+
+.devtools-skill-badge {
+ display: inline-block;
+ font-size: 10px;
+ padding: 1px 6px;
+ border-radius: 999px;
+ line-height: 1.5;
+}
+.devtools-skill-badge.is-custom { background: #ecfccb; color: #4d7c0f; }
+.devtools-skill-badge.is-platform { background: #dbeafe; color: #1e40af; }
+.devtools-skill-badge.is-b { background: #fef3c7; color: #92400e; }
+
+.devtools-skill-metrics-days { display: inline-flex; gap: 4px; margin-right: 6px; }
+.devtools-skill-metrics-days .btn.active {
+ background: var(--primary, #2563eb);
+ color: #fff;
+ border-color: transparent;
+}
+
/* ─── MathJax tweaks (chat bubbles) ────────────────────────────────────────
Display math on long formulas exceeds bubble width; give it a horizontal
scrollbar instead of clipping / stretching the bubble. Inline math just
diff --git a/test/main/features/chats-autotitle.test.ts b/test/main/features/chats-autotitle.test.ts
new file mode 100644
index 00000000..59bcf78b
--- /dev/null
+++ b/test/main/features/chats-autotitle.test.ts
@@ -0,0 +1,92 @@
+import { describe, it, expect } from 'vitest';
+import { autoTitle } from '../../../src/main/features/chats';
+
+// Heuristic autoTitle ladder: trim → filler strip (zh+en, longest-first, loop
+// ≤ 5) → first-clause split with ≥ 4 char floor → 30 char truncate → fallback
+// to original input → fallback to default-title key. Per CLAUDE.md §9 LLM-
+// output text munging rule: pin set A (must produce a clean title) AND
+// set B (must NOT over-strip / must NOT crash).
+
+describe('autoTitle — set A (produces clean title)', () => {
+ it('strips Chinese filler "看下" prefix', () => {
+ expect(autoTitle('看下本地还有哪些修改没提交')).toBe('本地还有哪些修改没提交');
+ });
+
+ it('strips Chinese filler "请帮我" prefix', () => {
+ expect(autoTitle('请帮我修复一下这个 bug')).toBe('修复一下这个 bug');
+ });
+
+ it('strips Chinese filler "想问问" prefix', () => {
+ expect(autoTitle('想问问这个怎么实现')).toBe('这个怎么实现');
+ });
+
+ it('strips stacked Chinese fillers ("请帮我看下...")', () => {
+ expect(autoTitle('请帮我看下数据库连接')).toBe('数据库连接');
+ });
+
+ it('strips English filler "Can you " case-insensitively', () => {
+ expect(autoTitle('Can you help me debug this?')).toBe('debug this');
+ });
+
+ it('strips stacked English fillers ("Could you please ...")', () => {
+ expect(autoTitle('Could you please review my PR')).toBe('review my PR');
+ });
+
+ it('cuts at first clause when ≥ 4 chars', () => {
+ expect(autoTitle('本地修改,顺便看下提交')).toBe('本地修改');
+ });
+
+ it('keeps full text when input lacks any filler', () => {
+ expect(autoTitle('搜索下最新一个月的ai圈的主要事件'))
+ .toBe('搜索下最新一个月的ai圈的主要事件');
+ });
+
+ it('collapses internal whitespace + newlines to single space', () => {
+ expect(autoTitle('看下\n本地\n 修改')).toBe('本地 修改');
+ });
+
+ it('truncates at 30 chars with ellipsis', () => {
+ const long = '搜索下' + 'A'.repeat(50);
+ const out = autoTitle(long);
+ expect(out.length).toBe(31); // 30 + …
+ expect(out.endsWith('…')).toBe(true);
+ });
+});
+
+describe('autoTitle — set B (must NOT over-strip / must NOT crash)', () => {
+ it('pure-filler input falls back to original (not empty)', () => {
+ expect(autoTitle('看下')).toBe('看下');
+ });
+
+ it('whitespace-only input falls back to default title key (non-empty)', () => {
+ const out = autoTitle(' \n \t ');
+ expect(out.length).toBeGreaterThan(0);
+ });
+
+ it('empty input falls back to default title key (non-empty)', () => {
+ const out = autoTitle('');
+ expect(out.length).toBeGreaterThan(0);
+ });
+
+ it('filler mid-text is NOT stripped (only leading)', () => {
+ expect(autoTitle('本地的看下逻辑对吗')).toBe('本地的看下逻辑对吗');
+ });
+
+ it('clause split with short first clause keeps full text', () => {
+ // "AI" is 2 chars → below the 4-char floor → don't cut, keep whole text.
+ expect(autoTitle('AI,请说说看')).toBe('AI,请说说看');
+ });
+
+ it('null/undefined input does not throw', () => {
+ expect(() => autoTitle(null as unknown as string)).not.toThrow();
+ expect(() => autoTitle(undefined as unknown as string)).not.toThrow();
+ });
+
+ it('does not strip single-character "请" alone (would clip "请教...")', () => {
+ expect(autoTitle('请教这个问题怎么解决')).toBe('请教这个问题怎么解决');
+ });
+
+ it('preserves non-filler English starting words', () => {
+ expect(autoTitle('Search the latest AI news')).toBe('Search the latest AI news');
+ });
+});
diff --git a/test/main/features/chats.test.ts b/test/main/features/chats.test.ts
index e4bc3f37..dc3c9474 100644
--- a/test/main/features/chats.test.ts
+++ b/test/main/features/chats.test.ts
@@ -83,6 +83,38 @@ describe('chats › createConversation', () => {
});
});
+describe('chats › setConversationPinned', () => {
+ it('pins a conversation above newer unpinned rows without changing activity time', async () => {
+ const chats = await loadChats();
+ const older = await chats.createConversation(TEST_UID, { title: 'older' });
+ const newer = await chats.createConversation(TEST_UID, { title: 'newer' });
+ const before = await chats.getConversation(TEST_UID, older.conversation_id);
+
+ const pinned = await chats.setConversationPinned(TEST_UID, older.conversation_id, true);
+ expect(pinned?.pinned_at).toBeTruthy();
+ expect(pinned?.updated_at).toBe(before?.updated_at);
+
+ const listed = await chats.listConversations(TEST_UID);
+ expect(listed.map((c) => c.conversation_id)).toEqual([
+ older.conversation_id,
+ newer.conversation_id,
+ ]);
+ });
+
+ it('unpins a conversation and removes pinned_at from the persisted index', async () => {
+ const chats = await loadChats();
+ const conv = await chats.createConversation(TEST_UID, { title: 'pin me' });
+ await chats.setConversationPinned(TEST_UID, conv.conversation_id, true);
+
+ const unpinned = await chats.setConversationPinned(TEST_UID, conv.conversation_id, false);
+ expect(unpinned?.pinned_at).toBeUndefined();
+
+ const idx = JSON.parse(fs.readFileSync(
+ path.join(tmpDir, TEST_UID, 'cloud', 'chats', '_index.json'), 'utf-8'));
+ expect(idx[0].pinned_at).toBeUndefined();
+ });
+});
+
describe('chats › deleteConversation', () => {
it('removes the conv from index + drops <cid>.jsonl + group dir', async () => {
const chats = await loadChats();
diff --git a/test/main/features/expert_signals/skill_ineffective.test.ts b/test/main/features/expert_signals/skill_ineffective.test.ts
new file mode 100644
index 00000000..9cb4c8b4
--- /dev/null
+++ b/test/main/features/expert_signals/skill_ineffective.test.ts
@@ -0,0 +1,178 @@
+import { describe, it, expect } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+// Same setup shape as turn_buffer.test.ts — WS_ROOT swap + activateUser
+// must run before any expert_signals import (storage caches active uid).
+const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'sig-skill-ineff-'));
+process.env.ORKAS_WORKSPACE_ROOT = TMP;
+fs.writeFileSync(path.join(TMP, 'users.json'),
+ JSON.stringify({ current_user_id: '99999992', users: [{ user_id: '99999992', created_at: new Date().toISOString() }] }));
+const UID = '99999992';
+
+import { activateUser } from '../../../../src/main/features/users';
+activateUser(UID);
+
+import { createSkillTurnBuffer } from '../../../../src/main/features/expert_signals/turn_hooks';
+import { querySignals } from '../../../../src/main/features/expert_signals';
+
+async function wait() { return new Promise((r) => setTimeout(r, 30)); }
+
+// Per CLAUDE.md §9: text-munging / extractor / decision branches must have
+// fixture coverage for shapes that MUST emit (set A) AND shapes that MUST
+// NOT (set B). The new skill_ineffective signal is a turn-end decision.
+
+describe('SkillTurnBuffer.drainAndEmit › skill_ineffective — set A (emits)', () => {
+ it('1 invoked + permanent errText → 1 skill_ineffective', async () => {
+ const buf = createSkillTurnBuffer();
+ buf.recordInvoked('search-docs', 'A.custom', 'read_file');
+ const cid = 'cid-ineff-a1';
+ buf.drainAndEmit({
+ uid: UID, cid, aid: 'agent_x',
+ turn_id: 'm_a1', msg_ids: ['m_a1'],
+ errText: 'agent specification missing — file vanished mid-turn',
+ });
+ await wait();
+
+ const sigs = await querySignals({ types: ['skill_ineffective'], cid });
+ expect(sigs.length).toBe(1);
+ expect(sigs[0].delta!.system).toBe('A.custom');
+ expect(sigs[0].delta!.skill_id).toBe('search-docs');
+ expect(sigs[0].turn_id).toBe('m_a1');
+ expect(sigs[0].metadata!.error_kind).toBe('permanent');
+ expect(typeof sigs[0].metadata!.error_excerpt).toBe('string');
+ });
+
+ it('multiple invoked across systems + permanent errText → 1 signal per skill', async () => {
+ const buf = createSkillTurnBuffer();
+ buf.recordInvoked('skill-a', 'A.custom', 'read_file');
+ buf.recordInvoked('skill-b', 'A.platform', 'read_file');
+ buf.recordInvoked('skill-c', 'B', 'read_file');
+ const cid = 'cid-ineff-a2';
+ buf.drainAndEmit({
+ uid: UID, cid, aid: 'agent_x',
+ turn_id: 'm_a2', msg_ids: ['m_a2'],
+ errText: 'parse failure: invalid JSON in tool output',
+ });
+ await wait();
+
+ const sigs = await querySignals({ types: ['skill_ineffective'], cid });
+ expect(sigs.length).toBe(3);
+ const bySkill = new Map(sigs.map((s) => [s.delta!.skill_id, s.delta!.system]));
+ expect(bySkill.get('skill-a')).toBe('A.custom');
+ expect(bySkill.get('skill-b')).toBe('A.platform');
+ expect(bySkill.get('skill-c')).toBe('B');
+ });
+
+ it('error_excerpt is truncated to 200 chars', async () => {
+ const buf = createSkillTurnBuffer();
+ buf.recordInvoked('x', 'A.custom', 'read_file');
+ const cid = 'cid-ineff-a3';
+ const longErr = 'permanent failure: ' + 'X'.repeat(500);
+ buf.drainAndEmit({
+ uid: UID, cid, aid: 'agent_x',
+ turn_id: 'm_a3', msg_ids: ['m_a3'],
+ errText: longErr,
+ });
+ await wait();
+
+ const sigs = await querySignals({ types: ['skill_ineffective'], cid });
+ expect(sigs.length).toBe(1);
+ expect((sigs[0].metadata!.error_excerpt as string).length).toBe(200);
+ });
+});
+
+describe('SkillTurnBuffer.drainAndEmit › skill_ineffective — set B (does NOT emit)', () => {
+ it('no invoked + permanent errText → 0 signals', async () => {
+ const buf = createSkillTurnBuffer();
+ // No invoked recorded.
+ const cid = 'cid-ineff-b1';
+ buf.drainAndEmit({
+ uid: UID, cid, aid: 'agent_x',
+ turn_id: 'm_b1', msg_ids: ['m_b1'],
+ errText: 'permanent: spec missing',
+ });
+ await wait();
+
+ const sigs = await querySignals({ types: ['skill_ineffective'], cid });
+ expect(sigs.length).toBe(0);
+ });
+
+ it('invoked + empty errText → 0 signals (clean turn)', async () => {
+ const buf = createSkillTurnBuffer();
+ buf.recordInvoked('search-docs', 'A.custom', 'read_file');
+ const cid = 'cid-ineff-b2';
+ buf.drainAndEmit({
+ uid: UID, cid, aid: 'agent_x',
+ turn_id: 'm_b2', msg_ids: ['m_b2'],
+ // errText omitted
+ });
+ await wait();
+
+ const sigs = await querySignals({ types: ['skill_ineffective'], cid });
+ expect(sigs.length).toBe(0);
+ });
+
+ it('invoked + transient errText (ECONNRESET) → 0 signals', async () => {
+ const buf = createSkillTurnBuffer();
+ buf.recordInvoked('search-docs', 'A.custom', 'read_file');
+ const cid = 'cid-ineff-b3';
+ buf.drainAndEmit({
+ uid: UID, cid, aid: 'agent_x',
+ turn_id: 'm_b3', msg_ids: ['m_b3'],
+ errText: 'request failed: ECONNRESET',
+ });
+ await wait();
+
+ const sigs = await querySignals({ types: ['skill_ineffective'], cid });
+ expect(sigs.length).toBe(0);
+ });
+
+ it('invoked + transient errText (fetch failed) → 0 signals', async () => {
+ const buf = createSkillTurnBuffer();
+ buf.recordInvoked('search-docs', 'A.custom', 'read_file');
+ const cid = 'cid-ineff-b4';
+ buf.drainAndEmit({
+ uid: UID, cid, aid: 'agent_x',
+ turn_id: 'm_b4', msg_ids: ['m_b4'],
+ errText: 'fetch failed at provider',
+ });
+ await wait();
+
+ const sigs = await querySignals({ types: ['skill_ineffective'], cid });
+ expect(sigs.length).toBe(0);
+ });
+
+ it('invoked + permanent errText + aborted=true → 0 signals (user-cancelled is not the skill\'s fault)', async () => {
+ const buf = createSkillTurnBuffer();
+ buf.recordInvoked('search-docs', 'A.custom', 'read_file');
+ const cid = 'cid-ineff-b5';
+ buf.drainAndEmit({
+ uid: UID, cid, aid: 'agent_x',
+ turn_id: 'm_b5', msg_ids: ['m_b5'],
+ errText: 'aborted by user',
+ aborted: true,
+ });
+ await wait();
+
+ const sigs = await querySignals({ types: ['skill_ineffective'], cid });
+ expect(sigs.length).toBe(0);
+ });
+
+ it('legacy call (no errText / aborted args) keeps the old skill_invoked behavior', async () => {
+ const buf = createSkillTurnBuffer();
+ buf.recordInvoked('search-docs', 'A.custom', 'read_file');
+ const cid = 'cid-ineff-b6';
+ buf.drainAndEmit({
+ uid: UID, cid, aid: 'agent_x',
+ turn_id: 'm_b6', msg_ids: ['m_b6'],
+ });
+ await wait();
+
+ const ineff = await querySignals({ types: ['skill_ineffective'], cid });
+ expect(ineff.length).toBe(0);
+ const inv = await querySignals({ types: ['skill_invoked'], cid });
+ expect(inv.length).toBe(1); // legacy emit still fires
+ });
+});
diff --git a/test/main/features/expert_signals/turn_hooks.test.ts b/test/main/features/expert_signals/turn_hooks.test.ts
new file mode 100644
index 00000000..0615cf44
--- /dev/null
+++ b/test/main/features/expert_signals/turn_hooks.test.ts
@@ -0,0 +1,209 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+// Same setup shape as turn_buffer.test.ts — WS_ROOT swap + activateUser
+// must run before any expert_signals import (storage caches active uid).
+const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'sig-turn-hooks-'));
+process.env.ORKAS_WORKSPACE_ROOT = TMP;
+fs.writeFileSync(path.join(TMP, 'users.json'),
+ JSON.stringify({ current_user_id: '99999993', users: [{ user_id: '99999993', created_at: new Date().toISOString() }] }));
+const UID = '99999993';
+
+import { activateUser } from '../../../../src/main/features/users';
+activateUser(UID);
+
+import {
+ onAgentTurnEnd,
+ onUserMessage,
+ _clearAgentMsgCache,
+} from '../../../../src/main/features/expert_signals/turn_hooks';
+import { querySignals } from '../../../../src/main/features/expert_signals';
+
+async function wait() { return new Promise((r) => setTimeout(r, 30)); }
+
+// Why this file exists: phase-0 commit 76358a8e shipped the chokepoint
+// functions (onAgentTurnEnd / onUserMessage) and the bus.ts wiring, but
+// the bus.ts portion silently fell out of the commit. The fall-out wasn't
+// detected because all expert_signals coverage was on the pure extractors
+// (text.test.ts / silence.test.ts / event.test.ts) — none exercised the
+// chokepoint end-to-end. These fixtures lock the chokepoint behaviour so
+// the next time someone refactors turn_hooks or moves the bus call site,
+// a missing wire surfaces in the test suite, not in production weeks
+// later. See `docs/plans/expert-signals-phase0-wiring-gaps.md`.
+
+beforeEach(() => {
+ _clearAgentMsgCache();
+});
+
+describe('onAgentTurnEnd › set A (live emit + cache)', () => {
+ it('caches agent msg + does NOT emit signals on a clean turn (no errText)', async () => {
+ const cid = 'cid-tha-a1';
+ onAgentTurnEnd({
+ uid: UID, cid,
+ actorId: 'agent_x',
+ isCommander: false,
+ agentMsg: { id: 'm_a1', text: 'Here is the plan.' },
+ // No errText → no tool_failure.
+ });
+ await wait();
+
+ const errSigs = await querySignals({ types: ['tool_failure'], cid });
+ expect(errSigs.length).toBe(0);
+ // Cache write is observable via the next onUserMessage call below.
+ });
+
+ it('errText non-empty → emits tool_failure once', async () => {
+ const cid = 'cid-tha-a2';
+ onAgentTurnEnd({
+ uid: UID, cid,
+ actorId: 'agent_x',
+ isCommander: false,
+ agentMsg: { id: 'm_a2', text: 'sorry' },
+ errText: 'permanent: agent spec missing',
+ });
+ await wait();
+
+ const sigs = await querySignals({ types: ['tool_failure'], cid });
+ expect(sigs.length).toBe(1);
+ expect(sigs[0].turn_id).toBe('m_a2');
+ expect(sigs[0].metadata!.error_excerpt).toContain('agent spec missing');
+ });
+
+ it('commander turn → aid is null on emitted signals', async () => {
+ const cid = 'cid-tha-a3';
+ onAgentTurnEnd({
+ uid: UID, cid,
+ actorId: 'commander',
+ isCommander: true,
+ agentMsg: { id: 'm_a3', text: 'done.' },
+ errText: 'something broke',
+ });
+ await wait();
+
+ const sigs = await querySignals({ types: ['tool_failure'], cid });
+ expect(sigs.length).toBe(1);
+ expect(sigs[0].aid).toBeNull();
+ });
+});
+
+describe('onUserMessage › set A (text-signal extraction after cache)', () => {
+ it('correction word → emits correction signal joined on cached turn_id', async () => {
+ const cid = 'cid-thu-a1';
+ onAgentTurnEnd({
+ uid: UID, cid,
+ actorId: 'agent_x',
+ isCommander: false,
+ agentMsg: { id: 'm_thu_a1', text: '我帮你写了一段示例代码。' },
+ });
+ const r = await onUserMessage({
+ uid: UID, cid,
+ userMsg: { id: 'u_a1', text: '不对,应该用另一种写法' },
+ });
+ expect(r.correctionDetected).toBe(true);
+ await wait();
+
+ const sigs = await querySignals({ types: ['correction'], cid });
+ expect(sigs.length).toBeGreaterThanOrEqual(1);
+ expect(sigs[0].turn_id).toBe('m_thu_a1');
+ expect(sigs[0].aid).toBe('agent_x');
+ });
+
+ it('explicit accept word → emits accept signal', async () => {
+ const cid = 'cid-thu-a2';
+ onAgentTurnEnd({
+ uid: UID, cid,
+ actorId: 'agent_x',
+ isCommander: false,
+ agentMsg: { id: 'm_thu_a2', text: 'How about this approach?' },
+ });
+ await onUserMessage({
+ uid: UID, cid,
+ userMsg: { id: 'u_a2', text: '好的,就这样' },
+ });
+ await wait();
+
+ const sigs = await querySignals({ types: ['accept'], cid });
+ expect(sigs.length).toBe(1);
+ expect(sigs[0].turn_id).toBe('m_thu_a2');
+ });
+
+ it('rejection word → emits reject signal', async () => {
+ const cid = 'cid-thu-a3';
+ onAgentTurnEnd({
+ uid: UID, cid,
+ actorId: 'agent_x',
+ isCommander: false,
+ agentMsg: { id: 'm_thu_a3', text: '我用 Python 实现一个排序。' },
+ });
+ await onUserMessage({
+ uid: UID, cid,
+ userMsg: { id: 'u_a3', text: '算了,不要这个了' },
+ });
+ await wait();
+
+ const sigs = await querySignals({ types: ['reject'], cid });
+ expect(sigs.length).toBe(1);
+ });
+});
+
+describe('onUserMessage / onAgentTurnEnd › set B (must NOT emit)', () => {
+ it('onUserMessage with no prior onAgentTurnEnd → no signals (cache miss)', async () => {
+ const cid = 'cid-thu-b1';
+ const r = await onUserMessage({
+ uid: UID, cid,
+ userMsg: { id: 'u_b1', text: '不对' },
+ });
+ expect(r.correctionDetected).toBe(false);
+ await wait();
+
+ const sigs = await querySignals({
+ types: ['correction', 'accept', 'reject', 'edit'],
+ cid,
+ });
+ expect(sigs.length).toBe(0);
+ });
+
+ it('silent agent turn (empty text) → no cache, so next user msg gets no signal', async () => {
+ const cid = 'cid-thu-b2';
+ onAgentTurnEnd({
+ uid: UID, cid,
+ actorId: 'agent_x',
+ isCommander: false,
+ agentMsg: { id: 'm_thu_b2', text: '' }, // silent turn
+ });
+ await onUserMessage({
+ uid: UID, cid,
+ userMsg: { id: 'u_b2', text: '不对' },
+ });
+ await wait();
+
+ const sigs = await querySignals({
+ types: ['correction', 'accept', 'reject', 'edit'],
+ cid,
+ });
+ expect(sigs.length).toBe(0);
+ });
+
+ it('neutral user reply → no correction/accept/reject (might still emit edit if it looks like one)', async () => {
+ const cid = 'cid-thu-b3';
+ onAgentTurnEnd({
+ uid: UID, cid,
+ actorId: 'agent_x',
+ isCommander: false,
+ agentMsg: { id: 'm_thu_b3', text: '我建议先做需求分析。' },
+ });
+ await onUserMessage({
+ uid: UID, cid,
+ userMsg: { id: 'u_b3', text: '我去问问产品经理' },
+ });
+ await wait();
+
+ const tagged = await querySignals({
+ types: ['correction', 'accept', 'reject'],
+ cid,
+ });
+ expect(tagged.length).toBe(0);
+ });
+});
diff --git a/test/main/features/group_chat/plan_executor.test.ts b/test/main/features/group_chat/plan_executor.test.ts
index ca66cf99..fe48228c 100644
--- a/test/main/features/group_chat/plan_executor.test.ts
+++ b/test/main/features/group_chat/plan_executor.test.ts
@@ -208,6 +208,51 @@ describe('plan_executor › sequential pipeline + variable substitution', () =>
}, 15_000);
});
+describe('plan_executor › plan-triggered agent live events', () => {
+ it('emits agent process/delta events before the plan-step final message', async () => {
+ const cid = newCid();
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+
+ _setScript(state.buildGmemberSessionId(cid, A_ID), [
+ { type: 'progress', text: 'searching sources' },
+ {
+ type: 'event',
+ event: {
+ stream: 'tool',
+ data: { phase: 'start', id: 'tool-1', name: 'web_search', arguments: { query: 'education' } },
+ },
+ },
+ { type: 'delta', text: 'partial answer' },
+ { type: 'final', text: 'final answer' },
+ ]);
+
+ const events: any[] = [];
+ const unsubscribe = bus.subscribe(TEST_UID, cid, (ev) => events.push(ev));
+ try {
+ await setupPlanAndKick(TEST_UID, cid, {
+ initial_message: 'research education',
+ steps: [
+ { title: 'research', assignee: A_NAME, input: 'go', wait_for: [] },
+ ],
+ });
+ await waitForQuiescent(TEST_UID, cid, 5000);
+ } finally {
+ unsubscribe();
+ }
+
+ const agentProcessIdx = events.findIndex((e) => e.type === 'process' && e.actor === A_ID);
+ const agentMessageIdx = events.findIndex((e) => e.type === 'message' && e.turn_end === true && e.msg?.from === A_ID);
+ expect(agentProcessIdx).toBeGreaterThanOrEqual(0);
+ expect(agentMessageIdx).toBeGreaterThan(agentProcessIdx);
+
+ const agentProcessEvents = events.filter((e) => e.type === 'process' && e.actor === A_ID);
+ expect(agentProcessEvents.some((e) => e.data?.type === 'progress' && e.data.text === 'searching sources')).toBe(true);
+ expect(agentProcessEvents.some((e) => e.data?.type === 'event' && e.data.event?.stream === 'tool')).toBe(true);
+ expect(agentProcessEvents.some((e) => e.data?.type === 'delta' && e.data.text === 'partial answer')).toBe(true);
+ }, 15_000);
+});
+
// ─────────────────────────────────────────────────────────────────────────
// Test 2 — parallel fork + synthesis
// ─────────────────────────────────────────────────────────────────────────
diff --git a/test/main/features/skill_metrics.test.ts b/test/main/features/skill_metrics.test.ts
new file mode 100644
index 00000000..8e763184
--- /dev/null
+++ b/test/main/features/skill_metrics.test.ts
@@ -0,0 +1,179 @@
+import { describe, it, expect } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+// Same setup shape as other expert_signals tests — WS_ROOT swap +
+// activateUser BEFORE importing the aggregator (storage caches active uid).
+const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'sk-metrics-'));
+process.env.ORKAS_WORKSPACE_ROOT = TMP;
+fs.writeFileSync(path.join(TMP, 'users.json'),
+ JSON.stringify({ current_user_id: '99999994', users: [{ user_id: '99999994', created_at: new Date().toISOString() }] }));
+const UID = '99999994';
+
+import { activateUser } from '../../../src/main/features/users';
+activateUser(UID);
+
+import { emitSignal } from '../../../src/main/features/expert_signals';
+import {
+ buildSkillAdvertisedSignal,
+ buildSkillInvokedSignal,
+ buildSkillIneffectiveSignal,
+} from '../../../src/main/features/expert_signals/extractors/event';
+import { aggregateSkillMetrics } from '../../../src/main/features/skill_metrics';
+
+async function wait() { return new Promise((r) => setTimeout(r, 30)); }
+
+function findRow(rows: any[], skill_id: string, system: string) {
+ return rows.find((r) => r.skill_id === skill_id && r.skill_system === system) || null;
+}
+
+describe('aggregateSkillMetrics — invocation_rate', () => {
+ it('2 advertise + 1 invoke for the same skill → invocation_rate = 0.5', async () => {
+ emitSignal(UID, buildSkillAdvertisedSignal({
+ cid: 'cid_inv_1', aid: 'agent_x', turn_id: 't1', system: 'A.custom', skill_ids: ['summary-writer'],
+ }));
+ emitSignal(UID, buildSkillAdvertisedSignal({
+ cid: 'cid_inv_1', aid: 'agent_x', turn_id: 't2', system: 'A.custom', skill_ids: ['summary-writer'],
+ }));
+ emitSignal(UID, buildSkillInvokedSignal({
+ cid: 'cid_inv_1', aid: 'agent_x', turn_id: 't1', system: 'A.custom', skill_id: 'summary-writer', trigger: 'read_file',
+ }));
+ await wait();
+
+ const r = await aggregateSkillMetrics({ sinceDays: 1 });
+ const row = findRow(r.rows, 'summary-writer', 'A.custom');
+ expect(row).not.toBeNull();
+ expect(row.advertised).toBeGreaterThanOrEqual(2);
+ expect(row.invoked).toBeGreaterThanOrEqual(1);
+ expect(row.invocation_rate).toBeGreaterThan(0);
+ expect(row.invocation_rate).toBeLessThanOrEqual(0.5 + 0.01);
+ });
+});
+
+describe('aggregateSkillMetrics — cross-system distinct rows', () => {
+ it('same skill_id under A.custom and A.platform → two separate rows', async () => {
+ emitSignal(UID, buildSkillInvokedSignal({
+ cid: 'cid_sys_1', aid: 'agent_y', turn_id: 't_sys_a', system: 'A.custom', skill_id: 'shared-id', trigger: 'read_file',
+ }));
+ emitSignal(UID, buildSkillInvokedSignal({
+ cid: 'cid_sys_1', aid: 'agent_y', turn_id: 't_sys_b', system: 'A.platform', skill_id: 'shared-id', trigger: 'read_file',
+ }));
+ await wait();
+
+ const r = await aggregateSkillMetrics({ sinceDays: 1 });
+ expect(findRow(r.rows, 'shared-id', 'A.custom')).not.toBeNull();
+ expect(findRow(r.rows, 'shared-id', 'A.platform')).not.toBeNull();
+ });
+});
+
+describe('aggregateSkillMetrics — modified-after-hit JOIN', () => {
+ it('invoke + correction same turn_id → modified_after_hit = 1', async () => {
+ const turn = 't_mod_1';
+ emitSignal(UID, buildSkillInvokedSignal({
+ cid: 'cid_mod_1', aid: 'agent_z', turn_id: turn, system: 'A.custom', skill_id: 'review-skill', trigger: 'read_file',
+ }));
+ emitSignal(UID, {
+ type: 'correction', source: 'event', cid: 'cid_mod_1', aid: 'agent_z',
+ turn_id: turn, context_ref: { msg_ids: [turn] },
+ extractor_version: '[email protected]',
+ delta: { matched_patterns: ['不对'] },
+ } as any);
+ await wait();
+
+ const r = await aggregateSkillMetrics({ sinceDays: 1 });
+ const row = findRow(r.rows, 'review-skill', 'A.custom');
+ expect(row).not.toBeNull();
+ expect(row.modified_after_hit).toBeGreaterThanOrEqual(1);
+ expect(row.modified_after_hit_rate).toBeGreaterThan(0);
+ });
+
+ it('two invokes in same turn + correction → both charged (over-attribute on purpose)', async () => {
+ const turn = 't_mod_multi';
+ emitSignal(UID, buildSkillInvokedSignal({
+ cid: 'cid_mod_multi', aid: 'agent_z', turn_id: turn, system: 'A.custom', skill_id: 'skill-x', trigger: 'read_file',
+ }));
+ emitSignal(UID, buildSkillInvokedSignal({
+ cid: 'cid_mod_multi', aid: 'agent_z', turn_id: turn, system: 'A.custom', skill_id: 'skill-y', trigger: 'read_file',
+ }));
+ emitSignal(UID, {
+ type: 'edit', source: 'event', cid: 'cid_mod_multi', aid: 'agent_z',
+ turn_id: turn, context_ref: { msg_ids: [turn] },
+ extractor_version: '[email protected]',
+ delta: { edit_distance: 142, edit_type: 'major_rewrite' },
+ } as any);
+ await wait();
+
+ const r = await aggregateSkillMetrics({ sinceDays: 1 });
+ const rx = findRow(r.rows, 'skill-x', 'A.custom');
+ const ry = findRow(r.rows, 'skill-y', 'A.custom');
+ expect(rx.modified_after_hit).toBeGreaterThanOrEqual(1);
+ expect(ry.modified_after_hit).toBeGreaterThanOrEqual(1);
+ });
+
+ it('invoke without same-turn correction/edit → modified_after_hit = 0', async () => {
+ emitSignal(UID, buildSkillInvokedSignal({
+ cid: 'cid_mod_none', aid: 'agent_z', turn_id: 't_mod_none',
+ system: 'A.custom', skill_id: 'unrelated-skill', trigger: 'read_file',
+ }));
+ await wait();
+
+ const r = await aggregateSkillMetrics({ sinceDays: 1 });
+ const row = findRow(r.rows, 'unrelated-skill', 'A.custom');
+ expect(row.modified_after_hit).toBe(0);
+ });
+});
+
+describe('aggregateSkillMetrics — negative_transfer from skill_ineffective', () => {
+ it('1 invoke + 1 skill_ineffective same turn → ineffective = 1', async () => {
+ emitSignal(UID, buildSkillInvokedSignal({
+ cid: 'cid_neg', aid: 'agent_a', turn_id: 't_neg',
+ system: 'A.custom', skill_id: 'bad-skill', trigger: 'read_file',
+ }));
+ emitSignal(UID, buildSkillIneffectiveSignal({
+ cid: 'cid_neg', aid: 'agent_a', turn_id: 't_neg',
+ system: 'A.custom', skill_id: 'bad-skill',
+ error_excerpt: 'permanent: parse failure',
+ }));
+ await wait();
+
+ const r = await aggregateSkillMetrics({ sinceDays: 1 });
+ const row = findRow(r.rows, 'bad-skill', 'A.custom');
+ expect(row).not.toBeNull();
+ expect(row.ineffective).toBe(1);
+ expect(row.ineffective_rate).toBeCloseTo(1.0, 2); // 1 / 1
+ });
+});
+
+describe('aggregateSkillMetrics — empty / display_name fallback', () => {
+ it('no signals in range → empty rows + 0 scanned', async () => {
+ // Query a future window (no signals there yet).
+ const farFuture = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString();
+ // aggregateSkillMetrics's window is `now - sinceDays` to `now`; we
+ // can't push it into the future. So we sanity-check by emitting
+ // nothing for a brand-new uid (already done via this test's beforeEach
+ // isolation? — no, all tests in this file share storage). Instead
+ // verify the shape contract via the actual report on the merged data.
+ const r = await aggregateSkillMetrics({ sinceDays: 0.001 }); // ~< 90 seconds — effectively now
+ expect(Array.isArray(r.rows)).toBe(true);
+ expect(r.range.since).toBeTruthy();
+ expect(r.range.until).toBeTruthy();
+ expect(typeof r.total_signals_scanned).toBe('number');
+ // Discard farFuture — only used to reference the API shape.
+ void farFuture;
+ });
+
+ it('display_name falls back to skill_id when unresolvable', async () => {
+ emitSignal(UID, buildSkillInvokedSignal({
+ cid: 'cid_name', aid: 'agent_b', turn_id: 't_name',
+ // No actual SKILL.md on disk for this id → listSkills() won't have it.
+ system: 'A.custom', skill_id: 'definitely-not-installed-skill-id-xyz', trigger: 'read_file',
+ }));
+ await wait();
+
+ const r = await aggregateSkillMetrics({ sinceDays: 1 });
+ const row = findRow(r.rows, 'definitely-not-installed-skill-id-xyz', 'A.custom');
+ expect(row).not.toBeNull();
+ expect(row.display_name).toBe('definitely-not-installed-skill-id-xyz');
+ });
+});
diff --git a/test/main/features/skills.test.ts b/test/main/features/skills.test.ts
index 4161a19a..3b23499a 100644
--- a/test/main/features/skills.test.ts
+++ b/test/main/features/skills.test.ts
@@ -673,6 +673,23 @@ describe('skills › updateCustomSkill', () => {
expect(fs.existsSync(path.join(customSkillsDir(), 'beta'))).toBe(true);
});
+ it('supports two-phase name edits with skipRename before final rename', async () => {
+ writeCustomSkill('alpha', 'name: "alpha"\ndescription_en: "x"', 'body');
+ const s = await loadSkills();
+
+ const staged = await s.updateCustomSkill('alpha', { name: 'beta' }, { skipRename: true });
+ expect(staged?.id).toBe('alpha');
+ expect(fs.existsSync(path.join(customSkillsDir(), 'alpha'))).toBe(true);
+ expect(fs.existsSync(path.join(customSkillsDir(), 'beta'))).toBe(false);
+ expect(fs.readFileSync(path.join(customSkillsDir(), 'alpha', 'SKILL.md'), 'utf8'))
+ .toContain('name: "beta"');
+
+ const committed = await s.updateCustomSkill('alpha', { name: 'beta' });
+ expect(committed?.id).toBe('beta');
+ expect(fs.existsSync(path.join(customSkillsDir(), 'alpha'))).toBe(false);
+ expect(fs.existsSync(path.join(customSkillsDir(), 'beta'))).toBe(true);
+ });
+
it('returns null for missing skill', async () => {
const s = await loadSkills();
expect(await s.updateCustomSkill('ghost', { description: 'x' })).toBeNull();
diff --git a/test/main/util/transient-errors.test.ts b/test/main/util/transient-errors.test.ts
new file mode 100644
index 00000000..4b6e3aad
--- /dev/null
+++ b/test/main/util/transient-errors.test.ts
@@ -0,0 +1,50 @@
+import { describe, it, expect } from 'vitest';
+import { isTransientError } from '../../../src/main/util/transient-errors';
+
+// Pinned per CLAUDE.md §9 — text-classifier with set A (must match) +
+// set B (must NOT match). Mirrors the patterns formerly local to
+// plan_executor.ts:75 + now shared with expert_signals/turn_hooks.ts.
+
+describe('isTransientError — set A (network-class blips)', () => {
+ it.each([
+ 'fetch failed at provider',
+ 'undici terminated',
+ 'connect ECONNRESET 1.2.3.4:443',
+ 'ETIMEDOUT during read',
+ 'connect ECONNREFUSED',
+ 'getaddrinfo EAI_AGAIN',
+ 'socket hang up',
+ 'EPIPE',
+ 'network error',
+ 'Connection closed unexpectedly',
+ ])('matches transient pattern: %s', (msg) => {
+ expect(isTransientError(msg)).toBe(true);
+ });
+
+ it('case-insensitive', () => {
+ expect(isTransientError('Fetch Failed')).toBe(true);
+ expect(isTransientError('econnreset')).toBe(true);
+ });
+});
+
+describe('isTransientError — set B (permanent / non-network)', () => {
+ it.each([
+ 'agent specification missing',
+ 'parse failure: invalid JSON in tool output',
+ 'sandbox: path out of scope',
+ 'no model configured',
+ 'tool rejected: bad arguments',
+ 'permission denied',
+ 'aborted by user',
+ ])('does NOT match: %s', (msg) => {
+ expect(isTransientError(msg)).toBe(false);
+ });
+});
+
+describe('isTransientError — edge cases', () => {
+ it('empty / null / undefined → false', () => {
+ expect(isTransientError('')).toBe(false);
+ expect(isTransientError(null)).toBe(false);
+ expect(isTransientError(undefined)).toBe(false);
+ });
+});
diff --git a/test/renderer/conversation-bucket.test.ts b/test/renderer/conversation-bucket.test.ts
new file mode 100644
index 00000000..16ce946e
--- /dev/null
+++ b/test/renderer/conversation-bucket.test.ts
@@ -0,0 +1,92 @@
+// Pin sidebar conversation-list time bucketing. timeBucket is a pure helper
+// in conversation.js (CJS bridge per CLAUDE.md §9) that classifies an ISO
+// timestamp into today / yesterday / last7 / last30 / older against an
+// injected `now`. Boundary-case fixtures use a fixed `now` so DST + wall-
+// clock skew don't flake the suite.
+
+import { describe, it, expect } from 'vitest';
+// eslint-disable-next-line @typescript-eslint/no-var-requires
+const convBucket = require('../../src/renderer/modules/conv-bucket.js');
+const { timeBucket } = convBucket as {
+ timeBucket: (iso: string, now?: Date) => 'today' | 'yesterday' | 'last7' | 'last30' | 'older';
+};
+
+// 2026-05-15T14:30:00 local — anchor every fixture against this; today
+// starts at 2026-05-15T00:00:00 local.
+const NOW = new Date(2026, 4, 15, 14, 30, 0);
+const DAY = 24 * 60 * 60 * 1000;
+const todayStart = (() => { const d = new Date(NOW); d.setHours(0, 0, 0, 0); return d; })();
+function offsetFromTodayStart(ms: number): string {
+ return new Date(todayStart.getTime() + ms).toISOString();
+}
+
+describe('timeBucket — today', () => {
+ it('exactly local midnight today → today', () => {
+ expect(timeBucket(offsetFromTodayStart(0), NOW)).toBe('today');
+ });
+
+ it('current wall-clock instant → today', () => {
+ expect(timeBucket(NOW.toISOString(), NOW)).toBe('today');
+ });
+
+ it('one millisecond before midnight today → yesterday', () => {
+ expect(timeBucket(offsetFromTodayStart(-1), NOW)).toBe('yesterday');
+ });
+});
+
+describe('timeBucket — yesterday', () => {
+ it('exactly local midnight yesterday → yesterday', () => {
+ expect(timeBucket(offsetFromTodayStart(-DAY), NOW)).toBe('yesterday');
+ });
+
+ it('one millisecond before midnight yesterday → last7', () => {
+ expect(timeBucket(offsetFromTodayStart(-DAY - 1), NOW)).toBe('last7');
+ });
+});
+
+describe('timeBucket — last7', () => {
+ it('3 days ago → last7', () => {
+ expect(timeBucket(offsetFromTodayStart(-3 * DAY + 1), NOW)).toBe('last7');
+ });
+
+ it('exactly 7 days ago at midnight → last7 (boundary inclusive)', () => {
+ expect(timeBucket(offsetFromTodayStart(-7 * DAY), NOW)).toBe('last7');
+ });
+
+ it('one millisecond before 7-day boundary → last30', () => {
+ expect(timeBucket(offsetFromTodayStart(-7 * DAY - 1), NOW)).toBe('last30');
+ });
+});
+
+describe('timeBucket — last30', () => {
+ it('15 days ago → last30', () => {
+ expect(timeBucket(offsetFromTodayStart(-15 * DAY), NOW)).toBe('last30');
+ });
+
+ it('exactly 30 days ago at midnight → last30 (boundary inclusive)', () => {
+ expect(timeBucket(offsetFromTodayStart(-30 * DAY), NOW)).toBe('last30');
+ });
+
+ it('one millisecond before 30-day boundary → older', () => {
+ expect(timeBucket(offsetFromTodayStart(-30 * DAY - 1), NOW)).toBe('older');
+ });
+});
+
+describe('timeBucket — older + degenerate inputs', () => {
+ it('60 days ago → older', () => {
+ expect(timeBucket(offsetFromTodayStart(-60 * DAY), NOW)).toBe('older');
+ });
+
+ it('empty iso → older (missing timestamp gets the safest bucket)', () => {
+ expect(timeBucket('', NOW)).toBe('older');
+ });
+
+ it('null-ish iso → older', () => {
+ expect(timeBucket(null as unknown as string, NOW)).toBe('older');
+ expect(timeBucket(undefined as unknown as string, NOW)).toBe('older');
+ });
+
+ it('malformed iso → older (no NaN leak)', () => {
+ expect(timeBucket('not-a-date', NOW)).toBe('older');
+ });
+});