JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat:/status命令查看基本状态
openJiuwen-botd7b0294bf6b3
diff --git a/jiuwenclaw/channels/tui/frontend/src/app-state.ts b/jiuwenclaw/channels/tui/frontend/src/app-state.tsindex a99118dcd4..ff768657fe 100644--- a/jiuwenclaw/channels/tui/frontend/src/app-state.ts+++ b/jiuwenclaw/channels/tui/frontend/src/app-state.ts@@ -55,6 +55,20 @@ import {clearTrustedDirs,} from "./core/tui-trusted-dirs-store.js";+export interface ModelUsageEntry {+ model: string;+ input_tokens: number;+ output_tokens: number;+ total_tokens: number;+}++export interface SessionUsageSummary {+ total_input_tokens: number;+ total_output_tokens: number;+ total_tokens: number;+ byModel: ModelUsageEntry[];+}+export interface AppSnapshot {connectionStatus: ConnectionStatus;sessionId: string;@@ -134,6 +148,7 @@ export class CliPiAppState {private historyPageDoneResolvers = new Map<number, () => void>();private unlistenStatus: (() => void) | null = null;private unlistenFrames: (() => void) | null = null;+ private usageByModel = new Map<string, ModelUsageEntry>();private modelInfo: { provider: string; model: string; version: string } = {provider: "",model: "",@@ -229,6 +244,18 @@ export class CliPiAppState {resolver();}},+ appendUsageSummary: (usage, model) => {+ const key = model || "unknown";+ const existing = this.usageByModel.get(key);+ const u = usage as Record<string, unknown>;+ const entry: ModelUsageEntry = {+ model: key,+ input_tokens: (existing?.input_tokens ?? 0) + (typeof u.input_tokens === "number" ? u.input_tokens : 0),+ output_tokens: (existing?.output_tokens ?? 0) + (typeof u.output_tokens === "number" ? u.output_tokens : 0),+ total_tokens: (existing?.total_tokens ?? 0) + (typeof u.total_tokens === "number" ? u.total_tokens : 0),+ };+ this.usageByModel.set(key, entry);+ },};constructor(@@ -421,6 +448,18 @@ export class CliPiAppState {clearTrustedDirs: clearTrustedDirs,getWorkspaceDir: () => getTrustedDirs()[0] || process.cwd(),enterConfigEditor: undefined, // AppScreen injects the real handler when executing slash commands.+ enterStatusView: undefined,+ getUsageSummary: () => this.getUsageSummary(),+ };+ }++ getUsageSummary(): SessionUsageSummary {+ const entries = Array.from(this.usageByModel.values());+ return {+ total_input_tokens: entries.reduce((s, e) => s + e.input_tokens, 0),+ total_output_tokens: entries.reduce((s, e) => s + e.output_tokens, 0),+ total_tokens: entries.reduce((s, e) => s + e.total_tokens, 0),+ byModel: entries,};}@@ -461,6 +500,7 @@ readonly request = async <T = Record<string, unknown>>(readonly updateSession = (newId: string): void => {this.sessionId = newId;+ this.usageByModel.clear();this.emitChange();};diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/status.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/status.tsnew file mode 100644index 0000000000..9c2201cbf1--- /dev/null+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/status.ts@@ -0,0 +1,161 @@+import { addError, addInfo } from "../helpers.js";+import { CommandKind, type SlashCommand } from "../types.js";+import type { SessionUsageSummary } from "../../../app-state.js";+import type { ConfigItemSchema } from "./config.js";++export type StatusPayload = {+ version: string;+ session_id: string;+ cwd: string;+ model: string;+ provider: string;+ api_base: string;+ connection_status: string;+ mcp_servers: { name: string; enabled: boolean; transport: string }[];+ config_path: string;+ settings_sources: string[];+};++function showOverview(ctx: import("../types.js").CommandContext, payload: StatusPayload): void {+ ctx.addItem(+ addInfo(ctx.sessionId, "Core identity", "i", {+ view: "kv",+ title: "Status — Core",+ items: [+ { label: "version", value: payload.version || "unknown" },+ { label: "session", value: payload.session_id || ctx.sessionId },+ { label: "name", value: ctx.sessionTitle || "/rename to add a name" },+ { label: "cwd", value: payload.cwd || "unknown" },+ { label: "mode", value: ctx.mode },+ ],+ }),+ );++ ctx.addItem(+ addInfo(ctx.sessionId, "Model & API", "i", {+ view: "kv",+ title: "Status — Model & API",+ items: [+ { label: "model", value: payload.model || "unknown" },+ { label: "provider", value: payload.provider || "unknown" },+ { label: "api_base", value: payload.api_base || "unknown" },+ { label: "connection", value: payload.connection_status || ctx.connectionStatus },+ ],+ }),+ );++ const mcpItems = (payload.mcp_servers ?? []).map((srv) => ({+ label: srv.name,+ value: `${srv.transport} | ${srv.enabled ? "enabled" : "disabled"}`,+ }));+ ctx.addItem(+ addInfo(ctx.sessionId, `MCP servers (${mcpItems.length})`, "i", {+ view: "kv",+ title: "Status — MCP",+ items: mcpItems.length > 0 ? mcpItems : [{ label: "—", value: "No MCP servers configured" }],+ }),+ );++ const sourceItems = (payload.settings_sources ?? []).map((s) => ({+ label: "source",+ value: s,+ }));+ ctx.addItem(+ addInfo(ctx.sessionId, "Config sources", "i", {+ view: "kv",+ title: "Status — Config",+ items: [+ { label: "config_path", value: payload.config_path || "unknown" },+ ...sourceItems,+ ],+ }),+ );+}++function showUsage(ctx: import("../types.js").CommandContext, summary: SessionUsageSummary): void {+ const fmt = (n: number) => n.toLocaleString("en-US");++ const items = [+ { label: "input_tokens", value: fmt(summary.total_input_tokens) },+ { label: "output_tokens", value: fmt(summary.total_output_tokens) },+ { label: "total_tokens", value: fmt(summary.total_tokens) },+ ];++ if (summary.byModel.length > 0) {+ for (const entry of summary.byModel) {+ items.push(+ { label: `model: ${entry.model}`, value: `${fmt(entry.total_tokens)} tokens` },+ { label: ` input`, value: fmt(entry.input_tokens) },+ { label: ` output`, value: fmt(entry.output_tokens) },+ );+ }+ }++ ctx.addItem(+ addInfo(ctx.sessionId, "Session usage", "u", {+ view: "kv",+ title: "Status — Usage",+ items,+ }),+ );+}++export function createStatusCommand(): SlashCommand {+ return {+ name: "status",+ description: "Show jiuwenclaw status (overview, usage, config)",+ usage: "/status [overview|usage|config]",+ example: "/status",+ kind: CommandKind.BUILT_IN,+ takesArgs: true,+ action: async (ctx, args) => {+ // If interactive StatusView is available, delegate to it+ if (ctx.enterStatusView) {+ const sub = args.trim().toLowerCase();+ const tab: "status" | "usage" | "config" | undefined =+ sub === "usage" ? "usage" :+ sub === "config" ? "config" :+ undefined;+ ctx.enterStatusView(tab);+ return;+ }++ const sub = args.trim().toLowerCase();++ try {+ if (sub === "usage") {+ const summary = ctx.getUsageSummary();+ showUsage(ctx, summary);+ return;+ }++ if (sub === "config") {+ let configPayload: Record<string, unknown> & { schema?: ConfigItemSchema[] };+ try {+ configPayload = await ctx.request<Record<string, unknown> & { schema?: ConfigItemSchema[] }>(+ "config.get",+ {},+ );+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ ctx.addItem(addError(ctx.sessionId, `config failed: ${message}`));+ return;+ }+ if (ctx.enterConfigEditor) {+ ctx.enterConfigEditor(undefined, configPayload);+ } else {+ ctx.addItem(addError(ctx.sessionId, "Interactive editor not available in this mode"));+ }+ return;+ }++ // Default: overview (also handles "overview" subcommand)+ const payload = await ctx.request<StatusPayload>("command.status", {});+ showOverview(ctx, payload);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ ctx.addItem(addError(ctx.sessionId, `status failed: ${message}`));+ }+ },+ };+}\ No newline at end of filediff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.tsindex 35b72249bd..237f493557 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts@@ -26,6 +26,7 @@ import { createPlanCommand } from "./builtins/plan.js";import { createResumeCommand } from "./builtins/resume.js";import { createRenameCommand } from "./builtins/rename.js";import { createSessionCommand } from "./builtins/session.js";+import { createStatusCommand } from "./builtins/status.js";import { createSkillsCommand } from "./builtins/skills.js";import { createTeamSkillsCommand } from "./builtins/teamskills.js";import { createThemeCommand } from "./builtins/theme.js";@@ -56,6 +57,7 @@ export function createBuiltinCommands(): SlashCommand[] {createRenameCommand(),createSessionCommand(),createSkillsCommand(),+ createStatusCommand(),createTeamSkillsCommand(),createThemeCommand(),createWorkspaceCommand(),diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/types.tsindex 3a4c42eca1..d1473a5f2f 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts@@ -3,9 +3,12 @@ import type { AccentColorName, ThemeName } from "../../ui/theme.js";import type { PendingQuestionItem, UserAnswer } from "../event-handlers.js";import type { FileAttachment } from "../protocol.js";import type { ConfigItemSchema } from "./builtins/config.js";+import type { SessionUsageSummary } from "../../app-state.js";export type ConnectionStatus = "idle" | "connecting" | "connected" | "reconnecting" | "auth_failed";+export type StatusViewTab = "status" | "usage" | "config";+export enum CommandKind {BUILT_IN = "built-in",}@@ -69,10 +72,12 @@ export interface CommandContext {clearTrustedDirs: () => void;// Workspace directory (current working directory)getWorkspaceDir: () => string | undefined;+ getUsageSummary: () => SessionUsageSummary;enterConfigEditor?: (focusKey?: string,configPayload?: Record<string, unknown> & { schema?: ConfigItemSchema[] },) => void;+ enterStatusView?: (tab?: StatusViewTab) => void;openInEditor?: (filePath: string) => void;}diff --git a/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.ts b/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.tsindex 61c15bb159..7d7915ba94 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.ts@@ -96,6 +96,8 @@ export interface AppEventDelegate {reportHistoryPageMeta(meta: { pageIdx?: number; totalPages?: number }): void;/** 某一页 history.get 流已结束(收到 `status: done` 帧),由 app-state 决定是否继续拉下一页。 */notifyHistoryPageDone(pageIdx: number): void;+ /** 累加 chat.usage_summary 事件的 token/cost 数据(按 model 分桶)。 */+ appendUsageSummary(usage: Record<string, unknown>, model?: string): void;}function _handleSwitchModeToolResult(@@ -890,6 +892,15 @@ export function handleIncomingFrame(delegate: AppEventDelegate, frame: EventFramcase "team.message":return handleTeamMessageEvent(delegate, payload);+ case "chat.usage_summary":+ delegate.appendUsageSummary(+ typeof payload.usage === "object" && payload.usage !== null+ ? (payload.usage as Record<string, unknown>)+ : {},+ typeof payload.model === "string" ? payload.model : undefined,+ );+ return true;+default:return connectionChanged;}diff --git a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.tsindex ec028bd5ea..2e19f262a2 100644--- a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts@@ -87,6 +87,18 @@ type ConfigEditorState = {list: SelectList;};+type StatusViewTab = "status" | "usage" | "config";++type StatusViewPhase = "tab_view" | "config_editor";++type StatusViewState = {+ phase: StatusViewPhase;+ tab: StatusViewTab;+ list: SelectList;+ statusPayload: import("../core/commands/builtins/status.js").StatusPayload | null;+ configPayload: (Record<string, unknown> & { schema?: ConfigItemSchema[] }) | null;+};+const IMAGE_MIME_TYPES: Record<string, string> = {".png": "image/png",".jpg": "image/jpeg",@@ -348,6 +360,7 @@ export class AppScreen implements Component, Focusable {private modelList: ModelListState | null = null;private themeList: ThemeListState | null = null;private configEditorState: ConfigEditorState | null = null;+ private statusViewState: StatusViewState | null = null;private startupPromptList: SelectList | null = null;private showTodos = true;private showTeamPanel = false;@@ -544,6 +557,67 @@ export class AppScreen implements Component, Focusable {return;}+ if (!snapshot.pendingQuestion && this.statusViewState !== null) {+ if (this.statusViewState.phase === "config_editor") {+ if (this.configEditorState?.phase === "input_value") {+ if (matchesKey(data, "escape")) {+ if (this.configEditorState.selectedGroup) {+ const groupSchemas = this.configEditorState.schemaList.filter(+ (s) => s.group === this.configEditorState!.selectedGroup,+ );+ this.showConfigGroupItems(+ this.configEditorState.selectedGroup,+ groupSchemas,+ this.configEditorState.currentValues,+ );+ } else {+ this.configEditorState = null;+ this.statusViewState = {+ ...this.statusViewState,+ phase: "tab_view",+ tab: "config",+ list: this.buildStatusViewTabState("config", this.statusViewState.statusPayload, this.statusViewState.configPayload),+ };+ }+ this.tui.requestRender();+ return;+ }+ if (matchesKey(data, "return")) {+ const text = this.editor.getText().trim();+ if (text && this.configEditorState.selectedKey) {+ const key = this.configEditorState.selectedKey;+ const schema = this.configEditorState.schemaList.find((s) => s.key === key);+ if (schema) {+ void this.applyConfigEditorSet(key, text, schema, this.configEditorState.currentValues);+ this.editor.setText("");+ }+ }+ return;+ }+ this.editor.handleInput(data);+ } else if (this.configEditorState) {+ this.configEditorState.list.handleInput(data);+ }+ this.tui.requestRender();+ return;+ }+ if (matchesKey(data, "escape")) {+ this.closeStatusView();+ return;+ }+ if (matchesKey(data, "left")) {+ this.switchStatusViewTab(-1);+ return;+ }+ if (matchesKey(data, "right")) {+ this.switchStatusViewTab(1);+ return;+ }+ this.statusViewState.list.handleInput(data);+ this.tui.requestRender();+ return;+ }+if (!snapshot.pendingQuestion && this.configEditorState !== null) {if (this.configEditorState.phase === "input_value") {// Handle Esc to cancel input and go back to group selection@@ -672,7 +746,8 @@ export class AppScreen implements Component, Focusable {const composerPreviewLines: string[] = [];const questionLines = [...this.buildStartupPromptLines(width),- ...this.buildConfigEditorLines(width),+ ...this.buildStatusViewLines(width),+ ...(!this.statusViewState ? this.buildConfigEditorLines(width) : []),...this.buildResumeSessionListLines(width),...this.buildModelListLines(width),...this.buildThemeListLines(width),@@ -771,6 +846,16 @@ export class AppScreen implements Component, Focusable {await this.openModelList();return;}+ if (/^\/status(?:\s+\S*)?\s*$/.test(text)) {+ this.editor.addToHistory(text);+ this.editor.setText("");+ this.state.addItem(addCommandEcho(snapshot.sessionId, text));+ const subMatch = text.match(/^\/status\s+(\S+)/);+ const tab: StatusViewTab | undefined =+ subMatch?.[1] === "usage" ? "usage" :+ subMatch?.[1] === "config" ? "config" :+ undefined;+ await this.openStatusView(tab);if (/^\/theme\s*$/.test(text)) {this.editor.addToHistory(text);this.editor.setText("");@@ -1267,8 +1352,16 @@ export class AppScreen implements Component, Focusable {this.showConfigGroupItems(item.value, groups[item.value], currentValues);};list.onCancel = () => {- this.configEditorState = null;- this.tui.requestRender();+ if (this.statusViewState) {+ this.statusViewState.phase = "tab_view";+ this.statusViewState.tab = "config";+ this.rebuildStatusViewTabList();+ this.configEditorState = null;+ this.tui.requestRender();+ } else {+ this.configEditorState = null;+ this.tui.requestRender();+ }};this.configEditorState = {phase: "select_group",@@ -1315,7 +1408,15 @@ export class AppScreen implements Component, Focusable {this.handleConfigItemSelection(schema, currentValues);};list.onCancel = () => {- this.showConfigGroupSelector(this.configEditorState!.schemaList, currentValues);+ if (this.statusViewState) {+ this.statusViewState.phase = "tab_view";+ this.statusViewState.tab = "config";+ this.rebuildStatusViewTabList();+ this.configEditorState = null;+ this.tui.requestRender();+ } else {+ this.showConfigGroupSelector(this.configEditorState!.schemaList, currentValues);+ }};this.configEditorState = {phase: "select_item",@@ -1378,6 +1479,12 @@ export class AppScreen implements Component, Focusable {(s) => s.group === this.configEditorState!.selectedGroup,);this.showConfigGroupItems(this.configEditorState.selectedGroup, groupSchemas, currentValues);+ } else if (this.statusViewState) {+ this.statusViewState.phase = "tab_view";+ this.statusViewState.tab = "config";+ this.rebuildStatusViewTabList();+ this.configEditorState = null;+ this.tui.requestRender();} else {this.configEditorState = null;this.tui.requestRender();@@ -1414,17 +1521,273 @@ export class AppScreen implements Component, Focusable {const message = error instanceof Error ? error.message : String(error);this.state.addItem(addError(this.state.getSnapshot().sessionId, `config.set failed: ${message}`));}- if (this.configEditorState?.selectedGroup) {- const groupSchemas = this.configEditorState.schemaList.filter(- (s) => s.group === this.configEditorState!.selectedGroup,- );- this.showConfigGroupItems(this.configEditorState.selectedGroup, groupSchemas, currentValues);+ if (this.statusViewState) {+ // Return to config tab in StatusView instead of closing entirely+ this.statusViewState.phase = "tab_view";+ this.statusViewState.tab = "config";+ this.rebuildStatusViewTabList();+ this.configEditorState = null;+ this.tui.requestRender();} else {this.configEditorState = null;this.tui.requestRender();}}+ // ──────────────────────────── StatusView ────────────────────────────++ private async openStatusView(tab?: StatusViewTab): Promise<void> {+ const initialTab: StatusViewTab = tab ?? "status";++ // Fetch status payload+ let statusPayload: import("../core/commands/builtins/status.js").StatusPayload | null = null;+ try {+ statusPayload = await this.state.request<import("../core/commands/builtins/status.js").StatusPayload>(+ "command.status",+ {},+ );+ } catch {+ // proceed with null — tab will show placeholder+ }++ // Fetch config payload (needed for Config tab)+ let configPayload: (Record<string, unknown> & { schema?: ConfigItemSchema[] }) | null = null;+ try {+ configPayload = await this.state.request<Record<string, unknown> & { schema?: ConfigItemSchema[] }>(+ "config.get",+ {},+ );+ } catch {+ // proceed with null+ }++ this.statusViewState = {+ phase: "tab_view",+ tab: initialTab,+ list: this.buildStatusViewTabState(initialTab, statusPayload, configPayload),+ statusPayload,+ configPayload,+ };+ this.tui.requestRender();+ }++ private buildStatusViewTabState(+ tab: StatusViewTab,+ statusPayload: import("../core/commands/builtins/status.js").StatusPayload | null,+ configPayload: (Record<string, unknown> & { schema?: ConfigItemSchema[] }) | null,+ ): SelectList {+ const items: SelectItem[] =+ tab === "status"+ ? this.buildStatusTabItems(statusPayload)+ : tab === "usage"+ ? this.buildUsageTabItems()+ : this.buildConfigTabItems(configPayload);++ const list = new SelectList(items, Math.min(Math.max(items.length, 1), 10), selectListTheme, {+ minPrimaryColumnWidth: 20,+ maxPrimaryColumnWidth: 50,+ });+ list.onSelect = (item) => {+ if (tab === "config" && item.value !== "__display__") {+ this.transitionToConfigEditor(item.value);+ }+ };+ list.onCancel = () => {+ this.closeStatusView();+ };+ return list;+ }++ private buildStatusTabItems(+ payload: import("../core/commands/builtins/status.js").StatusPayload | null,+ ): SelectItem[] {+ if (!payload) {+ return [{ value: "__display__", label: "Failed to load status data", description: "" }];+ }+ const snapshot = this.state.getSnapshot();+ const items: SelectItem[] = [+ { value: "__display__", label: `version: ${payload.version || "unknown"}`, description: "" },+ { value: "__display__", label: `session: ${payload.session_id || snapshot.sessionId}`, description: "" },+ { value: "__display__", label: `name: ${snapshot.sessionTitle || "/rename to add a name"}`, description: "" },+ { value: "__display__", label: `cwd: ${payload.cwd || "unknown"}`, description: "" },+ { value: "__display__", label: `mode: ${snapshot.mode}`, description: "" },+ { value: "__display__", label: `model: ${payload.model || "unknown"}`, description: "" },+ { value: "__display__", label: `provider: ${payload.provider || "unknown"}`, description: "" },+ { value: "__display__", label: `api_base: ${payload.api_base || "unknown"}`, description: "" },+ { value: "__display__", label: `connection: ${payload.connection_status || snapshot.connectionStatus}`, description: "" },+ ];++ const mcpServers = payload.mcp_servers ?? [];+ for (const srv of mcpServers) {+ items.push({+ value: "__display__",+ label: `mcp: ${srv.name}`,+ description: `${srv.transport} | ${srv.enabled ? "enabled" : "disabled"}`,+ });+ }++ const sources = payload.settings_sources ?? [];+ for (const s of sources) {+ items.push({ value: "__display__", label: `config_source: ${s}`, description: "" });+ }+ items.push({ value: "__display__", label: `config_path: ${payload.config_path || "unknown"}`, description: "" });++ return items;+ }++ private buildUsageTabItems(): SelectItem[] {+ const summary = this.state.getUsageSummary();+ const fmt = (n: number) => n.toLocaleString("en-US");+ const items: SelectItem[] = [+ { value: "__display__", label: `input_tokens: ${fmt(summary.total_input_tokens)}`, description: "" },+ { value: "__display__", label: `output_tokens: ${fmt(summary.total_output_tokens)}`, description: "" },+ { value: "__display__", label: `total_tokens: ${fmt(summary.total_tokens)}`, description: "" },+ ];++ for (const entry of summary.byModel) {+ items.push(+ { value: "__display__", label: `model: ${entry.model}`, description: `${fmt(entry.total_tokens)} tokens` },+ { value: "__display__", label: ` input`, description: fmt(entry.input_tokens) },+ { value: "__display__", label: ` output`, description: fmt(entry.output_tokens) },+ );+ }+ return items;+ }++ private buildConfigTabItems(+ configPayload: (Record<string, unknown> & { schema?: ConfigItemSchema[] }) | null,+ ): SelectItem[] {+ if (!configPayload?.schema?.length) {+ return [{ value: "__display__", label: "No config schema available", description: "" }];+ }+ const schemaList = configPayload.schema;+ const groups: Record<string, ConfigItemSchema[]> = {};+ for (const schema of schemaList) {+ const group = schema.group || "Other";+ if (!groups[group]) groups[group] = [];+ groups[group].push(schema);+ }++ const items: SelectItem[] = [];+ for (const groupName of Object.keys(groups)) {+ const groupSchemas = groups[groupName];+ items.push({ value: "__display__", label: groupName, description: `${groupSchemas.length} items` });+ for (const schema of groupSchemas) {+ const val = String(configPayload[schema.key] ?? "");+ const displayVal =+ schema.type === "toggle"+ ? val === "true" ? "Enabled" : "Disabled"+ : schema.sensitive+ ? val.length > 8 ? `${val.slice(0, 4)}****${val.slice(-4)}` : "***"+ : val || "(empty)";+ items.push({+ value: schema.key,+ label: ` ${schema.label}: ${displayVal}`,+ description: schema.description,+ });+ }+ }+ return items;+ }++ private renderTabBar(width: number): string[] {+ const tabs: StatusViewTab[] = ["status", "usage", "config"];+ const labels = tabs.map((t) => (t === this.statusViewState!.tab ? `[${t}]` : ` ${t} `));+ const barText = labels.join(" ");+ const activeIndex = tabs.indexOf(this.statusViewState!.tab);+ // Highlight active tab+ const parts: string[] = [];+ let pos = 0;+ for (let i = 0; i < labels.length; i++) {+ const seg = labels[i];+ if (i === activeIndex) {+ parts.push(palette.status.warning(seg));+ } else {+ parts.push(palette.text.dim(seg));+ }+ pos += seg.length;+ if (i < labels.length - 1) {+ parts.push(palette.text.dim(" "));+ pos += 2;+ }+ }+ const combined = parts.join("");+ return [padToWidth(combined, width)];+ }++ private getTabHint(tab: StatusViewTab): string {+ if (tab === "status" || tab === "usage") {+ return "←/→ switch tab · Esc close";+ }+ return "←/→ switch tab · Enter edit item · Esc close";+ }++ private buildStatusViewLines(width: number): string[] {+ if (!this.statusViewState) return [];+ if (this.statusViewState.phase === "config_editor") {+ return this.buildConfigEditorLines(width);+ }+ const lines: string[] = [];+ lines.push(...this.renderTabBar(width));+ lines.push(padToWidth(palette.status.warning("Status"), width));+ lines.push(...this.statusViewState.list.render(width));+ lines.push(padToWidth(palette.text.dim(this.getTabHint(this.statusViewState.tab)), width));+ return lines;+ }++ private switchStatusViewTab(direction: -1 | 1): void {+ if (!this.statusViewState || this.statusViewState.phase !== "tab_view") return;+ const tabs: StatusViewTab[] = ["status", "usage", "config"];+ const current = tabs.indexOf(this.statusViewState.tab);+ const next = (current + direction + tabs.length) % tabs.length;+ this.statusViewState.tab = tabs[next];+ this.rebuildStatusViewTabList();+ this.tui.requestRender();+ }++ private rebuildStatusViewTabList(): void {+ if (!this.statusViewState) return;+ this.statusViewState.list = this.buildStatusViewTabState(+ this.statusViewState.tab,+ this.statusViewState.statusPayload,+ this.statusViewState.configPayload,+ );+ this.tui.requestRender();+ }++ private transitionToConfigEditor(key: string): void {+ if (!this.statusViewState?.configPayload?.schema?.length) return;+ const schemaList = this.statusViewState.configPayload.schema;+ const schema = schemaList.find((s) => s.key === key);+ if (!schema) return;++ const currentValues: Record<string, string> = {};+ for (const s of schemaList) {+ currentValues[s.key] = String(this.statusViewState.configPayload?.[s.key] ?? "");+ }++ this.statusViewState.phase = "config_editor";+ this.configEditorState = {+ phase: "select_group",+ schemaList,+ currentValues,+ selectedGroup: null,+ selectedKey: null,+ list: new SelectList([], 1, selectListTheme),+ };++ // Navigate directly to the item's group or value+ const group = schema.group || "Other";+ const groupSchemas = schemaList.filter((s) => (s.group || "Other") === group);+ this.showConfigGroupItems(group, groupSchemas, currentValues);+ }++ private closeStatusView(): void {+ this.statusViewState = null;+ this.configEditorState = null;+ this.tui.requestRender();+ }+private syncComposerAttachmentsFromEditor(): void {if (this.syncingComposerInput) {return;diff --git a/jiuwenclaw/common/schema/message.py b/jiuwenclaw/common/schema/message.pyindex 227509ac5f..af706b7f06 100644--- a/jiuwenclaw/common/schema/message.py+++ b/jiuwenclaw/common/schema/message.py@@ -24,6 +24,7 @@ class ReqMethod(Enum):COMMAND_MODEL = "command.model"COMMAND_RESUME = "command.resume"COMMAND_SESSION = "command.session"+ COMMAND_STATUS = "command.status"CONFIG_GET = "config.get"CONFIG_SET = "config.set"diff --git a/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py b/jiuwenclaw/gateway/channel_manager/tui/tui_connect.pyindex c5923df9aa..e33f1235ed 100644--- a/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py+++ b/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py@@ -46,6 +46,7 @@ CLI_FORWARD_REQ_METHODS = frozenset("command.mcp","command.resume","command.session",+ "command.status","chat.send","chat.interrupt","chat.resume",@@ -98,6 +99,7 @@ CLI_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset("command.mcp","command.resume","command.session",+ "command.status","browser.start","skills.marketplace.list","skills.list",diff --git a/jiuwenclaw/server/agent_ws_server.py b/jiuwenclaw/server/agent_ws_server.pyindex 681f3b1fd0..d1e38649ee 100644--- a/jiuwenclaw/server/agent_ws_server.py+++ b/jiuwenclaw/server/agent_ws_server.py@@ -5,6 +5,7 @@from __future__ import annotationsimport asyncio+import datetime as _dtimport jsonimport loggingimport math@@ -28,11 +29,13 @@ from jiuwenclaw.common.e2a.wire_codec import (encode_json_parse_error_wire,)from jiuwenclaw.common.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk+from jiuwenclaw.common.version import __version__from jiuwenclaw.extensions.hook_event import AgentServerHookEventsfrom jiuwenclaw.agents.harness.common.plugins.rail_manager import get_rail_managerfrom jiuwenclaw.agents.harness.common.rails.permissions.permissions_persist import persist_cli_trusted_directoryfrom jiuwenclaw.extensions.hooks_context import AgentServerChatHookContextfrom jiuwenclaw.server.runtime.agent_manager import AgentManager, ACP_DEFAULT_CAPABILITIES+from jiuwenclaw.server.runtime.session.session_metadata import get_all_sessions_metadatafrom jiuwenclaw.agents.harness.common.rails.permissions.permissions_config_rpc import get_permissions_config_req_methodsfrom jiuwenclaw.common.config import (get_config,@@ -424,6 +427,9 @@ class AgentWebSocketServer:if request.req_method == ReqMethod.COMMAND_SESSION:await self._handle_command_session(ws, request, send_lock)return+ if request.req_method == ReqMethod.COMMAND_STATUS:+ await self._handle_command_status(ws, request, send_lock)+ returnif request.req_method == ReqMethod.BROWSER_START:await self._handle_browser_start(ws, request, send_lock)return@@ -1344,6 +1350,118 @@ class AgentWebSocketServer:async with send_lock:await ws.send(json.dumps(wire, ensure_ascii=False))+ async def _handle_command_status(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:+ try:+ params = request.params or {}+ action = str(params.get("action", "overview")).strip().lower()++ if action == "usage":+ sessions, total = get_all_sessions_metadata(limit=500, offset=0)+ messages_total = sum(s.get("message_count", 0) for s in sessions)+ model_counts: dict[str, int] = {}+ for s in sessions:+ mode = str(s.get("mode", "unknown"))+ model_counts[mode] = model_counts.get(mode, 0) + 1+ active_days_set: set[str] = set()+ longest_hours = 0.0+ for s in sessions:+ created = s.get("created_at", 0)+ last = s.get("last_message_at", 0)+ if created:+ try:+ day_str = _dt.datetime.fromtimestamp(+ created, tz=_dt.timezone.utc+ ).strftime("%Y-%m-%d")+ active_days_set.add(day_str)+ except Exception: # noqa: BLE001+ pass+ if created and last:+ longest_hours = max(longest_hours, (last - created) / 3600)++ models_used = [{"name": k, "count": v} for k, v in sorted(model_counts.items(), key=lambda x: -x[1])]+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={+ "sessions_total": total,+ "messages_total": messages_total,+ "models_used": models_used,+ "active_days": len(active_days_set),+ "longest_session_hours": round(longest_hours, 1),+ },+ )+ elif action == "config":+ config_path = str(get_config_file())+ settings_sources: list[str] = []+ config_dir = os.getenv("JIUWENCLAW_CONFIG_DIR")+ if config_dir:+ settings_sources.append(f"env:JIUWENCLAW_CONFIG_DIR={config_dir}")+ settings_sources.append(config_path)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={+ "config_path": config_path,+ "settings_sources": settings_sources,+ },+ )+ else:+ # overview (default)+ config = get_config()+ session_id = request.session_id or ""+ model_name = os.getenv("MODEL_NAME", config.get("model", ""))+ provider = os.getenv("MODEL_PROVIDER", str(config.get("model_provider", "")))+ api_base = os.getenv("API_BASE", str(config.get("api_base", "")))++ mcp_servers = get_mcp_servers()+ mcp_summary = [+ {+ "name": str(s.get("name", "unknown")),+ "enabled": bool(s.get("enabled", True)),+ "transport": str(s.get("transport", "unknown")),+ }+ for s in mcp_servers+ if isinstance(s, dict)+ ]++ config_path = str(get_config_file())+ settings_sources: list[str] = []+ config_dir = os.getenv("JIUWENCLAW_CONFIG_DIR")+ if config_dir:+ settings_sources.append(f"env:JIUWENCLAW_CONFIG_DIR={config_dir}")+ settings_sources.append(config_path)++ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={+ "version": __version__,+ "session_id": session_id,+ "cwd": os.getcwd(),+ "model": model_name,+ "provider": provider,+ "api_base": api_base,+ "connection_status": "connected",+ "mcp_servers": mcp_summary,+ "config_path": config_path,+ "settings_sources": settings_sources,+ },+ )+ except Exception as e: # noqa: BLE001+ logger.exception("[AgentWebSocketServer] command.status failed: %s", e)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": str(e)},+ )+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)+ async with send_lock:+ await ws.send(json.dumps(wire, ensure_ascii=False))+async def _handle_browser_start(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:"""启动浏览器并返回执行结果(returncode)。"""try:diff --git a/jiuwenclaw/server/runtime/agent_adapter/interface_deep.py b/jiuwenclaw/server/runtime/agent_adapter/interface_deep.pyindex 585a92c73c..d726549d62 100644--- a/jiuwenclaw/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenclaw/server/runtime/agent_adapter/interface_deep.py@@ -4203,6 +4203,7 @@ class JiuWenClawDeepAdapter:"event_type": "chat.usage_summary","session_id": session_id,"usage": summary,+ "model": self._resolve_model_name(),},is_complete=False,)