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:新增/export命令保存历史记录
openJiuwen-bot4c494e035588
diff --git a/jiuwenclaw/agents/harness/common/tools/command_tools.py b/jiuwenclaw/agents/harness/common/tools/command_tools.pyindex 81328c2009..a80d624b3d 100644--- a/jiuwenclaw/agents/harness/common/tools/command_tools.py+++ b/jiuwenclaw/agents/harness/common/tools/command_tools.py@@ -158,6 +158,19 @@ def _resolve_execution_plan(command: str, shell_type: str) -> tuple[list[str] |raise RuntimeError(f"Unsupported shell_type: {normalized}")+def _resolve_encoding(resolved_shell: str) -> str:+ """Choose subprocess text encoding based on the resolved shell type.++ - bash / sh on Windows (e.g. Git Bash / MSYS2) output UTF-8 by default.+ - cmd uses the system code page (typically CP936/GBK on Chinese Windows).+ - PowerShell also uses the system code page by default; safest to use+ the system code page and rely on ``errors='replace'`` for edge cases.+ """+ if os.name == "nt" and resolved_shell in ("bash", "sh"):+ return "utf-8"+ return locale.getpreferredencoding(False) or "utf-8"++def _run_command_sync(command: str,timeout_seconds: int,@@ -165,9 +178,8 @@ def _run_command_sync(shell_type: str,) -> tuple[subprocess.CompletedProcess[str], str]:plan, use_shell, resolved_shell = _resolve_execution_plan(command, shell_type)- # Windows 下 cmd 的输出通常是系统代码页(常见 CP936/GBK),- # 这里不要强行按 UTF-8 解码,否则会出现中文乱码(如 .lnk 名称)。- encoding = locale.getpreferredencoding(False) or "utf-8"+ # bash/sh on Windows output UTF-8; cmd/PowerShell use system code page.+ encoding = _resolve_encoding(resolved_shell)result = subprocess.run(plan,shell=use_shell,diff --git a/jiuwenclaw/channels/tui/frontend/src/app-state.ts b/jiuwenclaw/channels/tui/frontend/src/app-state.tsindex 8d49a3cd54..a99118dcd4 100644--- a/jiuwenclaw/channels/tui/frontend/src/app-state.ts+++ b/jiuwenclaw/channels/tui/frontend/src/app-state.ts@@ -874,7 +874,40 @@ readonly request = async <T = Record<string, unknown>>(return a.originalIndex - b.originalIndex;}).map((item) => item.entry);- this.entries = [...coalesceAssistantHistoryEntries(ordered)];++ const restored = coalesceAssistantHistoryEntries(ordered);++ // Merge: keep existing frontend entries that aren't in the restored set,+ // so that live entries accumulated during streaming aren't lost on reconnection.+ const restoredById = new Map<string, HistoryItem>();+ for (const entry of restored) {+ restoredById.set(entry.id, entry);+ }++ // Build merged set: restored entries + frontend-only entries (not in restored).+ // For entries present in both, prefer the restored version (server-authoritative).+ const merged: HistoryItem[] = [];+ for (const entry of restored) {+ merged.push(entry);+ }+ for (const entry of this.entries) {+ if (!restoredById.has(entry.id)) {+ merged.push(entry);+ }+ }++ // Sort merged entries by timestamp for consistent display order.+ const sorted = merged+ .map((entry, originalIndex) => ({ entry, originalIndex, ts: Date.parse(entry.at) }))+ .sort((a, b) => {+ const ta = Number.isNaN(a.ts) ? 0 : a.ts;+ const tb = Number.isNaN(b.ts) ? 0 : b.ts;+ if (ta !== tb) return ta - tb;+ return a.originalIndex - b.originalIndex;+ })+ .map((item) => item.entry);++ this.entries = [...sorted];this.rebuildToolExecutionState();this.emitChange();}diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/export.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/export.tsnew file mode 100644index 0000000000..b3c285fc1f--- /dev/null+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/export.ts@@ -0,0 +1,174 @@+import { writeFileSync } from "node:fs";+import { join } from "node:path";+import { copyToClipboard } from "../clipboard.js";+import { addError, addInfo } from "../helpers.js";+import { CommandKind, type SlashCommand } from "../types.js";+import type { HistoryItem, ToolCallDisplay } from "../../types.js";++function formatTimestamp(date: Date): string {+ const year = date.getFullYear();+ const month = String(date.getMonth() + 1).padStart(2, "0");+ const day = String(date.getDate()).padStart(2, "0");+ const hours = String(date.getHours()).padStart(2, "0");+ const minutes = String(date.getMinutes()).padStart(2, "0");+ const seconds = String(date.getSeconds()).padStart(2, "0");+ return `${year}-${month}-${day}-${hours}${minutes}${seconds}`;+}++function extractFirstPrompt(entries: HistoryItem[]): string {+ const firstUserEntry = entries.find((e) => e.kind === "user");+ if (!firstUserEntry || firstUserEntry.kind !== "user") return "";+ const text = firstUserEntry.content.trim().split("\n")[0] || "";+ return text.length > 50 ? text.substring(0, 49) + "…" : text;+}++function sanitizeFilename(text: string): string {+ return text+ .toLowerCase()+ .replace(/[^a-z0-9\s一-鿿-]/g, "")+ .replace(/\s+/g, "-")+ .replace(/-+/g, "-")+ .replace(/^-|-$/g, "");+}++function renderEntriesToPlainText(entries: HistoryItem[]): string {+ const lines: string[] = [];++ for (const entry of entries) {+ const time = entry.at ? new Date(entry.at).toLocaleString() : "";++ switch (entry.kind) {+ case "user":+ lines.push(`[User] ${time}`);+ lines.push(entry.content);+ lines.push("");+ break;++ case "assistant":+ lines.push(`[Assistant] ${time}`);+ lines.push(entry.content);+ lines.push("");+ break;++ case "thinking":+ lines.push(`[Thinking] ${time}`);+ lines.push(entry.content);+ lines.push("");+ break;++ case "tool_group": {+ const toolNames = entry.tools.map((t: ToolCallDisplay) => t.name).join(", ");+ lines.push(`[Tools] ${time} — ${toolNames}`);+ for (const tool of entry.tools) {+ lines.push(` ${tool.name}${tool.summary ? `: ${tool.summary}` : ""}`);+ if (tool.result) {+ const truncated =+ tool.result.length > 500 ? tool.result.substring(0, 499) + "…" : tool.result;+ lines.push(` Result: ${truncated}`);+ }+ }+ lines.push("");+ break;+ }++ case "collapsed_tool_group": {+ const hint = entry.latestHint || "";+ const counts = entry.counts;+ const countStr = Object.entries(counts)+ .filter(([, v]) => v > 0)+ .map(([k, v]) => `${v} ${k}`)+ .join(", ");+ lines.push(`[Tools] ${time} — ${hint || countStr}`);+ lines.push("");+ break;+ }++ case "system":+ lines.push(`[System] ${time}`);+ lines.push(entry.content);+ lines.push("");+ break;++ case "error":+ lines.push(`[Error] ${time}`);+ lines.push(entry.content);+ lines.push("");+ break;++ case "info":+ lines.push(`[Info] ${time}`);+ lines.push(entry.content);+ lines.push("");+ break;++ case "diff":+ lines.push(`[Diff] ${time}`);+ for (const turn of entry.meta.turns) {+ lines.push(` Turn ${turn.turnIndex}: ${turn.userPromptPreview}`);+ for (const [, file] of Object.entries(turn.files)) {+ lines.push(+ ` ${file.filePath} (+${file.linesAdded}/-${file.linesRemoved}${file.isNewFile ? " [new]" : ""})`,+ );+ }+ }+ lines.push("");+ break;+ }+ }++ return lines.join("\n");+}++export function createExportCommand(): SlashCommand {+ return {+ name: "export",+ description: "Export current conversation to a file or clipboard",+ usage: "/export [filename]",+ example: "/export my-chat.txt",+ kind: CommandKind.BUILT_IN,+ takesArgs: true,+ action: (ctx, args) => {+ const content = renderEntriesToPlainText(ctx.entries);+ const arg = args.trim();++ if (!arg) {+ if (!copyToClipboard(content)) {+ ctx.addItem(+ addError(ctx.sessionId, "Clipboard unavailable — specify a filename to export to file"),+ );+ return;+ }+ ctx.addItem(addInfo(ctx.sessionId, "Conversation exported to clipboard", "e"));+ return;+ }++ const filename = arg.endsWith(".txt") ? arg : arg.replace(/\.[^.]+$/, "") + ".txt";+ const workspaceDir = ctx.getWorkspaceDir() || process.cwd();+ const filepath = join(workspaceDir, filename);++ try {+ writeFileSync(filepath, content, { encoding: "utf-8" });+ ctx.addItem(addInfo(ctx.sessionId, `Conversation exported to: ${filepath}`, "e"));+ } catch (error) {+ const message = error instanceof Error ? error.message : "Unknown error";+ ctx.addItem(addError(ctx.sessionId, `Failed to export: ${message}`));+ }+ },+ completion: (ctx, partial) => {+ const firstPrompt = extractFirstPrompt(ctx.entries);+ const timestamp = formatTimestamp(new Date());+ const defaults: string[] = [];++ if (firstPrompt) {+ const sanitized = sanitizeFilename(firstPrompt);+ defaults.push(`${timestamp}-${sanitized}.txt`);+ }+ defaults.push(`conversation-${timestamp}.txt`);++ if (partial) {+ return defaults.filter((d) => d.startsWith(partial));+ }+ return defaults;+ },+ };+}\ No newline at end of filediff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/clipboard.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/clipboard.tsindex 9f3c7b55e2..a36cab9c4a 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/clipboard.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/clipboard.ts@@ -9,6 +9,21 @@ function tryClipboard(command: string, args: string[], text: string): boolean {}}+function tryClipboardUtf8OnWindows(text: string): boolean {+ try {+ // PowerShell handles UTF-8 correctly on Windows, unlike the `clip` command+ // which silently re-encodes input as ANSI (GBK), breaking Chinese characters.+ const script = `$null = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Set-Content -Path (Join-Path $env:TEMP "clip-tmp.txt") -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("${Buffer.from(text, "utf-8").toString("base64")}"))) -Encoding UTF8; Get-Content -Path (Join-Path $env:TEMP "clip-tmp.txt") -Encoding UTF8 -Raw | Set-Clipboard; Remove-Item (Join-Path $env:TEMP "clip-tmp.txt") -Force`;+ execFileSync("powershell", ["-NoProfile", "-NonInteractive", "-Command", script], {+ stdio: ["pipe", "ignore", "ignore"],+ timeout: 5000,+ });+ return true;+ } catch {+ return false;+ }+}+export function copyToClipboard(text: string): boolean {if (!text) return false;@@ -17,7 +32,7 @@ export function copyToClipboard(text: string): boolean {}if (process.platform === "win32") {- return tryClipboard("clip", [], text);+ return tryClipboardUtf8OnWindows(text);}if (process.env.WAYLAND_DISPLAY && tryClipboard("wl-copy", [], text)) {diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.tsindex 5f5aa8809c..35b72249bd 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts@@ -6,6 +6,7 @@ import { createCompactCommand } from "./builtins/compact.js";import { createConfigCommand } from "./builtins/config.js";import { createCopyCommand } from "./builtins/copy.js";import { createDiffCommand } from "./builtins/diff.js";+import { createExportCommand } from "./builtins/export.js";import {createEvolveCommand,createEvolveListCommand,@@ -40,6 +41,7 @@ export function createBuiltinCommands(): SlashCommand[] {createConfigCommand(),createCopyCommand(),createDiffCommand(),+ createExportCommand(),createEvolveCommand(),createEvolveListCommand(),createEvolveRebuildCommand(),