Skip to content

🤖 Open-source, local-first alternative to Grok Bot, OpenAI dots and Claude Duet. Your own AI bots on any model: GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more through one Modelflare key. Reach them in the app, WeChat or Feishu; they remember you, work in the background, run commands and use your computer. Pay per use.

feat(windows): suggest PowerShell 7 when it's missing; DSH uses the detected pwsh

Marla840c2ee9240a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e797a6b..c3c4539 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -126,8 +126,9 @@ jobs:
# --launch shell: Start-Process without redirection (ShellExecute), so the app has no std
# handles, like a Start-menu launch. /status is probed before and during the first turn.
+ # --expect-pwsh7: the image has PowerShell 7; the app must detect it and DSH must run the tool in it.
- name: Chat through the app; no console windows
- run: node scripts/e2e-agent.mjs --out "$RUNNER_TEMP/e2e" --launch shell --cwd "$GITHUB_WORKSPACE" --timeout-ms 150000 --procmon --managed --stream --tool --status-probes --observe-ms 20000 --max-console-windows 0 --expect-diagnostics -- "$ELECTRON_EXE" .
+ run: node scripts/e2e-agent.mjs --out "$RUNNER_TEMP/e2e" --launch shell --cwd "$GITHUB_WORKSPACE" --timeout-ms 150000 --procmon --managed --stream --tool --status-probes --observe-ms 20000 --max-console-windows 0 --expect-diagnostics --expect-pwsh7 -- "$ELECTRON_EXE" .
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: failure()
diff --git a/scripts/e2e-agent.mjs b/scripts/e2e-agent.mjs
index 42e2695..6955346 100644
--- a/scripts/e2e-agent.mjs
+++ b/scripts/e2e-agent.mjs
@@ -11,6 +11,9 @@
// runs (scripts/ci/procmon.ps1), which is how the "flashing console windows" report is checked.
// --max-console-windows N: fail when more than N new visible console windows appeared (needs --procmon).
// --expect-diagnostics: also require the troubleshooting page's "test model" and "test agent" to pass.
+// --expect-pwsh7 (Windows): require that the app detected PowerShell 7 (/amb/api/pwsh and the diagnostics
+// status), passed it to DSH (the "patch written" log line) and that the --tool command ran in it
+// (the pwsh tool prints $PSVersionTable.PSVersion.Major). GitHub's windows-2025 image has PowerShell 7.
// --tool: the mock model asks for one shell tool call before answering (exercises tool spawning).
// --managed: use the bundled magpie gateway (as users do) with "Modelflare" pointed at the mock
// (AMB_MODELFLARE_BASE_URL) and connected through the API; otherwise the app calls the mock directly.
@@ -68,6 +71,7 @@ const jl = (file, obj) => fs.appendFileSync(path.join(out, file), JSON.stringify
const MODEL = "mock-agent";
const ANSWER = "pong-from-mock";
const wantTool = flag("tool");
+const expectPwsh7 = flag("expect-pwsh7");
const managed = flag("managed");
const reasoning = flag("reasoning");
const observeMs = Number(opt("observe-ms", 0));
@@ -111,7 +115,9 @@ const llm = http.createServer(async (req, res) => {
// One shell call first when asked (and the runtime offers a shell tool), then the answer.
const shell = tools.find((n) => n === "bash" || n === "pwsh" || n === "powershell");
const toolResults = msgs.filter((m) => m.role === "tool");
- const call = wantTool && b.tools && shell && !toolResults.length ? { name: shell, args: { description: "say hi", command: "echo tool-ran-ok" } } : undefined;
+ // PowerShell also prints its major version, so the e2e can tell PowerShell 7 from Windows PowerShell 5.1
+ const command = shell === "bash" ? "echo tool-ran-ok" : 'echo tool-ran-ok; "psver=$($PSVersionTable.PSVersion.Major)"';
+ const call = wantTool && b.tools && shell && !toolResults.length ? { name: shell, args: { description: "say hi", command } } : undefined;
const text = toolResults.length ? `${ANSWER} [${toolResults.map((m) => textOf(m.content)).join("|").slice(0, 300)}]` : ANSWER;
if (!b.stream) {
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ id: "c1", object: "chat.completion", model: b.model, choices: [{ index: 0, message: { role: "assistant", content: text }, finish_reason: "stop" }], usage: { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 } }));
@@ -334,6 +340,29 @@ try {
say(`test model: ${modelOk ? "ok" : "FAILED"} (${m?.verdict ?? "no result"}); test agent: ${summary.testAgent?.ok ? "ok" : `FAILED at ${summary.testAgent?.stuckAt ?? "?"}`}`);
summary.ok &&= modelOk && !!summary.testAgent?.ok;
}
+ if (expectPwsh7) {
+ // PowerShell 7 detected, handed to DSH and actually used for the tool call
+ const ps = (await api("/amb/api/pwsh", {}, 30_000)).body;
+ const diagPs = JSON.parse(fs.readFileSync(path.join(out, "diag-diag.json"), "utf8")).body?.pwsh;
+ fs.writeFileSync(path.join(out, "diag-pwsh.json"), JSON.stringify({ api: ps, diagnostics: diagPs }, null, 2));
+ let patchLine = "";
+ try {
+ patchLine = fs.readFileSync(path.join(dataDir, "logs", "app.log"), "utf8").split(/\r?\n/).find((l) => l.includes("dsh start: patch written")) ?? "";
+ } catch {
+ /* no log */
+ }
+ const psver = [summary.chat, summary.chat2].map((c) => /psver=(\d+)/.exec(c?.reply ?? "")?.[1]).filter(Boolean);
+ summary.pwsh = { api: ps, diagnostics: diagPs, patchLine: patchLine.slice(0, 400), psver };
+ const ok7 = (x) => !!x?.applicable && !!x?.found && !x?.missing && /^7\./.test(x?.version ?? "");
+ const checks = {
+ detected: ok7(ps),
+ diagnostics: ok7(diagPs),
+ passedToDsh: /"pwsh":"[^"]*pwsh\.exe"/i.test(patchLine),
+ toolRanInPwsh7: !wantTool || (psver.length > 0 && psver.every((v) => v === "7")),
+ };
+ say(`PowerShell: ${ps?.version ?? "-"} at ${ps?.path ?? "-"} (${ps?.source ?? "-"}); checks ${JSON.stringify(checks)}; tool psver ${psver.join(",") || "-"}`);
+ summary.ok &&= Object.values(checks).every(Boolean);
+ }
} catch (e) {
summary.error = String(e?.message ?? e);
say("error:", summary.error);
diff --git a/src/agent/host.ts b/src/agent/host.ts
index 2a7f062..34af9d3 100644
--- a/src/agent/host.ts
+++ b/src/agent/host.ts
@@ -9,6 +9,7 @@ import os from "node:os";
import { findAppRoot } from "../magpie/supervisor.js";
import { adaptSkill, mcpPatchLines, resolveComputerUse, type CuResolved } from "./computer-use.js";
import { cuaConfig, cuaMcpEnv, discoverAppsCached, type CuaApp } from "./cua-driver.js";
+import { pwshPatchLines, pwshProbe } from "./pwsh.js";
import { DEFAULT_SETTINGS, permissionMode, type BotSettings } from "./settings.js";
const log = logger("agent.host");
@@ -309,7 +310,7 @@ export class AgentHost {
});
}
- private writePatch(model: string, apps: CuaApp[] = []): string {
+ private writePatch(model: string, apps: CuaApp[] = [], pwshPath?: string): string {
const lim = MODEL_LIMITS.find(([re]) => re.test(model)) ?? [/./, 128_000, 16_000];
const plugin = path.join(this.o.runtimeDir, "plugins", "amb-bridge.mjs");
const memory = path.join(this.o.runtimeDir, "plugins", "amb-memory.mjs");
@@ -328,6 +329,8 @@ export class AgentHost {
` name: ${yamlStr(model.split("/").pop() || model)}`,
` contextWindow: ${lim[1]}`,
` maxTokens: ${lim[2]}`,
+ // Windows:命令用检测到的 PowerShell 7(DSH 自己只看 Program Files\PowerShell\7 和 PATH,找不到就退回 5.1)
+ ...pwshPatchLines(pwshPath),
"- insert:",
" - id: amb-bridge",
` name: ${yamlStr(plugin)}`,
@@ -507,7 +510,8 @@ exec "$REAL" "$@"
/** 影响子进程启动参数的设置签名 */
private settingsSig(): string {
const st = this.settings();
- return `${st.permission}|${st.memory.enabled}|${st.computerUse.enabled}|${st.computerUse.backend}|${st.computerUse.approval}`;
+ // 带上 PowerShell 路径:用户装好 PowerShell 7 点"重新检测"后,空闲的代理进程在下一条消息时换用它
+ return `${st.permission}|${st.memory.enabled}|${st.computerUse.enabled}|${st.computerUse.backend}|${st.computerUse.approval}|${pwshProbe.cachedDshPath ?? ""}`;
}
private sig = "";
@@ -552,7 +556,7 @@ exec "$REAL" "$@"
await this.closeHarness();
}
if (this.harness && this.sig !== this.settingsSig() && this.active === 0) {
- log.info("bot settings changed, restarting dsh", { bot: this.o.botId });
+ log.info("bot settings or PowerShell changed, restarting dsh", { bot: this.o.botId });
await this.closeHarness();
}
if (this.harness) return this.harness;
@@ -607,10 +611,11 @@ exec "$REAL" "$@"
// 应用清单(Computer Use 的能力清单用)异步扫描并缓存,不阻塞主进程
const cu = this.computerUseActive();
const apps = cu && cu.backend === "cua" ? await discoverAppsCached() : [];
- const patch = this.writePatch(model, apps);
+ const pwshPath = await pwshProbe.dshPath();
+ const patch = this.writePatch(model, apps, pwshPath);
this.sig = this.settingsSig();
const timeoutMs = this.initTimeoutMs();
- this.stage("patch written", t0, { computerUse: cu ? cu.backend : "off", apps: apps.length, initTimeoutMs: timeoutMs });
+ this.stage("patch written", t0, { computerUse: cu ? cu.backend : "off", apps: apps.length, initTimeoutMs: timeoutMs, ...(process.platform === "win32" ? { pwsh: pwshPath ?? "dsh default (Windows PowerShell 5.1)" } : {}) });
h = new sdk.DeepSeekHarness({
profile: "sdk",
patches: [patch],
diff --git a/src/agent/pwsh.ts b/src/agent/pwsh.ts
new file mode 100644
index 0000000..3f60c97
--- /dev/null
+++ b/src/agent/pwsh.ts
@@ -0,0 +1,224 @@
+/**
+ * Windows 上的 PowerShell 7(pwsh)检测。
+ *
+ * 代理(DSH)在 Windows 上用 PowerShell 执行命令(@deepseek-ai/dsh-pwsh-sandbox,经 Windows ACL 沙箱)。它自己按
+ * %ProgramFiles%\PowerShell\7\pwsh.exe → PATH 里的 pwsh.exe → Windows PowerShell 5.1 的顺序找
+ * (dsh-pwsh-local 的 resolvePwshPath)。经沙箱时 5.1 每条命令要二三十秒,PowerShell 7 大约 1 秒,
+ * 所以没装 7 时界面里建议安装。
+ *
+ * - 只看文件,不拉起进程、不阻塞主线程:先按 DSH 的顺序,再补上 DSH 不看的位置(7-preview 等其他 7* 目录、
+ * Microsoft Store / winget 的 WindowsApps 别名)。
+ * - 找到的路径写进 DSH 补丁(pwsh-sandbox 的 pwshPath),DSH 用的就是这里检测到的那一个。
+ * - 版本号异步读:先读 pwsh.deps.json,读不到(Store 别名)再 `pwsh -Version`(windowsHide,5 秒超时)。
+ * - 结果缓存;"重新检测"时刷新。AMB_PWSH_FORCE=missing 在任何平台上模拟"未安装"(截图、测试),不影响 DSH。
+ */
+import { execFile } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { logger } from "../log.js";
+
+const log = logger("pwsh");
+const W = path.win32;
+
+export const PWSH_INSTALL_URL = "https://aka.ms/PSWindows";
+export const PWSH_WINGET = "winget install --id Microsoft.PowerShell --source winget";
+
+/** program-files:%ProgramFiles%\PowerShell\7(MSI、winget);preview:7-preview 等;store:WindowsApps 别名;path:PATH 里的其他位置 */
+export type PwshSource = "program-files" | "path" | "preview" | "store";
+
+export interface PwshCandidate {
+ path: string;
+ source: PwshSource;
+}
+
+export interface PwshStatus {
+ /** 只在 Windows 上检测(或 AMB_PWSH_FORCE 模拟);其他平台代理用 bash */
+ applicable: boolean;
+ /** 第一次检测还没完成 */
+ checking?: boolean;
+ /** 找到了 pwsh.exe */
+ found: boolean;
+ /** 没有 PowerShell 7+:代理会退回 Windows PowerShell 5.1(或更旧的 pwsh),界面建议安装 */
+ missing: boolean;
+ path?: string;
+ source?: PwshSource;
+ /** 例如 7.4.6;读不到时为空 */
+ version?: string;
+ /** AMB_PWSH_FORCE=missing 模拟的结果 */
+ forced?: boolean;
+ checkedAt: number;
+}
+
+/** 可替换的环境与文件系统(测试用) */
+export interface PwshDeps {
+ env?: NodeJS.ProcessEnv;
+ platform?: NodeJS.Platform;
+ lstat?: (p: string) => Promise<{ isFile(): boolean; isSymbolicLink(): boolean }>;
+ readdir?: (p: string) => Promise<string[]>;
+ readFile?: (p: string) => Promise<string>;
+ /** `pwsh -Version` 的输出(读版本号的最后手段) */
+ runVersion?: (exe: string) => Promise<string>;
+}
+
+const dirKey = (p: string) => W.normalize(p).replace(/\\+$/, "").toLowerCase();
+
+function pathEntries(env: NodeJS.ProcessEnv): string[] {
+ return (env.PATH ?? env.Path ?? "")
+ .split(";")
+ .map((e) => e.trim().replace(/^"|"$/g, ""))
+ .filter(Boolean);
+}
+
+/** 按优先级排好的候选位置:前两类和 DSH 的顺序一致,后两类是 DSH 自己不看的 */
+export async function pwshCandidates(d: PwshDeps = {}): Promise<PwshCandidate[]> {
+ const env = d.env ?? process.env;
+ const readdir = d.readdir ?? ((p: string) => fs.promises.readdir(p));
+ const roots = [...new Set([env.ProgramFiles || "C:\\Program Files", env.ProgramW6432].filter((r): r is string => !!r).map((r) => W.join(r, "PowerShell")))];
+ const store = env.LOCALAPPDATA ? W.join(env.LOCALAPPDATA, "Microsoft", "WindowsApps") : "";
+ const list: PwshCandidate[] = [{ path: W.join(roots[0], "7", "pwsh.exe"), source: "program-files" }];
+ for (const dir of pathEntries(env)) list.push({ path: W.join(dir, "pwsh.exe"), source: store && dirKey(dir) === dirKey(store) ? "store" : "path" });
+ for (const root of roots) {
+ const names = (await readdir(root).catch(() => [] as string[])).filter((n) => /^7/.test(n));
+ names.sort((a, b) => Number(/preview/i.test(a)) - Number(/preview/i.test(b)) || a.localeCompare(b));
+ for (const n of names) list.push({ path: W.join(root, n, "pwsh.exe"), source: /preview/i.test(n) ? "preview" : "program-files" });
+ }
+ if (store) list.push({ path: W.join(store, "pwsh.exe"), source: "store" });
+ const seen = new Set<string>();
+ return list.filter((c) => !seen.has(dirKey(c.path)) && !!seen.add(dirKey(c.path)));
+}
+
+/**
+ * 第一个存在的 pwsh.exe。和 DSH 一样用 lstat:Store 的应用执行别名是重解析点,stat 会撞上目标的 ACL(EACCES),
+ * lstat 看到的是别名本身(新版 Node 报成符号链接,旧版报成文件)。
+ */
+export async function findPwsh(d: PwshDeps = {}): Promise<PwshCandidate | undefined> {
+ const lstat = d.lstat ?? ((p: string) => fs.promises.lstat(p));
+ const list = await pwshCandidates(d);
+ const hits = await Promise.all(list.map((c) => lstat(c.path).then((s) => s.isFile() || s.isSymbolicLink(), () => false)));
+ const i = hits.indexOf(true);
+ return i >= 0 ? list[i] : undefined;
+}
+
+export function parsePwshVersion(text: string): string | undefined {
+ return /(\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?)/.exec(text)?.[1];
+}
+
+function runVersion(exe: string): Promise<string> {
+ return new Promise((resolve, reject) =>
+ execFile(exe, ["-Version"], { windowsHide: true, timeout: 5000, encoding: "utf8", maxBuffer: 64 * 1024 }, (err, stdout) => (err ? reject(err) : resolve(String(stdout)))),
+ );
+}
+
+/** 版本号:MSI / zip 安装目录里的 pwsh.deps.json 有 "pwsh/7.4.6",不用拉起进程;Store 别名旁边没有,再问 pwsh 自己 */
+export async function readPwshVersion(c: PwshCandidate, d: PwshDeps = {}): Promise<string | undefined> {
+ const readFile = d.readFile ?? ((p: string) => fs.promises.readFile(p, "utf8"));
+ try {
+ const m = /"pwsh\/(\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?)"/.exec(await readFile(W.join(W.dirname(c.path), "pwsh.deps.json")));
+ if (m) return m[1];
+ } catch {
+ /* 没有这个文件 */
+ }
+ try {
+ return parsePwshVersion(await (d.runVersion ?? runVersion)(c.path));
+ } catch (e) {
+ log.warn("could not read the PowerShell version", { path: c.path, err: String((e as Error)?.message ?? e).slice(0, 200) });
+ return undefined;
+ }
+}
+
+export class PwshProbe {
+ private run?: Promise<PwshStatus>;
+ private locating?: Promise<PwshCandidate | undefined>;
+ private located?: PwshCandidate;
+ private last?: PwshStatus;
+
+ constructor(private readonly d: PwshDeps = {}) {}
+
+ private get platform(): NodeJS.Platform {
+ return this.d.platform ?? process.platform;
+ }
+ private get forced(): boolean {
+ return (this.d.env ?? process.env).AMB_PWSH_FORCE === "missing";
+ }
+ get applicable(): boolean {
+ return this.platform === "win32" || this.forced;
+ }
+
+ /** 检测(结果缓存);refresh = 重新检测 */
+ check(refresh = false): Promise<PwshStatus> {
+ if (this.run && !refresh) return this.run;
+ if (!this.applicable || this.forced) {
+ this.last = { applicable: this.applicable, found: false, missing: this.forced, ...(this.forced ? { forced: true } : {}), checkedAt: Date.now() };
+ return (this.run = Promise.resolve(this.last));
+ }
+ const t0 = Date.now();
+ const locating = findPwsh(this.d).catch((e) => {
+ log.warn("PowerShell detection failed", { err: String((e as Error)?.message ?? e) });
+ return undefined;
+ });
+ this.locating = locating;
+ const run: Promise<PwshStatus> = locating.then(async (c) => {
+ if (this.locating === locating) this.located = c;
+ const version = c ? await readPwshVersion(c, this.d) : undefined;
+ const st: PwshStatus = { applicable: true, found: !!c, missing: !c || Number(version?.split(".")[0]) < 7, path: c?.path, source: c?.source, version, checkedAt: Date.now() };
+ if (this.run === run) this.last = st;
+ log.info("PowerShell", { found: st.found, missing: st.missing, path: st.path, source: st.source, version: st.version, ms: Date.now() - t0 });
+ return st;
+ });
+ this.run = run;
+ return run;
+ }
+
+ /** 同步快照(/status、诊断):没检测过就开始检测,先返回"检测中" */
+ snapshot(): PwshStatus {
+ if (!this.run) void this.check();
+ return this.last ?? { applicable: this.applicable, checking: true, found: false, missing: false, checkedAt: 0 };
+ }
+
+ /**
+ * DSH 启动前调用:要写进补丁的 pwshPath。只等文件检测(不等版本号),最多 waitMs;
+ * 不是 Windows、模拟"未安装"或没找到时返回 undefined(DSH 自己找)。
+ */
+ async dshPath(waitMs = 3000): Promise<string | undefined> {
+ if (this.platform !== "win32" || this.forced) return undefined;
+ if (!this.run) void this.check();
+ let timer: NodeJS.Timeout | undefined;
+ const c = await Promise.race([this.locating!, new Promise<undefined>((r) => (timer = setTimeout(() => r(undefined), waitMs)))]);
+ clearTimeout(timer);
+ return c?.path;
+ }
+
+ /** 最近一次检测到的 DSH 路径(同步):变了就在代理进程空闲时重启它 */
+ get cachedDshPath(): string | undefined {
+ return this.platform !== "win32" || this.forced ? undefined : this.located?.path;
+ }
+}
+
+/** 进程内共用的一个:宿主、诊断、/status、界面接口都读它 */
+export const pwshProbe = new PwshProbe();
+
+/** DSH 补丁:Windows 上的 pwsh 执行器(pwsh-sandbox;基础 profile 里它没有 config)用检测到的这一个 */
+export function pwshPatchLines(pwshPath: string | undefined): string[] {
+ return pwshPath ? ["- id: pwsh-sandbox", " config:", ` pwshPath: ${JSON.stringify(pwshPath)}`] : [];
+}
+
+const SOURCE: Record<PwshSource, string> = { "program-files": "安装目录", path: "PATH", preview: "预览版", store: "Microsoft Store" };
+
+/** 聊天里 /status 的一行(只在 Windows 上有) */
+export function pwshStatusLine(st: PwshStatus): string {
+ if (!st.applicable) return "";
+ if (st.checking) return "PowerShell:检测中";
+ if (!st.missing) return `PowerShell:${st.version ?? "7"}(代理用它执行命令)`;
+ const now = st.found && st.version ? `PowerShell ${st.version} 版本较旧` : "没有安装 PowerShell 7,代理执行命令用的是系统自带的 Windows PowerShell 5.1,每条可能要二三十秒";
+ return `PowerShell:${now}。装上 PowerShell 7,命令执行快得多,也更稳定:${PWSH_WINGET}(或打开 ${PWSH_INSTALL_URL})`;
+}
+
+/** 诊断报告里的一行(只在 Windows 上有) */
+export function pwshReportLine(st: PwshStatus): string | undefined {
+ if (!st.applicable) return undefined;
+ if (st.checking) return "[PowerShell] 检测中";
+ const where = st.path ? ` · ${st.path}(${SOURCE[st.source!] ?? st.source})` : "";
+ if (!st.missing) return `[PowerShell] ${st.version ?? "7(版本未知)"}${where} · 代理用它执行命令`;
+ if (st.found) return `[PowerShell] ${st.version ?? "?"} 版本较旧${where} · 建议安装 PowerShell 7`;
+ return `[PowerShell] 未安装 PowerShell 7:代理用 Windows PowerShell 5.1 执行命令(经沙箱每条约 25 秒,7 约 1 秒)${st.forced ? " · AMB_PWSH_FORCE 模拟" : ""}`;
+}
diff --git a/src/app.ts b/src/app.ts
index d2b052f..fc2b895 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -17,6 +17,7 @@ import { initFileLog, logFilePath, logger, mask, registerSecret } from "./log.js
import { AgentManager } from "./agent/manager.js";
import { normalizeSettings } from "./agent/settings.js";
import { locateDshRuntime } from "./agent/host.js";
+import { pwshProbe } from "./agent/pwsh.js";
import { findAppRoot } from "./magpie/supervisor.js";
import {
MODELFLARE_LINES,
@@ -363,6 +364,8 @@ export class App {
this.picksTimer = setInterval(() => void this.syncModelPicks(), 3600_000);
this.picksTimer.unref();
}
+ // Windows:找 PowerShell 7(只看文件,异步);代理进程启动时和界面的提示都用这个结果
+ if (pwshProbe.applicable) void pwshProbe.check();
void this.prewarmAgent();
if (this.magpie && !this.opts.noWeb) {
// 余额与低余额提醒:启动后读一次,之后每 5 分钟一次
diff --git a/src/config.ts b/src/config.ts
index 19eaaf8..719cfe2 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -16,6 +16,8 @@ export interface AppConfig {
zoom: number;
/** 桌面版关闭窗口时:true 隐藏到托盘,false 退出 */
closeToTray: boolean;
+ /** Windows 上"建议安装 PowerShell 7"的提示点过"不再提示" */
+ pwshHintDismissed: boolean;
};
/**
* Modelflare 线路;密钥本身只存在内置 magpie 的隔离配置里。
@@ -67,6 +69,7 @@ export function loadConfig(overrides: { dataDir?: string; env?: NodeJS.ProcessEn
token: env.AMB_UI_TOKEN || file.ui?.token || "",
zoom: ZOOMS.includes(Number(file.ui?.zoom)) ? Number(file.ui?.zoom) : 1,
closeToTray: file.ui?.closeToTray !== false,
+ pwshHintDismissed: file.ui?.pwshHintDismissed === true,
},
modelflare: {
line: normalizeLine(file.modelflare?.line),
diff --git a/src/core/runtime.ts b/src/core/runtime.ts
index a1a91d3..fbab5d5 100644
--- a/src/core/runtime.ts
+++ b/src/core/runtime.ts
@@ -7,6 +7,7 @@ import { logger } from "../log.js";
import type { AgentManager } from "../agent/manager.js";
import { promptText, type QuestionItem } from "../agent/approvals.js";
import { MEMORY_GUIDE } from "../agent/steward.js";
+import { pwshProbe, pwshStatusLine } from "../agent/pwsh.js";
import { isBotProviderModel } from "../modelflare.js";
import type { ApprovalRow } from "../store/db.js";
@@ -147,9 +148,11 @@ export class BotRuntime {
const cui = a?.available ? a.computerUse(botId) : undefined;
const cu = cui ? [`电脑操作:${cui.backend === "codex" ? "Codex 桥" : "Cua Driver"},${cui.active ? "已启用" : "未启用"}——${cui.reason}`, ...(cui.notice && cui.enabled ? [cui.notice] : [])] : [];
const host = a?.available ? [a.hostSummary(botId)] : [];
+ // Windows:代理执行命令用的 PowerShell;没有 7 时建议安装
+ const ps = a?.available ? pwshStatusLine(pwshProbe.snapshot()) : "";
const turn = a?.turnsInProgress.get(convId);
const busy = turn ? [`本会话上一条消息还在处理(已 ${Math.round((Date.now() - turn.since) / 1000)} 秒),新消息会排在它后面`] : [];
- return [`当前模型:${m}${convModel ? "(会话设置)" : ""}`, `运行方式:${mode}`, ...host, ...busy, ...cu, ...(pend.length ? [`未决:${pend.join(",")}`] : [])].join("\n");
+ return [`当前模型:${m}${convModel ? "(会话设置)" : ""}`, `运行方式:${mode}`, ...host, ...(ps ? [ps] : []), ...busy, ...cu, ...(pend.length ? [`未决:${pend.join(",")}`] : [])].join("\n");
}
/** 卡片按钮回调:批准/拒绝/选择选项。 */
diff --git a/src/diagnostics.ts b/src/diagnostics.ts
index bf6af87..d64821c 100644
--- a/src/diagnostics.ts
+++ b/src/diagnostics.ts
@@ -9,6 +9,7 @@ import type { HostEvent } from "./agent/host.js";
import type { ProxyEvent } from "./agent/bridge.js";
import { logFilePath, logger, readLogTail, redactText, redactValue } from "./log.js";
import { bareModel } from "./modelflare.js";
+import { pwshProbe, pwshReportLine } from "./agent/pwsh.js";
const log = logger("diagnostics");
@@ -343,6 +344,8 @@ export function diagnosticsStatus(app: App): Record<string, unknown> {
}
: { mode: "external", state: "external", url: redactText(app.config.magpie.externalBaseUrl) },
agent: app.agent.diagnostics(),
+ // Windows:代理执行命令用的 PowerShell(没有 7 时每条命令要二三十秒)
+ pwsh: pwshProbe.snapshot(),
last: app.lastDiagnostics,
};
}
@@ -373,6 +376,8 @@ export function diagnosticsReport(app: App, lines = 200): string {
out.push(` 机器人 ${id}: ${h.state} · pid ${h.pid ?? "-"} · 重启 ${h.restarts} 次 · 进行中 ${h.activeTurns}${h.lastExit ? ` · 上次退出 code=${h.lastExit.code} signal=${h.lastExit.signal} @ ${ts(h.lastExit.at)}` : ""}${h.lastError ? `\n 最近错误:${h.lastError}` : ""}`);
for (const l of h.stderrTail ?? []) out.push(` | ${l}`);
}
+ const ps = pwshReportLine(s.pwsh);
+ if (ps) out.push(ps);
const m = app.lastDiagnostics.model;
if (m) {
out.push("");
diff --git a/src/web/server.ts b/src/web/server.ts
index f07fa79..c59c8e5 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -17,6 +17,7 @@ import { connectionFromPids } from "../agent/peer-guard.js";
import type { ApprovalRow } from "../store/db.js";
import { normalizeSettings } from "../agent/settings.js";
import { scopeLabel } from "../agent/memory.js";
+import { pwshProbe, type PwshStatus } from "../agent/pwsh.js";
const log = logger("web");
const require = createRequire(import.meta.url);
@@ -354,6 +355,27 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
return send(res, 200, { ok: true });
}
if (p === "/agent" && m === "GET") return send(res, 200, app.agent.status());
+ // —— Windows:没有 PowerShell 7 时建议安装(对话空状态、设置 → 常规、故障排查)——
+ if (seg[0] === "pwsh") {
+ const view = (st: PwshStatus) => ({ ...st, dismissed: cfg.ui.pwshHintDismissed });
+ if (seg.length === 1 && m === "GET") return send(res, 200, view(await pwshProbe.check()));
+ if (seg[1] === "recheck" && m === "POST") {
+ const before = pwshProbe.cachedDshPath;
+ const st = await pwshProbe.check(true);
+ // 代理进程空闲时下一条消息会换用新的 PowerShell(宿主的设置签名里带着它)
+ if (pwshProbe.cachedDshPath !== before) log.info("PowerShell changed; idle agent hosts restart on the next message", { from: before, to: pwshProbe.cachedDshPath });
+ return send(res, 200, view(st));
+ }
+ if (seg.length === 1 && m === "PUT") {
+ const b = await readJson(req);
+ if (b.dismissed !== undefined) {
+ cfg.ui.pwshHintDismissed = !!b.dismissed;
+ saveConfigFile(cfg.dataDir, (f) => (f.ui = { ...(f.ui ?? {}), pwshHintDismissed: cfg.ui.pwshHintDismissed }));
+ }
+ return send(res, 200, view(await pwshProbe.check()));
+ }
+ throw new HttpError(405, "method not allowed");
+ }
// —— 故障排查(设置 → 故障排查):所有输出都已脱敏 ——
if (seg[0] === "diagnostics") {
const sub = seg.slice(1).join("/");
diff --git a/test/pwsh.unit.test.ts b/test/pwsh.unit.test.ts
new file mode 100644
index 0000000..059fd43
--- /dev/null
+++ b/test/pwsh.unit.test.ts
@@ -0,0 +1,252 @@
+/**
+ * Windows 上的 PowerShell 7 检测(文件系统、环境变量和路径都是假的,在任何平台上跑)+ 界面接口、诊断报告。
+ */
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+// 读版本号的最后手段(`pwsh -Version`):只拦假的 pwsh.exe,其余照常
+const spawned: Array<{ exe: string; args: string[]; opts: any }> = [];
+vi.mock("node:child_process", async (orig) => {
+ const real: any = await orig();
+ const execFile = (exe: string, args: string[], opts: any, cb: (e: Error | null, out: string, err: string) => void) => {
+ if (!/^C:\\.*pwsh\.exe$/i.test(exe)) return real.execFile(exe, args, opts, cb);
+ spawned.push({ exe, args, opts });
+ setImmediate(() => cb(null, "PowerShell 7.5.4\r\n", ""));
+ return {} as any;
+ };
+ return { ...real, default: { ...real, execFile }, execFile };
+});
+
+import { PwshProbe, findPwsh, parsePwshVersion, pwshPatchLines, pwshReportLine, pwshStatusLine, readPwshVersion, PWSH_WINGET, type PwshDeps } from "../src/agent/pwsh.js";
+import { App } from "../src/app.js";
+import { loadConfig } from "../src/config.js";
+
+const PF = "C:\\Program Files";
+const LOCAL = "C:\\Users\\li\\AppData\\Local";
+const APPS = `${LOCAL}\\Microsoft\\WindowsApps`;
+const PS5 = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\";
+const ENV = { ProgramFiles: PF, ProgramW6432: PF, LOCALAPPDATA: LOCAL, PATH: `C:\\Windows\\system32;C:\\Windows;${PS5};${APPS}` };
+const DEPS_746 = '{"targets":{".NETCoreApp,Version=v8.0/win-x64":{"pwsh/7.4.6":{"dependencies":{}}}},"libraries":{"pwsh/7.4.6":{"type":"project"}}}';
+
+/** 假的 Windows 文件系统:exes 里是存在的 pwsh.exe(file 或 Store 别名 alias),texts 是可读的文件,dirs 是目录列表 */
+function fakeWin(o: { exes?: Record<string, "file" | "alias">; texts?: Record<string, string>; dirs?: Record<string, string[]>; env?: NodeJS.ProcessEnv; runVersion?: PwshDeps["runVersion"] } = {}) {
+ const k = (p: string) => p.toLowerCase();
+ const exes = new Map(Object.entries(o.exes ?? {}).map(([p, v]) => [k(p), v]));
+ const texts = new Map(Object.entries(o.texts ?? {}).map(([p, v]) => [k(p), v]));
+ const lstats: string[] = [];
+ const runs: string[] = [];
+ const enoent = (p: string) => Object.assign(new Error(`ENOENT: ${p}`), { code: "ENOENT" });
+ const deps: PwshDeps = {
+ platform: "win32",
+ env: o.env ?? ENV,
+ lstat: async (p) => {
+ lstats.push(p);
+ const v = exes.get(k(p));
+ if (!v) throw enoent(p);
+ return { isFile: () => v === "file", isSymbolicLink: () => v === "alias" };
+ },
+ readdir: async (p) => {
+ const d = o.dirs?.[p];
+ if (!d) throw enoent(p);
+ return d;
+ },
+ readFile: async (p) => {
+ const v = texts.get(k(p));
+ if (v === undefined) throw enoent(p);
+ return v;
+ },
+ runVersion: async (exe) => {
+ runs.push(exe);
+ if (!o.runVersion) throw new Error("no version");
+ return o.runVersion(exe);
+ },
+ };
+ return { deps, lstats, runs, addExe: (p: string, v: "file" | "alias" = "file") => exes.set(k(p), v) };
+}
+
+describe("PowerShell 7 检测", () => {
+ it("不是 Windows:不检测、不碰文件,DSH 补丁里不写 pwshPath", async () => {
+ const w = fakeWin({ exes: { [`${PF}\\PowerShell\\7\\pwsh.exe`]: "file" } });
+ const probe = new PwshProbe({ ...w.deps, platform: "linux", env: {} });
+ expect(probe.applicable).toBe(false);
+ expect(await probe.check()).toMatchObject({ applicable: false, found: false, missing: false });
+ expect(await probe.dshPath()).toBeUndefined();
+ expect(w.lstats).toEqual([]);
+ expect(pwshStatusLine(probe.snapshot())).toBe("");
+ expect(pwshReportLine(probe.snapshot())).toBeUndefined();
+ });
+
+ it("和 DSH 一样先认 Program Files\\PowerShell\\7;版本号从 pwsh.deps.json 读,不拉起进程", async () => {
+ const exe = `${PF}\\PowerShell\\7\\pwsh.exe`;
+ const w = fakeWin({ exes: { [exe]: "file", [`${APPS}\\pwsh.exe`]: "alias" }, texts: { [`${PF}\\PowerShell\\7\\pwsh.deps.json`]: DEPS_746 } });
+ const probe = new PwshProbe(w.deps);
+ const st = await probe.check();
+ expect(st).toMatchObject({ applicable: true, found: true, missing: false, path: exe, source: "program-files", version: "7.4.6" });
+ expect(w.runs).toEqual([]);
+ expect(await probe.dshPath()).toBe(exe);
+ expect(probe.cachedDshPath).toBe(exe);
+ expect(pwshStatusLine(st)).toBe("PowerShell:7.4.6(代理用它执行命令)");
+ expect(pwshReportLine(st)).toBe(`[PowerShell] 7.4.6 · ${exe}(安装目录) · 代理用它执行命令`);
+ });
+
+ it("PATH 里的 pwsh.exe(带引号和空格的项);读不到 deps.json 时问 pwsh -Version", async () => {
+ const dir = "D:\\Tools\\PowerShell 7";
+ const env = { ...ENV, PATH: `C:\\Windows\\system32; "${dir}" ;${PS5}` };
+ const w = fakeWin({ env, exes: { [`${dir}\\pwsh.exe`]: "file" }, runVersion: async () => "PowerShell 7.5.4\r\n" });
+ const st = await new PwshProbe(w.deps).check();
+ expect(st).toMatchObject({ found: true, missing: false, path: `${dir}\\pwsh.exe`, source: "path", version: "7.5.4" });
+ expect(w.runs).toEqual([`${dir}\\pwsh.exe`]);
+ });
+
+ it("预览版(7-preview,DSH 自己找不到):找到并写进 DSH 补丁", async () => {
+ const exe = `${PF}\\PowerShell\\7-preview\\pwsh.exe`;
+ const w = fakeWin({
+ exes: { [exe]: "file" },
+ dirs: { [`${PF}\\PowerShell`]: ["Modules", "7-preview"] },
+ texts: { [`${PF}\\PowerShell\\7-preview\\pwsh.deps.json`]: DEPS_746.replaceAll("7.4.6", "7.6.0-preview.5") },
+ });
+ const probe = new PwshProbe(w.deps);
+ expect(await probe.check()).toMatchObject({ found: true, missing: false, source: "preview", version: "7.6.0-preview.5" });
+ expect(pwshPatchLines(await probe.dshPath())).toEqual(["- id: pwsh-sandbox", " config:", ' pwshPath: "C:\\\\Program Files\\\\PowerShell\\\\7-preview\\\\pwsh.exe"']);
+ expect(pwshPatchLines(undefined)).toEqual([]);
+ });
+
+ it("正式版和预览版都在时先用正式版", async () => {
+ const w = fakeWin({
+ exes: { [`${PF}\\PowerShell\\7.5\\pwsh.exe`]: "file", [`${PF}\\PowerShell\\7-preview\\pwsh.exe`]: "file" },
+ dirs: { [`${PF}\\PowerShell`]: ["7-preview", "7.5"] },
+ });
+ expect(await findPwsh(w.deps)).toEqual({ path: `${PF}\\PowerShell\\7.5\\pwsh.exe`, source: "program-files" });
+ });
+
+ it("Microsoft Store / winget 的 WindowsApps 别名:lstat 报成符号链接也算;不在 PATH 里也找得到", async () => {
+ const env = { ...ENV, PATH: `C:\\Windows\\system32;${PS5}` };
+ const w = fakeWin({ env, exes: { [`${APPS}\\pwsh.exe`]: "alias" }, runVersion: async () => "PowerShell 7.5.4" });
+ const st = await new PwshProbe(w.deps).check();
+ expect(st).toMatchObject({ found: true, missing: false, path: `${APPS}\\pwsh.exe`, source: "store", version: "7.5.4" });
+ // 在 PATH 里(默认如此)时同样标成 Store
+ const w2 = fakeWin({ exes: { [`${APPS}\\pwsh.exe`]: "alias" } });
+ expect(await findPwsh(w2.deps)).toEqual({ path: `${APPS}\\pwsh.exe`, source: "store" });
+ });
+
+ it("没有 PowerShell 7:提示安装;DSH 补丁不写 pwshPath(它退回 Windows PowerShell 5.1)", async () => {
+ const w = fakeWin({ exes: { [`${PS5}powershell.exe`]: "file" } });
+ const probe = new PwshProbe(w.deps);
+ const st = await probe.check();
+ expect(st).toMatchObject({ applicable: true, found: false, missing: true });
+ expect(st.path).toBeUndefined();
+ expect(await probe.dshPath()).toBeUndefined();
+ expect(pwshStatusLine(st)).toContain("Windows PowerShell 5.1");
+ expect(pwshStatusLine(st)).toContain(PWSH_WINGET);
+ expect(pwshReportLine(st)).toContain("未安装 PowerShell 7");
+ // 每个候选都只看了一次文件(PATH 里重复的目录去重)
+ expect(new Set(w.lstats.map((p) => p.toLowerCase())).size).toBe(w.lstats.length);
+ expect(w.lstats.every((p) => p.toLowerCase().endsWith("pwsh.exe"))).toBe(true);
+ });
+
+ it("PATH 里只有 PowerShell 6:仍建议装 7", async () => {
+ const w = fakeWin({ exes: { "C:\\PS6\\pwsh.exe": "file" }, env: { ...ENV, PATH: "C:\\PS6" }, runVersion: async () => "PowerShell 6.2.7" });
+ const st = await new PwshProbe(w.deps).check();
+ expect(st).toMatchObject({ found: true, missing: true, version: "6.2.7" });
+ expect(pwshStatusLine(st)).toContain("6.2.7 版本较旧");
+ });
+
+ it("读不到版本号也算找到了", async () => {
+ const w = fakeWin({ exes: { [`${PF}\\PowerShell\\7\\pwsh.exe`]: "file" } });
+ const st = await new PwshProbe(w.deps).check();
+ expect(st).toMatchObject({ found: true, missing: false });
+ expect(st.version).toBeUndefined();
+ expect(pwshReportLine(st)).toContain("7(版本未知)");
+ });
+
+ it("结果缓存;重新检测时重新找(装好后点“重新检测”),宿主看到的路径随之更新", async () => {
+ const w = fakeWin();
+ const probe = new PwshProbe(w.deps);
+ expect(probe.snapshot()).toMatchObject({ applicable: true, checking: true });
+ expect(await probe.check()).toMatchObject({ missing: true });
+ const n = w.lstats.length;
+ expect(await probe.check()).toMatchObject({ missing: true });
+ expect(probe.snapshot()).toMatchObject({ missing: true });
+ expect(w.lstats.length).toBe(n);
+ expect(probe.cachedDshPath).toBeUndefined();
+ w.addExe(`${PF}\\PowerShell\\7\\pwsh.exe`);
+ expect(await probe.check(true)).toMatchObject({ found: true, missing: false });
+ expect(w.lstats.length).toBeGreaterThan(n);
+ expect(probe.cachedDshPath).toBe(`${PF}\\PowerShell\\7\\pwsh.exe`);
+ expect(probe.snapshot()).toMatchObject({ found: true, missing: false });
+ });
+
+ it("AMB_PWSH_FORCE=missing:任何平台都模拟“未安装”(截图、测试),不影响 DSH", async () => {
+ const w = fakeWin({ exes: { [`${PF}\\PowerShell\\7\\pwsh.exe`]: "file" } });
+ for (const platform of ["linux", "win32"] as const) {
+ const probe = new PwshProbe({ ...w.deps, platform, env: { ...ENV, AMB_PWSH_FORCE: "missing" } });
+ expect(probe.applicable).toBe(true);
+ expect(await probe.check()).toMatchObject({ applicable: true, found: false, missing: true, forced: true });
+ expect(await probe.dshPath()).toBeUndefined();
+ expect(probe.cachedDshPath).toBeUndefined();
+ }
+ expect(w.lstats).toEqual([]);
+ });
+
+ it("版本号:pwsh -Version 拉起时隐藏窗口、有超时", async () => {
+ spawned.length = 0;
+ const exe = `${APPS}\\pwsh.exe`;
+ expect(await readPwshVersion({ path: exe, source: "store" }, { readFile: async () => "{}" })).toBe("7.5.4");
+ expect(spawned).toHaveLength(1);
+ expect(spawned[0]).toMatchObject({ exe, args: ["-Version"], opts: { windowsHide: true } });
+ expect(spawned[0].opts.timeout).toBeGreaterThan(0);
+ expect(spawned[0].opts.timeout).toBeLessThanOrEqual(10_000);
+ expect(parsePwshVersion("PowerShell 7.6.0-preview.5\n")).toBe("7.6.0-preview.5");
+ expect(parsePwshVersion("garbage")).toBeUndefined();
+ });
+});
+
+describe("界面接口与诊断(AMB_PWSH_FORCE=missing)", () => {
+ let app: App;
+ let base = "";
+ const TOKEN = "ui-token-pwsh-0123456789";
+ const prev = process.env.AMB_PWSH_FORCE;
+ const api = async (p: string, init: { method?: string; body?: unknown } = {}) => {
+ const res = await fetch(`${base}/amb/api${p}`, {
+ method: init.method ?? "GET",
+ headers: { "x-amb-token": TOKEN, ...(init.body !== undefined ? { "content-type": "application/json" } : {}) },
+ body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
+ });
+ return { status: res.status, json: (await res.json()) as any };
+ };
+
+ beforeAll(async () => {
+ process.env.AMB_PWSH_FORCE = "missing";
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-pwsh-"));
+ const config = loadConfig({ dataDir, env: { AMB_MAGPIE_BASE_URL: "http://127.0.0.1:9/v1", AMB_UI_PORT: "0", AMB_UI_TOKEN: TOKEN, AMB_AGENT: "off", AMB_WEIXIN_API_BASE: "http://127.0.0.1:9" } });
+ app = new App(config, { printQrToTerminal: false });
+ await app.start();
+ base = app.web!.url.replace(/\/$/, "");
+ });
+ afterAll(async () => {
+ await app?.stop();
+ if (prev === undefined) delete process.env.AMB_PWSH_FORCE;
+ else process.env.AMB_PWSH_FORCE = prev;
+ });
+
+ it("GET /pwsh、诊断状态与复制的报告都带 PowerShell 状态", async () => {
+ const r = await api("/pwsh");
+ expect(r.status).toBe(200);
+ expect(r.json).toMatchObject({ applicable: true, found: false, missing: true, forced: true, dismissed: false });
+ expect((await api("/diagnostics")).json.pwsh).toMatchObject({ applicable: true, missing: true });
+ expect((await api("/diagnostics/report")).json.text).toContain("[PowerShell] 未安装 PowerShell 7");
+ });
+
+ it("重新检测;“不再提示”写进 config.json,重启后还在", async () => {
+ expect((await api("/pwsh/recheck", { method: "POST", body: {} })).json).toMatchObject({ missing: true, dismissed: false });
+ const r = await api("/pwsh", { method: "PUT", body: { dismissed: true } });
+ expect(r.status).toBe(200);
+ expect(r.json).toMatchObject({ missing: true, dismissed: true });
+ expect(JSON.parse(fs.readFileSync(path.join(app.config.dataDir, "config.json"), "utf8")).ui.pwshHintDismissed).toBe(true);
+ expect(loadConfig({ dataDir: app.config.dataDir, env: {} }).ui.pwshHintDismissed).toBe(true);
+ expect((await api("/pwsh")).json.dismissed).toBe(true);
+ expect((await api("/pwsh", { method: "DELETE" })).status).toBe(405);
+ });
+});
diff --git a/ui/components/pwsh-hint.js b/ui/components/pwsh-hint.js
new file mode 100644
index 0000000..9078f3b
--- /dev/null
+++ b/ui/components/pwsh-hint.js
@@ -0,0 +1,34 @@
+// "建议安装 PowerShell 7":一条安静的 .notice(淡底 + 图标 + 字,不描边),多一行等宽的安装命令和一排操作。
+// 放在对话空状态和设置 → 常规的顶部;只在 Windows 上、没有 PowerShell 7、没点过"不再提示"时出现。
+import { useState } from "preact/hooks";
+import { html, Icon, CopyButton } from "./ui.js";
+import { PWSH_INSTALL_URL, PWSH_WINGET, dismissPwsh, recheckPwsh, showPwshHint, usePwsh } from "../lib/pwsh.js";
+import { failed } from "../lib/store.js";
+
+export function PwshHint() {
+ const s = usePwsh();
+ const [busy, setBusy] = useState(false);
+ if (!showPwshHint(s)) return null;
+ const recheck = async () => {
+ setBusy(true);
+ try {
+ await recheckPwsh();
+ } catch (e) {
+ failed(e);
+ } finally {
+ setBusy(false);
+ }
+ };
+ return html`<div class="notice pwsh-hint" role="note" aria-label="建议安装 PowerShell 7">
+ <${Icon} name="info" size=${14} />
+ <div class="pwsh-body">
+ <p><b>建议安装 PowerShell 7</b>机器人执行命令现在用的是系统自带的 Windows PowerShell 5.1,每条可能要等二三十秒。装上 PowerShell 7,命令执行快得多,也更稳定。</p>
+ <div class="pwsh-cmd"><span class="t-meta">或在终端运行</span><code>${PWSH_WINGET}</code><${CopyButton} text=${PWSH_WINGET} label="复制安装命令" /></div>
+ <div class="pwsh-actions">
+ <a class="btn" href=${PWSH_INSTALL_URL} target="_blank" rel="noopener noreferrer">安装 PowerShell 7 ↗</a>
+ <button type="button" class="text" disabled=${busy} aria-busy=${busy || undefined} onClick=${recheck}>${busy ? "检测中…" : "重新检测"}</button>
+ <button type="button" class="text" onClick=${() => dismissPwsh().catch(failed)}>不再提示</button>
+ </div>
+ </div>
+ </div>`;
+}
diff --git a/ui/css/shell.css b/ui/css/shell.css
index 00fbd5b..2f5db7c 100644
--- a/ui/css/shell.css
+++ b/ui/css/shell.css
@@ -212,4 +212,19 @@ button.thread:active { background: var(--side-press); }
@media (max-width: 900px) {
:root { --side-w: 240px; }
}
+
+/* "建议安装 PowerShell 7"(components/pwsh-hint.js):一条 .notice(淡底 + 图标 + 字,不描边),文字之下多一行等宽的
+ 安装命令(就是一行字,不再套底)和一排操作。对话空状态与设置 → 常规共用 */
+.notice.pwsh-hint { align-items: flex-start; padding: var(--space-3); text-align: left; }
+.notice.pwsh-hint > .ic { margin-top: 3px; } /* 微调:图标对齐第一行文字(14px 图标 / 约 20px 行高) */
+.pwsh-body { flex: 1; min-width: 0; display: grid; gap: var(--space-2); }
+.pwsh-body b { display: block; margin-bottom: var(--space-0-5); font-weight: var(--fw-semibold); }
+.pwsh-cmd { display: flex; align-items: center; gap: var(--space-2); min-width: 0; }
+.pwsh-cmd .t-meta, .pwsh-cmd .copy { flex: none; }
+.pwsh-cmd code { min-width: 0; font-family: var(--code); font-size: var(--fs-xs); color: var(--fg); user-select: text; -webkit-user-select: text; overflow-wrap: anywhere; }
+.pwsh-cmd .copy { margin-left: calc(-1 * var(--space-1)); }
+.pwsh-actions { display: flex; align-items: center; gap: var(--ctl-gap); flex-wrap: wrap; }
+.chat-empty .pwsh-hint { width: min(100%, 560px); margin-top: var(--space-4); }
+.set-body > .pwsh-hint { margin-top: var(--space-6); }
+.set-body > .pwsh-hint + .list { margin-top: var(--space-3); }
}
diff --git a/ui/lib/pwsh.js b/ui/lib/pwsh.js
new file mode 100644
index 0000000..aba22bf
--- /dev/null
+++ b/ui/lib/pwsh.js
@@ -0,0 +1,43 @@
+// Windows:没有 PowerShell 7 时建议安装。检测结果放在一个全局 store 里,对话空状态、设置 → 常规、故障排查共用,
+// "重新检测""不再提示"立即同步到每一处。检测在后端(只看文件、不拉起进程),这里只读接口。
+import { useEffect } from "preact/hooks";
+import { api } from "./api.js";
+import { createStore, toast, useStore } from "./store.js";
+
+export const PWSH_INSTALL_URL = "https://aka.ms/PSWindows";
+export const PWSH_WINGET = "winget install --id Microsoft.PowerShell --source winget";
+
+export const pwshState = createStore(null);
+let loading = null;
+
+export function loadPwsh() {
+ loading ??= api("/pwsh")
+ .then((s) => pwshState.set(s))
+ .catch(() => {})
+ .finally(() => (loading = null));
+ return loading;
+}
+
+/** 重新检测:装好后点它,下一条消息起代理就用 PowerShell 7 */
+export async function recheckPwsh() {
+ const s = await api("/pwsh/recheck", { method: "POST", body: {} });
+ pwshState.set(s);
+ toast(s.missing ? "还没有检测到 PowerShell 7" : `已检测到 PowerShell ${s.version || "7"},下一条消息起生效`, s.missing ? "warn" : "ok");
+ return s;
+}
+
+/** 不再提示:记在 config.json(ui.pwshHintDismissed);故障排查里的状态行照常显示 */
+export async function dismissPwsh() {
+ pwshState.set(await api("/pwsh", { method: "PUT", body: { dismissed: true } }));
+}
+
+export function usePwsh() {
+ const s = useStore(pwshState);
+ useEffect(() => {
+ if (!pwshState.get()) loadPwsh();
+ }, []);
+ return s;
+}
+
+/** 要不要显示提示:Windows(或模拟)、没有 PowerShell 7、没点过"不再提示" */
+export const showPwshHint = (s) => !!(s && s.applicable && s.missing && !s.dismissed);
diff --git a/ui/screens/chat.js b/ui/screens/chat.js
index 15c599c..64a8b39 100644
--- a/ui/screens/chat.js
+++ b/ui/screens/chat.js
@@ -5,6 +5,7 @@ import { html, Icon, IconButton, CopyButton, Menu, Popover, Badge, Notice, Skele
import { BotAvatar } from "../components/avatar.js";
import { Markdown, Linkified } from "../components/markdown.js";
import { ModelPicker, shortModel, sameModel } from "../components/model-picker.js";
+import { PwshHint } from "../components/pwsh-hint.js";
import { api, streamChat } from "../lib/api.js";
import { confirmSheet, failed, saved } from "../lib/store.js";
import { fmtSep, fmtClock, fmtDur } from "../lib/format.js";
@@ -456,6 +457,7 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultMode
<button type="button" class="chip" onClick=${() => send("你能帮我做什么?")}>你能帮我做什么?</button>
<button type="button" class="chip" onClick=${() => send("/help")}>/help 查看命令</button>
</div>
+ <${PwshHint} />
</div>`}
${rows}
</div>
diff --git a/ui/screens/settings.js b/ui/screens/settings.js
index 8728741..0123ee8 100644
--- a/ui/screens/settings.js
+++ b/ui/screens/settings.js
@@ -11,6 +11,7 @@ import { MF_CONSOLE, MF_DOCS, MF_TOPUP, usd } from "../lib/links.js";
import { useStore, confirmSheet, failed, saved } from "../lib/store.js";
import { themeMode, setThemeMode } from "../lib/theme.js";
import { TroubleshootPane } from "./troubleshoot.js";
+import { PwshHint } from "../components/pwsh-hint.js";
export const TABS = [
["general", "常规", "sliders"],
@@ -259,7 +260,7 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, onTab, focusRow,
{ tab: "about", id: "diagnostics", name: "诊断信息", sub: status ? `内置模型网关 · ${GATEWAY[status.gateway.state] || status.gateway.state}${status.gateway.restarts ? ` · 重启 ${status.gateway.restarts} 次` : ""}${status.gateway.lastError ? ` · ${status.gateway.lastError}` : ""}` : "", keys: "网关 gateway magpie",
ctl: html`<button type="button" class="text" onClick=${() => onTab?.("troubleshoot")}>故障排查</button>` },
// 故障排查页是单独的面板(troubleshoot.js),这一行只给搜索用:搜"日志""测试模型"时能找到入口
- { tab: "troubleshoot", id: "troubleshoot", name: "故障排查", sub: "模型网关与代理进程的状态、测试模型、测试代理、最近日志、复制诊断信息", keys: "日志 log 测试 test 代理 agent 卡住 转圈 诊断 diagnostics 重启",
+ { tab: "troubleshoot", id: "troubleshoot", name: "故障排查", sub: "模型网关与代理进程的状态、测试模型、测试代理、最近日志、复制诊断信息", keys: "日志 log 测试 test 代理 agent 卡住 转圈 诊断 diagnostics 重启 PowerShell pwsh 命令慢",
ctl: html`<button type="button" class="text" onClick=${() => { setQ(""); onTab?.("troubleshoot"); }}>打开</button>` },
{ tab: "about", id: "links", name: "Modelflare", sub: "官网与文档",
ctl: html`<a class="text" href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">modelflare.dev ↗</a><a class="text" href=${MF_DOCS} target="_blank" rel="noopener noreferrer">文档 ↗</a>` },
@@ -276,6 +277,7 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, onTab, focusRow,
<div class="set-body">
${!s && html`<div class="list"><div class="row"><${Skeleton} w="40%" /></div><div class="row"><${Skeleton} w="55%" /></div></div>`}
${s && !shown.length && html`<p class="set-none">没有匹配的设置</p>`}
+ ${s && !needle && tab === "general" && html`<${PwshHint} />`}
${s && !needle && tab === "troubleshoot" ? html`<${TroubleshootPane} bots=${bots} desktop=${desktop} />` : parts.map(([label, list]) => html`${label && html`<div class="set-part">${label}</div>`}
<div class="list">${list.map((r) => html`<${Row} key=${r.id} id=${r.id} name=${r.name} sub=${r.sub} title=${r.title || r.sub} flash=${flash === r.id}>${r.ctl}<//>`)}</div>`)}
</div>
diff --git a/ui/screens/troubleshoot.js b/ui/screens/troubleshoot.js
index 55dfe82..c9fb134 100644
--- a/ui/screens/troubleshoot.js
+++ b/ui/screens/troubleshoot.js
@@ -4,6 +4,7 @@ import { useEffect, useRef, useState } from "preact/hooks";
import { html, Button, CopyButton, Icon, Skeleton } from "../components/ui.js";
import { api } from "../lib/api.js";
import { failed, toast } from "../lib/store.js";
+import { PWSH_INSTALL_URL, PWSH_WINGET, recheckPwsh } from "../lib/pwsh.js";
const GATEWAY = { running: ["运行中", "ok"], starting: ["启动中", "warn"], restarting: ["重启中", "warn"], failed: ["失败", "err"], stopped: ["已停止", "off"], external: ["外部端点", "ok"] };
const HOST = { running: ["运行中", "ok"], starting: ["启动中", "warn"], backoff: ["等待重试", "warn"], error: ["已暂停", "err"], stopped: ["未启动", "off"] };
@@ -44,6 +45,28 @@ const Verdict = ({ ok }) => html`<span class="ts-state"><span class=${`dot ${ok
const ms = (v) => (v === undefined || v === null ? "" : v >= 10_000 ? `${(v / 1000).toFixed(1)} 秒` : `${v} ms`);
const exitText = (e) => (e ? `上次退出 code=${e.code ?? "-"}${e.signal ? ` signal=${e.signal}` : ""}` : "");
const join = (...a) => a.filter(Boolean).join(" · ");
+const PS_SOURCE = { "program-files": "安装目录", path: "PATH", preview: "预览版", store: "Microsoft Store" };
+
+/** PowerShell(只在 Windows 上):版本或"未安装";没有 7 时下面多一行安装命令和下载链接 */
+function PwshRows({ ps, busy, onRecheck }) {
+ if (!ps || !ps.applicable) return null;
+ const [text, kind] = ps.checking ? ["检测中", ""] : !ps.missing ? [ps.version || "7", "ok"] : ps.found && ps.version ? [ps.version, "warn"] : ["未安装", "warn"];
+ const sub = ps.checking
+ ? "正在找 PowerShell 7"
+ : !ps.missing
+ ? join(ps.path, PS_SOURCE[ps.source], "代理用它执行命令")
+ : ps.found
+ ? join(ps.path, "版本较旧:装上 PowerShell 7,命令执行快得多,也更稳定")
+ : "代理执行命令用的是系统自带的 Windows PowerShell 5.1,每条可能要二三十秒。装上 PowerShell 7,命令执行快得多,也更稳定";
+ return html`<${Row} id="pwsh" name="PowerShell" sub=${sub}>
+ <span class="ts-state"><span class=${`dot ${kind}`}></span>${text}</span>
+ <button type="button" class="text" disabled=${!!busy} aria-busy=${busy === "pwsh" || undefined} onClick=${onRecheck}>${busy === "pwsh" ? "检测中…" : "重新检测"}</button>
+ <//>
+ ${ps.missing && html`<${Row} compact id="pwsh-install" name="安装 PowerShell 7" sub=${PWSH_WINGET} mono>
+ <${CopyButton} text=${PWSH_WINGET} label="复制安装命令" />
+ <a class="btn sm" href=${PWSH_INSTALL_URL} target="_blank" rel="noopener noreferrer">下载安装 ↗</a>
+ <//>`}`;
+}
function ProbeRow({ name, p }) {
if (!p) return null;
@@ -107,6 +130,7 @@ export function TroubleshootPane({ bots, desktop }) {
const r = await api("/diagnostics/restart-agent", { method: "POST", body: {} });
toast(r.restarted.length ? "代理进程已重启" : "代理进程还没有启动,下一条消息时启动");
});
+ const recheckPs = () => run("pwsh", recheckPwsh);
const copy = () =>
run("copy", async () => {
const { text } = await api("/diagnostics/report?lines=200");
@@ -133,6 +157,7 @@ export function TroubleshootPane({ bots, desktop }) {
<${State} map=${HOST} s=${h.state} />
<//>`)}
${tail.length > 0 && html`<div class="row-edit ts-tail"><span class="t-label">代理进程输出(stderr 最后 ${tail.length} 行)</span><pre class="ts-mono">${tail.join("\n")}</pre></div>`}
+ <${PwshRows} ps=${st.pwsh} busy=${busy} onRecheck=${recheckPs} />
<${Row} id="version" name="版本" sub=${join(st.os, st.electron && `Electron ${st.electron}`, `Node ${st.node}`)}>
<span class="val">${st.version} · ${st.platform} ${st.arch}</span>
<//>