diff --git a/src/cli/commands/auth.ts b/src/cli/commands/auth.ts index 8a7cdd3..21a7590 100644 --- a/src/cli/commands/auth.ts +++ b/src/cli/commands/auth.ts @@ -18,6 +18,7 @@ import { createEkbClient } from "../../core/auth/ekb.js"; import { stringOption, booleanOption } from "../parser.js"; import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js"; import { prompt } from "../helpers.js"; +import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; export async function handleAuthCommand( @@ -68,6 +69,14 @@ async function handleLogin(parsed: CliParsedArgs, runtime: CliRuntime): Promise< const isSync = booleanOption(parsed.options, ["sync"]); const isInteractive = booleanOption(parsed.options, ["interactive", "i"]) || (!phone && !password && !isSms && !isSync); + if (isDryRun(parsed, runtime)) { + return mutationPreview(parsed, runtime, "登录并保存企业凭证", phone || (isSync ? "浏览器会话" : "交互式登录"), { + mode: isSync ? "browser-sync" : isSms ? "sms" : "password", + saveAll: true, + }); + } + requireMutationConfirmation(parsed, runtime, "登录并保存企业凭证", `hose-use auth login${phone ? ` --phone=${phone}` : ""} --yes`); + // 1. 浏览器同步 if (isSync) { const res = await fullBrowserSyncLogin({ saveAll: true }); @@ -230,6 +239,10 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise async function handleRefresh(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const accountId = stringOption(parsed.options, ["account", "a"]); + if (isDryRun(parsed, runtime)) { + return mutationPreview(parsed, runtime, "刷新账号下企业凭证", accountId || "当前账号", { saveAll: true }); + } + requireMutationConfirmation(parsed, runtime, "刷新账号下企业凭证", `hose-use auth refresh${accountId ? ` --account=${accountId}` : ""} --yes`); const res = await refreshAccountCorporations(accountId, { saveAll: true }); if (runtime.jsonMode) { @@ -253,6 +266,16 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise const ttl = stringOption(parsed.options, ["ttl"]); const expires = stringOption(parsed.options, ["expires", "days"]); + if (isDryRun(parsed, runtime)) { + return mutationPreview(parsed, runtime, "导入并保存企业凭证", corpId || "待解析企业", { + source: raw ? "captured-input" : "manual-input", + overwrite, + ttl: ttl || null, + expires: expires || null, + }); + } + requireMutationConfirmation(parsed, runtime, "导入并保存企业凭证", `hose-use auth ${parsed.action || "import"} --yes`); + if (!raw && !accessToken && process.stdin.isTTY) { raw = await prompt("请粘贴抓包文本 / cURL 命令行 / 协助免密 URL (直接回车则手动逐项输入): "); } @@ -370,6 +393,11 @@ async function handleSwitchAccount(parsed: CliParsedArgs, runtime: CliRuntime): return { stdout: "", stderr: "用法: hose-use auth switch-account \n", exitCode: 1 }; } + if (isDryRun(parsed, runtime)) { + return mutationPreview(parsed, runtime, "切换当前活跃账号", target, { activeAccountId: target }); + } + requireMutationConfirmation(parsed, runtime, "切换当前活跃账号", `hose-use auth switch-account ${target} --yes`); + const success = setActiveAccount(target); if (!success) { return { stdout: "", stderr: `未找到账号: ${target}\n`, exitCode: 1 }; diff --git a/src/cli/commands/config.ts b/src/cli/commands/config.ts index 2d9124f..75e3eb5 100644 --- a/src/cli/commands/config.ts +++ b/src/cli/commands/config.ts @@ -9,6 +9,7 @@ import { } from "../../core/config/loader.js"; import { booleanOption } from "../parser.js"; import { printJson, printKeyValue } from "../printer.js"; +import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; export async function handleConfigCommand( @@ -94,6 +95,10 @@ async function handleMode(parsed: CliParsedArgs, runtime: CliRuntime): Promise = { @@ -269,6 +270,11 @@ async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise return { stdout: "", stderr: "用法: hose-use corps switch <企业ID>\n", exitCode: 1 }; } + if (isDryRun(parsed, runtime)) { + return mutationPreview(parsed, runtime, "切换当前工作企业", corpId, { defaultCorpId: corpId }); + } + requireMutationConfirmation(parsed, runtime, "切换当前工作企业", `hose-use corps switch ${corpId} --yes`); + const success = runtime.corpContext.switchCorp(corpId); if (!success) { return { @@ -364,6 +370,16 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis }; } + if (isDryRun(parsed, runtime)) { + return mutationPreview(parsed, runtime, "从协助链接导入企业凭证", name || "待解析企业", { + source: "assistance-link", + overwrite, + ttl: ttl || null, + expires: expires || null, + }); + } + requireMutationConfirmation(parsed, runtime, "从协助链接导入企业凭证", `hose-use corps add-link --yes`); + try { const corp = await importFromLink(linkUrl, { name, diff --git a/src/cli/commands/message.ts b/src/cli/commands/message.ts index 1e36af4..8f15bd4 100644 --- a/src/cli/commands/message.ts +++ b/src/cli/commands/message.ts @@ -4,6 +4,7 @@ import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; import { createEkbClient } from "../../core/auth/ekb.js"; import { filterMessages, listMessages, mergeMessages, readMessage } from "../../domains/message/tools.js"; import type { MessageItem } from "../../domains/message/types.js"; +import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js"; function formatTime(value: number | undefined): string { return value === undefined ? "-" : new Date(value).toISOString().replace("T", " ").slice(0, 16); @@ -26,10 +27,10 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu const corp = runtime.selectedCorp; if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose-use corps list 或指定 --corp="); const action = parsed.action || parsed.args[0] || "list"; - const client = await createEkbClient(corp); const corpId = corp.corpId || corp.id; if (action === "count" || action === "unread") { + const client = await createEkbClient(corp); const result = await listMessages(client, corpId, { start: 0, count: 1, read: false }); if (runtime.jsonMode) return { stdout: printJson({ corpId, unread: result.total }, runtime.outputOptions), stderr: "", exitCode: 0 }; return { stdout: `未读消息: ${result.total}\n`, stderr: "", exitCode: 0 }; @@ -38,12 +39,22 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu if (action === "read" || action === "mark-read") { const messageId = parsed.args[0] || stringOption(parsed.options, ["id", "message-id"]); if (!messageId) return { stdout: "", stderr: "用法: hose-use message read \n", exitCode: 1 }; + if (isDryRun(parsed, runtime)) { + return mutationPreview(parsed, runtime, "标记消息为已读", messageId, { read: true }); + } + requireMutationConfirmation(parsed, runtime, "标记消息为已读", `hose-use message read ${messageId} --yes`); + const client = await createEkbClient(corp); await readMessage(client, corpId, messageId); if (runtime.jsonMode) return { stdout: printJson({ corpId, id: messageId, read: true }, runtime.outputOptions), stderr: "", exitCode: 0 }; return { stdout: `已标记消息为已读: ${messageId}\n`, stderr: "", exitCode: 0 }; } if (action === "read-all" || action === "mark-all-read") { + if (isDryRun(parsed, runtime)) { + return mutationPreview(parsed, runtime, "批量标记未读消息为已读", `corp:${corpId}`, { read: true, allUnread: true }); + } + requireMutationConfirmation(parsed, runtime, "批量标记未读消息为已读", "hose-use message read-all --yes"); + const client = await createEkbClient(corp); const ids: string[] = []; let start = 0; let total = 0; @@ -63,6 +74,8 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu return { stdout: "", stderr: `未知消息子命令: ${action}。支持: list, count, read , read-all\n`, exitCode: 1 }; } + const client = await createEkbClient(corp); + const read = booleanOption(parsed.options, ["read"]); const unread = booleanOption(parsed.options, ["unread"]); const all = booleanOption(parsed.options, ["all"]); diff --git a/src/cli/commands/skill.ts b/src/cli/commands/skill.ts index 5888631..23519ef 100644 --- a/src/cli/commands/skill.ts +++ b/src/cli/commands/skill.ts @@ -1,6 +1,7 @@ import { existsSync } from "node:fs"; import { join } from "node:path"; import { + EMBEDDED_SKILL_FILES, getDefaultGlobalSkillDir, getAgentSkillCandidates, getSkillContent, @@ -8,6 +9,7 @@ import { } from "../../core/embedded-skill.js"; import { booleanOption, stringOption } from "../parser.js"; import { printJson, printKeyValue } from "../printer.js"; +import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; export async function handleSkillCommand( @@ -41,6 +43,15 @@ export async function handleSkillCommand( ? join(process.cwd(), ".agents", "skills", "hose-use") : getDefaultGlobalSkillDir(); + if (isDryRun(parsed, runtime)) { + return mutationPreview(parsed, runtime, "安装 Agent Skill 文件", targetDir, { + fileCount: Object.keys(EMBEDDED_SKILL_FILES).length, + local: isLocal, + syncCandidates: !customDir, + }); + } + requireMutationConfirmation(parsed, runtime, "安装 Agent Skill 文件", `hose-use skill install${customDir ? ` --dir=${customDir}` : ""} --yes`); + const result = installSkillFiles(targetDir); // 也同时尝试安装到其它检测到的候选目录 diff --git a/src/cli/mutation-boundaries.test.ts b/src/cli/mutation-boundaries.test.ts new file mode 100644 index 0000000..48e55a9 --- /dev/null +++ b/src/cli/mutation-boundaries.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, test } from "bun:test"; +import { handleAuthCommand } from "./commands/auth.js"; +import { handleConfigCommand } from "./commands/config.js"; +import { handleCorpsCommand } from "./commands/corps.js"; +import { handleMessageCommand } from "./commands/message.js"; +import { handleSkillCommand } from "./commands/skill.js"; +import type { CliRuntime } from "./types.js"; + +const runtime: CliRuntime = { + corpContext: { + listCorps: () => [], + getCurrent: () => null, + switchCorp: () => true, + resolve: () => null, + } as any, + selectedCorp: { + id: "corp-test", + name: "测试企业", + corpId: "corp-test", + credentials: { accessToken: "token", corpId: "corp-test", staffId: "staff-test" }, + } as any, + jsonMode: true, +}; + +describe("CLI mutation boundaries", () => { + test("auth login dry-run does not prompt or call the login API", async () => { + const result = await handleAuthCommand({ area: "auth", action: "login", args: [], options: { "dry-run": true }, raw: ["auth", "login", "--dry-run"] }, runtime); + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout).dryRun).toBe(true); + }); + + test("corps/config state changes share the dry-run protocol", async () => { + const corp = await handleCorpsCommand({ area: "corps", action: "switch", args: ["corp-next"], options: { "dry-run": true }, raw: ["corps", "switch", "corp-next", "--dry-run"] }, runtime); + const config = await handleConfigCommand({ area: "config", action: "mode", args: ["stateless"], options: { "dry-run": true }, raw: ["config", "mode", "stateless", "--dry-run"] }, runtime); + expect(JSON.parse(corp.stdout).operation).toContain("工作企业"); + expect(JSON.parse(config.stdout).changes.stateful).toBe(false); + }); + + test("skill installation and message read never write during dry-run", async () => { + const skill = await handleSkillCommand({ area: "skill", action: "install", args: [], options: { "dry-run": true }, raw: ["skill", "install", "--dry-run"] }, runtime); + const message = await handleMessageCommand({ area: "message", action: "read", args: ["message-1"], options: { "dry-run": true }, raw: ["message", "read", "message-1", "--dry-run"] }, runtime); + expect(JSON.parse(skill.stdout).dryRun).toBe(true); + expect(JSON.parse(message.stdout).changes.read).toBe(true); + }); +});