diff --git a/.prettierignore b/.prettierignore index 3c33704..2dcef2a 100644 --- a/.prettierignore +++ b/.prettierignore @@ -58,3 +58,8 @@ plugins/openclaw-weixin/ # Top-level legal / generated text LICENSE NOTICE + +# Private/generated Goals acceptance artifacts +benchmarks/harbor/.venv/ +benchmarks/harbor/.work/ +benchmarks/harbor/reports/ diff --git a/README.md b/README.md index 8eed83b..6111a7f 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ MicroClaw is designed to remove the usual Windows setup friction around OpenClaw - **Only the LLM is bring-your-own**: the user supplies the model endpoint, API key, and model name; the rest of the stack is installed and configured by MicroClaw - **Fast path on first launch**: if no provider is configured, the app opens a setup wizard that asks only for model credentials; if `MODEL_*` values already exist in `.env`, MicroClaw can auto-configure them - **Recommended tasks on day one**: the home screen ships with starter task cards and prompt suggestions so users can begin with concrete tasks instead of a blank chat box +- **Personal goals per agent**: add, edit and complete persistent todos in chat or the sidebar's Goals page. Choose a category to create a goal; reminders are optional. One-time reminders use ordinary messages while the desktop app is running. See [Todo behavior and delivery](plugins/microclaw-todos/README.md). - **Preloaded capability surface**: bundled OpenClaw skills plus 6 managed skills are included in the default Windows experience; availability depends on each skill's platform, dependencies and configuration, and specialist agents add their own skills on demand ### Built-In Trust diff --git a/README.zh-CN.md b/README.zh-CN.md index 5ca4bff..5e6a448 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -27,6 +27,7 @@ MicroClaw 的设计重点,是把 OpenClaw 在 Windows 上常见的安装和配 - **唯一需要用户自备的是 LLM**:用户提供模型地址、API Key 和模型名,其余栈内组件由 MicroClaw 安装并连接起来 - **首启路径很短**:如果还没有模型配置,应用只会引导填写模型凭据;如果 `.env` 里已有 `MODEL_*`,MicroClaw 还可以自动配置 - **首屏自带推荐任务**:首页不是空白输入框,而是预置了任务卡片和提示词建议,安装后就能直接开始做事 +- **每个助手独立目标**:通过聊天或侧栏「目标」添加、编辑和完成持久事项。页面提供简洁的跟进列表和分类创建入口,单次文字提醒可按需设置。行为与投递范围见 [Todo 说明](plugins/microclaw-todos/README.md)。 - **能力预装到位**:默认包含 OpenClaw 内置技能及 6 个托管技能;实际可用性取决于各技能的平台、依赖和配置,专家智能体按需安装自己的专属技能 ### 内建信任 diff --git a/benchmarks/harbor/.gitignore b/benchmarks/harbor/.gitignore new file mode 100644 index 0000000..cae1a9e --- /dev/null +++ b/benchmarks/harbor/.gitignore @@ -0,0 +1,6 @@ +.venv/ +.work/ +reports/ +node_modules/ +__pycache__/ +*.local.json diff --git a/benchmarks/harbor/README.md b/benchmarks/harbor/README.md new file mode 100644 index 0000000..715b83e --- /dev/null +++ b/benchmarks/harbor/README.md @@ -0,0 +1,67 @@ +# Goals Harbor acceptance + +This standalone suite contains only two Goals tasks. Harbor 0.25.0 runs a fixed UI oracle against the real Windows desktop; the model inside MicroClaw performs the actions. The verifier independently checks native tool provenance, the trial's persisted Todo state, session/agent identity, visible results, and graceful cleanup. + +| Task | Coverage | +| --- | --- | +| `goals-chat-lifecycle` (G01) | Create, list, rename, complete and delete the same Todo through natural-language chat. | +| `goals-agent-isolation` (G03) | A new conversation of the same agent sees its Todo; another agent sees only its own and cannot modify the foreign ID. | + +The suite requires only a packaged Goals build and model credentials. Shared support handles disposable profiles, credential protection, UI evidence and standard Harbor reward files. The Windows adapter is not a security sandbox. + +## Setup + +Build a complete packaged desktop directory containing the Goals plugin: + +```powershell +npm run pack --prefix desktop +.\benchmarks\harbor\run.ps1 -Setup -Check +``` + +The default configuration is `%LOCALAPPDATA%\MicroClawBench\goals.json`, outside the repository. `-Check` performs no model call. Fill the selected model configuration and point `appPath` at the new packaged executable. Both tasks require an actual model; there is no UI-only substitute. + +```json +{ + "schema": 1, + "appPath": "C:\\path\\to\\win-unpacked\\MicroClawDesktop.exe", + "model": { + "provider": "openai-compatible", + "baseUrl": "https://your-model-endpoint.example/v1", + "id": "your-model-id", + "apiKey": "enter-locally-then-run-check" + }, + "evidence": { "privacy": "local-details" } +} +``` + +After entering a key, immediately run `-Check`: the input is verified and replaced by a reference to Windows DPAPI CurrentUser ciphertext. No plaintext backup is created. Do not commit or share the configuration, credential cache, or private profile. Existing configuration is never overwritten by initialization. + +An existing GitHub Copilot test cache is also supported with `model.provider="github-copilot"`, `model.id`, absolute `model.credentialCache`, and `model.runtimeDir` pointing to the pinned OpenClaw 2026.10.10 package. The credential helper restores only that provider into the new test profile. A cache's existence is not proof that the service will accept it. + +## Run + +```powershell +.\benchmarks\harbor\run.ps1 -Task goals-chat-lifecycle -Config 'C:\private\goals.json' -Check +.\benchmarks\harbor\run.ps1 -Task goals-chat-lifecycle -Config 'C:\private\goals.json' +.\benchmarks\harbor\run.ps1 -Task goals-agent-isolation -Config 'C:\private\goals.json' +``` + +Run one desktop trial at a time. Each trial uses a unique marker and a fresh `MICROCLAW_TEST_PROFILE`; it does not import daily todos, chats, or messaging accounts. All mutations go through visible UI or the tested model's Todo tools. Read-only native catalog/history and filesystem observations provide independent evidence; the driver never repairs the model's work by writing the Todo store or invoking mutation RPCs. + +The state parser and verifier are independent of the product's TodoStore. They reject missing/stale tool results, wrong agent/session identity, duplicate items, unsolicited reminders, foreign disclosure, unexpected state changes and forced cleanup. A verbal claim alone cannot pass. The bounded history projection is requested explicitly for evidence; ordinary chat history reads retain their default limits. + +Reports are written under `reports///`, with verifier `result.json` and `reward.txt`, a screenshot gallery and conversation evidence. Reward is 1 only when all required checkpoints pass. `BLOCKED` prerequisites receive 0 and remain distinct from a product failure. Historical failures are retained. If a trial fails or its processes cannot be confirmed stopped, its `.work` profile remains private for diagnosis. + +G01/G03 do not cover scheduling accuracy, restart recovery, or real phone delivery. Runtime/unit tests cover the deterministic reminder contract separately. Real phone checks require a dedicated account/device and separate authorization. + +## Framework tests + +```powershell +npm ci --ignore-scripts --prefix benchmarks/harbor +npm test --prefix benchmarks/harbor +Push-Location benchmarks/harbor +.\.venv\Scripts\python.exe -X utf8 -m unittest discover -s tests -p test_environment.py +Pop-Location +``` + +Task definitions follow Harbor schema 1.4 and explicitly register in `runtime/cases.mjs` and the Windows environment allowlist. Additions must provide their own expected state and verifier; absent implementations are not successful runs. diff --git a/benchmarks/harbor/microclaw_harbor/__init__.py b/benchmarks/harbor/microclaw_harbor/__init__.py new file mode 100644 index 0000000..094a8fb --- /dev/null +++ b/benchmarks/harbor/microclaw_harbor/__init__.py @@ -0,0 +1 @@ +"""MicroClaw's trusted local Windows task adapter for Harbor.""" diff --git a/benchmarks/harbor/microclaw_harbor/environment.py b/benchmarks/harbor/microclaw_harbor/environment.py new file mode 100644 index 0000000..b469306 --- /dev/null +++ b/benchmarks/harbor/microclaw_harbor/environment.py @@ -0,0 +1,218 @@ +"""Runs reviewed desktop tasks in disposable profiles on the interactive Windows host. + +This is deliberately not a security sandbox or an arbitrary-command environment. +Only Harbor's oracle/verifier batch entry points and reward cleanup are accepted. +Virtual C:\\ paths never address the host drive root. +""" + +import asyncio +import json +import os +import re +import shutil +import tempfile +from pathlib import Path, PureWindowsPath + +from harbor.environments.base import BaseEnvironment, ExecResult +from harbor.environments.capabilities import EnvironmentCapabilities + +ROOT = Path(__file__).resolve().parents[1] + + +class WindowsDesktop(BaseEnvironment): + def __init__(self, *args, config_path=None, **kwargs): + self.config_path = ( + str(Path(config_path).resolve()) + if config_path + else str( + Path(os.environ.get("LOCALAPPDATA", Path.home())) / "MicroClawBench" / "goals.json" + ) + ) + self.root = None + self.process = None + super().__init__(*args, **kwargs) + + @staticmethod + def type(): + return "microclaw-windows-desktop" + + @property + def capabilities(self): + return EnvironmentCapabilities(windows=True) + + def _validate_definition(self): + self._task_name() + + def _task_name(self): + definition = self.environment_dir.resolve() + if ( + definition.parent.parent != ROOT / "tasks" + or definition.name != "environment" + or definition.parent.name + not in { + "goals-chat-lifecycle", + "goals-agent-isolation", + } + or not (definition / "desktop.json").is_file() + ): + raise ValueError("Only reviewed MicroClaw desktop task definitions are supported") + return definition.parent.name + + def local_path(self, value): + virtual = PureWindowsPath(str(value)) + if virtual.drive.lower() != "c:" or not virtual.is_absolute() or ".." in virtual.parts: + raise ValueError("Expected an absolute Harbor virtual C: path") + relative = virtual.parts[1:] + if not relative or relative[0].lower() not in {"logs", "tests", "solution", "workdir"}: + raise ValueError("Unsupported Harbor virtual directory") + target = self.root.joinpath(*relative).resolve() + if not target.is_relative_to(self.root) or target == self.root: + raise ValueError("Path escapes this trial") + return target + + async def start(self, force_build=False): + if os.name != "nt": + raise RuntimeError("An interactive Windows desktop is required") + work = ROOT / ".work" + work.mkdir(exist_ok=True) + self.root = Path(tempfile.mkdtemp(prefix="trial-", dir=work)).resolve() + for name in ( + "logs/agent", + "logs/verifier", + "logs/artifacts", + "tests", + "solution", + "workdir", + ): + (self.root / name).mkdir(parents=True, exist_ok=True) + + async def _stop_process(self): + if self.process and self.process.returncode is None: + # Only the process created by this trial, including its owned desktop/Gateway. + killer = await asyncio.create_subprocess_exec( + "taskkill.exe", + "/PID", + str(self.process.pid), + "/T", + "/F", + stdout=asyncio.subprocess.DEVNULL, + stderr=asyncio.subprocess.DEVNULL, + ) + await killer.wait() + await self.process.wait() + + async def stop(self, delete=True): + await self._stop_process() + if delete and self.root: + target = self.root.resolve() + if target.parent != (ROOT / ".work").resolve() or not target.name.startswith("trial-"): + raise ValueError("Invalid trial cleanup path") + if (target / "workdir" / "profile").exists(): + try: + evidence = json.loads( + (target / "logs/agent/evidence.json").read_text(encoding="utf-8") + ) + cleaned = any( + p.get("name") == "cleanup" and p.get("ok") is True + for p in evidence.get("checkpoints", []) + ) + except (OSError, ValueError): + cleaned = False + if not cleaned: + raise RuntimeError( + f"Desktop cleanup was not confirmed; private profile retained at {target}" + ) + try: + verdict = json.loads( + (target / "logs/verifier/result.json").read_text(encoding="utf-8") + ) + except (OSError, ValueError): + verdict = {} + if evidence.get("status") != "COMPLETE" or verdict.get("status") != "PASS": + # Preserve failed trial artifacts privately without preventing the next serial run. + return + shutil.rmtree("\\\\?\\" + str(target) if os.name == "nt" else target) + + async def upload_file(self, source_path, target_path): + target = self.local_path(target_path) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source_path, target) + + async def upload_dir(self, source_dir, target_dir): + shutil.copytree(source_dir, self.local_path(target_dir), dirs_exist_ok=True) + + async def download_file(self, source_path, target_path): + Path(target_path).parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(self.local_path(source_path), target_path) + + async def download_dir(self, source_dir, target_dir): + shutil.copytree(self.local_path(source_dir), target_dir, dirs_exist_ok=True) + + async def is_dir(self, path, user=None): + return self.local_path(path).is_dir() + + async def is_file(self, path, user=None): + return self.local_path(path).is_file() + + async def reset_dirs(self, *, remove_dirs, create_dirs, chmod_dirs=None): + for directory in remove_dirs: + target = self.local_path(directory) + if target.exists(): + shutil.rmtree(target) + return await self.ensure_dirs(create_dirs) + + async def ensure_dirs(self, dirs, *, chmod=True): + for directory in dirs: + self.local_path(directory).mkdir(parents=True, exist_ok=True) + return ExecResult(return_code=0) + + async def empty_dirs(self, dirs, *, chmod=True): + return await self.reset_dirs(remove_dirs=dirs, create_dirs=dirs) + + async def exec(self, command, cwd=None, env=None, timeout_sec=None, user=None): + if user is not None: + raise ValueError("User switching is unsupported") + # Harbor removes old reward files before invoking the verifier. Do it natively. + if "del /F /Q" in command and "reward.txt" in command and "reward.json" in command: + for name in ("reward.txt", "reward.json"): + (self.root / "logs" / "verifier" / name).unlink(missing_ok=True) + return ExecResult(return_code=0) + matches = re.findall(r"C:[\\/](?:solution[\\/]solve|tests[\\/]test)\.bat", command, re.I) + if len(matches) != 1: + raise ValueError("This adapter only runs the task's solve.bat and test.bat") + script = self.local_path(matches[0]) + process_env = dict(os.environ) + process_env.update(self._merge_env(env) or {}) + process_env.update( + { + "MICROCLAW_BENCH_ROOT": str(ROOT), + "MICROCLAW_BENCH_WORK": str(self.root / "workdir"), + "MICROCLAW_BENCH_CONFIG": self.config_path, + "MICROCLAW_BENCH_TASK": self._task_name(), + "MICROCLAW_BENCH_EVIDENCE": str(self.root / "logs" / "agent" / "evidence.json"), + "MICROCLAW_BENCH_REPORT_DIR": str(self.trial_paths.agent_dir.resolve()), + "MICROCLAW_BENCH_REWARD": str(self.root / "logs" / "verifier"), + } + ) + self.process = await asyncio.create_subprocess_exec( + "cmd.exe", + "/d", + "/c", + str(script), + cwd=self.local_path(cwd) if cwd else self.root / "workdir", + env=process_env, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + try: + stdout, stderr = await asyncio.wait_for(self.process.communicate(), timeout_sec) + except (TimeoutError, asyncio.CancelledError): + await self._stop_process() + raise + # Scripts emit only machine statuses. Never copy application stdout or secrets here. + output = stdout.decode("utf-8", errors="replace") + errors = stderr.decode("utf-8", errors="replace") + log_matches = re.findall(r"C:[\\/]logs[\\/](?:agent|verifier)[\\/][\w.-]+", command, re.I) + if log_matches: + self.local_path(log_matches[0]).write_text(output + errors, encoding="utf-8") + return ExecResult(stdout=output, stderr=errors, return_code=self.process.returncode) diff --git a/benchmarks/harbor/package-lock.json b/benchmarks/harbor/package-lock.json new file mode 100644 index 0000000..94254c5 --- /dev/null +++ b/benchmarks/harbor/package-lock.json @@ -0,0 +1,53 @@ +{ + "name": "microclaw-harbor-bench", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "microclaw-harbor-bench", + "dependencies": { + "playwright": "1.64.1" + }, + "devDependencies": { + "pngjs": "7.0.0" + } + }, + "node_modules/playwright": { + "version": "1.64.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/playwright/-/playwright-1.64.1.tgz", + "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.64.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.64.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/pngjs": { + "version": "7.0.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/pngjs/-/pngjs-7.0.0.tgz", + "integrity": "sha1-qLdEYCDrvGrHOdtsVBWmXRcJDiY=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.19.0" + } + } + } +} diff --git a/benchmarks/harbor/package.json b/benchmarks/harbor/package.json new file mode 100644 index 0000000..d401b1a --- /dev/null +++ b/benchmarks/harbor/package.json @@ -0,0 +1,16 @@ +{ + "name": "microclaw-harbor-bench", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/*.test.mjs support/credentials/tests/*.test.mjs", + "check": "node runtime/config.mjs check", + "init": "node runtime/config.mjs init" + }, + "dependencies": { + "playwright": "1.64.1" + }, + "devDependencies": { + "pngjs": "7.0.0" + } +} diff --git a/benchmarks/harbor/requirements.txt b/benchmarks/harbor/requirements.txt new file mode 100644 index 0000000..9927e60 --- /dev/null +++ b/benchmarks/harbor/requirements.txt @@ -0,0 +1 @@ +harbor==0.25.0 diff --git a/benchmarks/harbor/run.ps1 b/benchmarks/harbor/run.ps1 new file mode 100644 index 0000000..4978332 --- /dev/null +++ b/benchmarks/harbor/run.ps1 @@ -0,0 +1,40 @@ +#Requires -Version 5.1 +[CmdletBinding()] +param( + [switch]$Setup, + [switch]$Check, + [ValidateSet('goals-chat-lifecycle', 'goals-agent-isolation')] + [string]$Task = 'goals-chat-lifecycle', + [string]$Config = (Join-Path $env:LOCALAPPDATA 'MicroClawBench/goals.json'), + [string]$PythonExe +) +$ErrorActionPreference = 'Stop' +$taskPath = Join-Path $PSScriptRoot "tasks/$Task" +Push-Location $PSScriptRoot +try { + if (-not $PythonExe) { $PythonExe = Join-Path $PSScriptRoot '.venv/Scripts/python.exe' } + if ($Setup) { + if (-not (Test-Path -LiteralPath $PythonExe)) { + & python -m venv (Join-Path $PSScriptRoot '.venv') + if ($LASTEXITCODE -ne 0) { throw 'Python environment creation failed.' } + } + & $PythonExe -m pip install -r requirements.txt + if ($LASTEXITCODE -ne 0) { throw 'Harbor installation failed.' } + & npm.cmd ci --ignore-scripts --no-audit --no-fund + if ($LASTEXITCODE -ne 0) { throw 'Playwright installation failed.' } + } + & node runtime/config.mjs init $Config $Task + if ($LASTEXITCODE -ne 0) { throw 'Configuration initialization failed.' } + & node runtime/config.mjs protect $Config + if ($LASTEXITCODE -ne 0) { throw 'Credential protection failed; the benchmark will not start.' } + if ($Check) { + & node runtime/config.mjs check $Config $Task + exit $LASTEXITCODE + } + if (-not (Test-Path -LiteralPath $PythonExe)) { throw 'Run with -Setup first.' } + & $PythonExe -X utf8 -m harbor.cli.main run --path $taskPath --agent oracle ` + --env microclaw_harbor.environment:WindowsDesktop ` + --environment-kwarg "config_path=$Config" --n-concurrent 1 ` + --jobs-dir (Join-Path $PSScriptRoot 'reports') + exit $LASTEXITCODE +} finally { Pop-Location } diff --git a/benchmarks/harbor/runtime/bounded.mjs b/benchmarks/harbor/runtime/bounded.mjs new file mode 100644 index 0000000..8a9e4a0 --- /dev/null +++ b/benchmarks/harbor/runtime/bounded.mjs @@ -0,0 +1,14 @@ +/** Bound read-only automation requests whose underlying API has no timeout option. */ +export async function bounded(operation, milliseconds, code = "AUTOMATION_TIMEOUT") { + let timer; + try { + return await Promise.race([ + operation, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(code)), milliseconds); + }), + ]); + } finally { + clearTimeout(timer); + } +} diff --git a/benchmarks/harbor/runtime/cases.mjs b/benchmarks/harbor/runtime/cases.mjs new file mode 100644 index 0000000..301ac6b --- /dev/null +++ b/benchmarks/harbor/runtime/cases.mjs @@ -0,0 +1,8 @@ +import lifecycle from "../tasks/goals-chat-lifecycle/case.mjs"; +import isolation from "../tasks/goals-agent-isolation/case.mjs"; +export const defaultTask = lifecycle.id; +export const cases = Object.freeze({ [lifecycle.id]: lifecycle, [isolation.id]: isolation }); +export function getCase(id = defaultTask) { + if (!Object.hasOwn(cases, id)) throw new Error("Unknown Harbor Goals task"); + return cases[id]; +} diff --git a/benchmarks/harbor/runtime/config.mjs b/benchmarks/harbor/runtime/config.mjs new file mode 100644 index 0000000..1ea2248 --- /dev/null +++ b/benchmarks/harbor/runtime/config.mjs @@ -0,0 +1,188 @@ +import fs from "node:fs/promises"; +import path from "node:path"; +import os from "node:os"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { getCase, defaultTask } from "./cases.mjs"; +import { protectConfig, resolveCredentials } from "./credentials.mjs"; + +export const benchRoot = fileURLToPath(new URL("../", import.meta.url)); +export const repoRoot = path.resolve(benchRoot, "../.."); +export const defaultConfigPath = path.join( + process.env.LOCALAPPDATA || os.homedir(), + "MicroClawBench", + "goals.json", +); +export function configTemplate() { + return { + schema: 1, + instructions: + "Configure a packaged MicroClaw build with Goals and a test model. Run check after entering credentials to protect them with Windows DPAPI. Keep this file outside the repository.", + appPath: path.join(repoRoot, "desktop/release/win-unpacked/MicroClawDesktop.exe"), + model: { provider: "openai-compatible", baseUrl: "", id: "", apiKey: "" }, + evidence: { privacy: "local-details" }, + }; +} +function selected(selection = defaultTask) { + const value = typeof selection === "string" ? { task: selection } : selection; + const task = getCase(value.task ?? defaultTask); + return { task, scenario: value.scenario }; +} +export function validateConfig(config, selection = defaultTask) { + const { task, scenario } = selected(selection); + if (config?.schema !== 1) return ["schema"]; + const missing = [...task.configuration(config)]; + if (scenario) missing.push("scenario.unsupported"); + if (config.uiOnly === true) missing.push("model.inference-required"); + if ( + config.evidence?.privacy !== undefined && + !["redacted", "local-details"].includes(config.evidence.privacy) + ) + missing.push("evidence.privacy"); + const provider = config.model?.provider ?? "openai-compatible"; + if (!["openai-compatible", "github-copilot"].includes(provider)) missing.push("model.provider"); + for (const [name, value] of [ + ["appPath", config.appPath], + ["model.id", config.model?.id], + ...(provider === "github-copilot" + ? [ + ["model.credentialCache", config.model?.credentialCache], + ["model.runtimeDir", config.model?.runtimeDir], + ] + : [ + ["model.baseUrl", config.model?.baseUrl], + ["model.apiKey", config.model?.apiKey], + ]), + ]) { + if (typeof value !== "string" || !value.trim()) missing.push(name); + } + if (typeof config.appPath === "string" && config.appPath && !path.isAbsolute(config.appPath)) + missing.push("appPath.absolute"); + if (provider === "github-copilot") { + if ( + typeof config.model?.id === "string" && + !/^[a-zA-Z0-9][a-zA-Z0-9._:-]*$/.test(config.model.id) + ) + missing.push("model.id.valid"); + for (const key of ["credentialCache", "runtimeDir"]) + if (config.model?.[key] && !path.isAbsolute(config.model[key])) + missing.push(`model.${key}.absolute`); + } else if (config.model?.baseUrl) { + try { + const url = new URL(config.model.baseUrl); + if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) + missing.push("model.baseUrl.valid"); + } catch { + missing.push("model.baseUrl.valid"); + } + } + return missing; +} +export async function readConfig(filename = defaultConfigPath, selection = defaultTask) { + selected(selection); + if (!path.isAbsolute(filename)) return { missing: ["config.absolute-path"] }; + const resolved = await fs.realpath(filename).catch(() => null); + if (!resolved) return { missing: ["config.file"] }; + const relative = path.relative(repoRoot, resolved); + if (!relative || (!relative.startsWith(".." + path.sep) && !path.isAbsolute(relative))) + return { missing: ["config.must-be-outside-repository"] }; + let config; + try { + config = JSON.parse(await fs.readFile(resolved, "utf8")); + } catch { + return { missing: ["config.valid-json"] }; + } + if (!config || typeof config !== "object" || Array.isArray(config)) + return { missing: ["schema"] }; + try { + config = await resolveCredentials(config, resolved); + } catch { + return { missing: ["credentialStore.unavailable"] }; + } + const missing = validateConfig(config, selection); + if (config.model?.provider === "github-copilot") { + if ( + config.model.credentialCache && + !(await fs + .stat(config.model.credentialCache) + .then((s) => s.isFile()) + .catch(() => false)) + ) + missing.push("model.credentialCache.exists"); + if (config.model.runtimeDir) { + const meta = await fs + .readFile(path.join(config.model.runtimeDir, "package.json"), "utf8") + .then(JSON.parse) + .catch(() => null); + if (meta?.name !== "openclaw" || meta.version !== "2026.10.10") + missing.push("model.runtimeDir.compatible"); + } + } + if ( + config.appPath && + !(await fs + .stat(config.appPath) + .then((s) => s.isFile()) + .catch(() => false)) + ) + missing.push("appPath.exists"); + if (config.appPath && !missing.some((name) => name.startsWith("appPath"))) { + const resources = path.join(path.dirname(config.appPath), "resources"); + const archive = await fs.readFile(path.join(resources, "app.asar")).catch(() => null); + if (!archive?.includes(Buffer.from("microclaw.test-profile.v1"))) + missing.push("appPath.test-profile-support"); + const manifest = await fs + .readFile(path.join(resources, "microclaw-todos/openclaw.plugin.json"), "utf8") + .then(JSON.parse) + .catch(() => null); + if ( + !archive?.includes(Buffer.from("todos:list")) || + !archive?.includes(Buffer.from("microclaw.todos.")) || + manifest?.id !== "microclaw-todos" || + !["todo_list", "todo_add", "todo_update", "todo_delete"].every((name) => + manifest.contracts?.tools?.includes(name), + ) + ) + missing.push("appPath.goals-support"); + } + return { config, missing }; +} +export async function initializeConfig(filename = defaultConfigPath, taskId = defaultTask) { + getCase(taskId); + const relative = path.relative(repoRoot, path.resolve(filename)); + if (!relative || (!relative.startsWith(".." + path.sep) && !path.isAbsolute(relative))) + throw new Error("Credential file must be outside the repository"); + await fs.mkdir(path.dirname(filename), { recursive: true }); + try { + await fs.writeFile(filename, JSON.stringify(configTemplate(), null, 2) + "\n", { + flag: "wx", + mode: 0o600, + }); + } catch (error) { + if (error.code !== "EEXIST") throw error; + } + return filename; +} +async function cli() { + const filename = process.argv[3] || defaultConfigPath; + const task = process.argv[4] || defaultTask; + if (process.argv[2] === "init") + process.stdout.write((await initializeConfig(filename, task)) + "\n"); + else if (process.argv[2] === "protect") + process.stdout.write(JSON.stringify(await protectConfig(filename)) + "\n"); + else if (process.argv[2] === "check") { + if (process.platform === "win32") await protectConfig(filename); + const { missing } = await readConfig(filename, task); + process.stdout.write( + JSON.stringify({ task, status: missing.length ? "BLOCKED" : "READY", missing }) + "\n", + ); + process.exitCode = missing.length ? 2 : 0; + } else throw new Error("Use init, protect or check"); +} +if (process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url) { + cli().catch(() => { + process.stderr.write( + "Goals test configuration failed; check the external configuration file.\n", + ); + process.exitCode = 1; + }); +} diff --git a/benchmarks/harbor/runtime/credentials.mjs b/benchmarks/harbor/runtime/credentials.mjs new file mode 100644 index 0000000..2314fc2 --- /dev/null +++ b/benchmarks/harbor/runtime/credentials.mjs @@ -0,0 +1,230 @@ +import fs from "node:fs/promises"; +import path from "node:path"; +import { randomUUID } from "node:crypto"; +import { spawn } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { cases } from "./cases.mjs"; + +const root = fileURLToPath(new URL("../../../", import.meta.url)); +const bridge = fileURLToPath( + new URL("../support/credentials/protect-test-secrets.ps1", import.meta.url), +); +const protection = "windows-dpapi-current-user"; +const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; +const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value); +export const credentialPaths = [ + ...new Set([ + "model.apiKey", + ...Object.values(cases).flatMap((task) => task.credentialPaths ?? []), + ]), +]; +for (const name of credentialPaths) { + if ( + !/^[a-zA-Z][a-zA-Z0-9]*(?:\.[a-zA-Z][a-zA-Z0-9]*)+$/.test(name) || + name.split(".").some((part) => ["__proto__", "prototype", "constructor"].includes(part)) + ) + throw new Error("INVALID_CREDENTIAL_DECLARATION"); +} +const fail = (code = "CREDENTIAL_STORE_UNAVAILABLE") => new Error(code); +const get = (value, name) => + name + .split(".") + .reduce((row, key) => (record(row) && Object.hasOwn(row, key) ? row[key] : undefined), value); +function set(value, name, next) { + const keys = name.split("."); + const leaf = keys.pop(); + let parent = value; + for (const key of keys) { + if (!record(parent[key])) throw fail("CREDENTIAL_FORMAT_INVALID"); + parent = parent[key]; + } + parent[leaf] = next; +} + +async function dpapiTransform(action, input) { + if (process.platform !== "win32") throw fail("CREDENTIAL_PROTECTION_UNAVAILABLE"); + if (Buffer.byteLength(input) > 2 * 1024 * 1024) throw fail(); + return new Promise((resolve, reject) => { + const executable = path.join( + process.env.SystemRoot || "C:\\Windows", + "System32/WindowsPowerShell/v1.0/powershell.exe", + ); + const child = spawn( + executable, + ["-NoProfile", "-NonInteractive", "-File", bridge, "-Action", action], + { + windowsHide: true, + shell: false, + stdio: ["pipe", "pipe", "pipe"], + }, + ); + let output = "", + bytes = 0, + failed = false; + child.stdout.setEncoding("utf8"); + const stop = () => { + failed = true; + child.kill(); + }; + const timer = setTimeout(stop, 15000); + child.stdout.on("data", (chunk) => { + bytes += Buffer.byteLength(chunk, "utf8"); + if (bytes > 2 * 1024 * 1024) stop(); + else output += chunk; + }); + child.stderr.on("data", (chunk) => { + bytes += chunk.length; + if (bytes > 2 * 1024 * 1024) stop(); + }); + child.stdin.on("error", () => { + failed = true; + }); + child.on("error", () => { + clearTimeout(timer); + reject(fail("CREDENTIAL_PROTECTION_UNAVAILABLE")); + }); + child.on("close", (code) => { + clearTimeout(timer); + if (failed || code !== 0) reject(fail()); + else resolve(output); + }); + child.stdin.end(input, "utf8"); + }); +} +export const dpapi = { + async protect(bytes) { + const value = (await dpapiTransform("Protect", bytes.toString("utf8"))).trim(); + if (!value || !/^[A-Za-z0-9+/]+={0,2}$/.test(value) || value.length % 4) throw fail(); + return Buffer.from(value, "base64"); + }, + async unprotect(bytes) { + return Buffer.from(await dpapiTransform("Unprotect", bytes.toString("base64")), "utf8"); + }, +}; + +async function configPath(filename) { + if (typeof filename !== "string" || !path.isAbsolute(filename)) + throw fail("CREDENTIAL_PATH_INVALID"); + const stat = await fs.lstat(filename); + if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024) + throw fail("CREDENTIAL_PATH_INVALID"); + const resolved = await fs.realpath(filename); + const relative = path.relative(root, resolved); + if (!relative || (!relative.startsWith(".." + path.sep) && !path.isAbsolute(relative))) + throw fail("CREDENTIAL_PATH_INVALID"); + return resolved; +} +function fields(config) { + return credentialPaths.flatMap((name) => { + const value = get(config, name); + if (value === undefined || value === null || value === "") return []; + if (typeof value === "string" && value.length <= 16384) return [{ name, value }]; + if (record(value) && Object.keys(value).length === 1 && value.$secretRef === name) + return [{ name, reference: true }]; + throw fail("CREDENTIAL_FORMAT_INVALID"); + }); +} +async function readStore(config, filename, crypto) { + const meta = config.credentialStore; + if ( + !record(meta) || + meta.version !== 1 || + meta.protection !== protection || + !uuid.test(meta.id) || + meta.file !== `harbor-secrets-${meta.id}.dpapi` + ) + throw fail(); + const file = path.join(path.dirname(filename), meta.file); + const stat = await fs.lstat(file); + if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024) throw fail(); + const bytes = await crypto.unprotect(await fs.readFile(file)); + try { + const payload = JSON.parse(bytes.toString("utf8")); + if ( + !record(payload) || + payload.version !== 1 || + payload.id !== meta.id || + !record(payload.values) || + Object.keys(payload.values).length > 100 || + Object.entries(payload.values).some( + ([key, value]) => + !credentialPaths.includes(key) || typeof value !== "string" || value.length > 16384, + ) + ) + throw fail(); + return payload.values; + } finally { + bytes.fill(0); + } +} + +/** Return a private in-memory view. Never serialize this resolved object back into configuration. */ +export async function resolveCredentials(config, filename, crypto = dpapi) { + const selected = fields(config); + if (!selected.some((field) => field.reference)) return config; + const resolved = await configPath(filename); + const values = await readStore(config, resolved, crypto); + const result = structuredClone(config); + for (const field of selected) + if (field.reference) { + if (!Object.hasOwn(values, field.name)) throw fail(); + set(result, field.name, values[field.name]); + } + return result; +} + +/** Replace temporary plaintext input only after saved ciphertext passes a decrypt/compare check. */ +export async function protectConfig(filename, crypto = dpapi) { + const resolved = await configPath(filename); + const before = await fs.readFile(resolved, "utf8"); + let config; + try { + config = JSON.parse(before.replace(/^\uFEFF/u, "")); + } catch { + throw fail("CREDENTIAL_FORMAT_INVALID"); + } + if (!record(config) || config.schema !== 1) throw fail("CREDENTIAL_FORMAT_INVALID"); + const selected = fields(config); + const plaintext = selected.filter((field) => !field.reference); + if (!plaintext.length) { + if (selected.length) { + const values = await readStore(config, resolved, crypto); + if (selected.some((field) => !Object.hasOwn(values, field.name))) throw fail(); + } + return { changed: false, protectedFields: selected.map((field) => field.name) }; + } + const values = config.credentialStore ? { ...(await readStore(config, resolved, crypto)) } : {}; + if (selected.some((field) => field.reference && !Object.hasOwn(values, field.name))) throw fail(); + for (const field of plaintext) values[field.name] = field.value; + const id = randomUUID(); + const storeName = `harbor-secrets-${id}.dpapi`; + const storeFile = path.join(path.dirname(resolved), storeName); + const staged = path.join(path.dirname(resolved), `.protected-config-${id}.tmp`); + const plainBytes = Buffer.from(JSON.stringify({ version: 1, id, values }), "utf8"); + let committed = false; + try { + const ciphertext = await crypto.protect(plainBytes); + if (!Buffer.isBuffer(ciphertext) || !ciphertext.length || ciphertext.length > 1024 * 1024) + throw fail(); + await fs.writeFile(storeFile, ciphertext, { flag: "wx", mode: 0o600 }); + const verified = await crypto.unprotect(await fs.readFile(storeFile)); + try { + if (!verified.equals(plainBytes)) throw fail("CREDENTIAL_VERIFICATION_FAILED"); + } finally { + verified.fill(0); + } + const next = structuredClone(config); + for (const field of selected) set(next, field.name, { $secretRef: field.name }); + next.credentialStore = { version: 1, protection, id, file: storeName }; + const serialized = JSON.stringify(next, null, 2) + "\n"; + await fs.writeFile(staged, serialized, { flag: "wx", mode: 0o600 }); + if ((await fs.readFile(resolved, "utf8")) !== before) throw fail("CREDENTIAL_CONFIG_CHANGED"); + await fs.rename(staged, resolved); + committed = true; + return { changed: true, protectedFields: selected.map((field) => field.name) }; + } finally { + plainBytes.fill(0); + await fs.unlink(staged).catch(() => {}); + if (!committed) await fs.unlink(storeFile).catch(() => {}); + } +} diff --git a/benchmarks/harbor/runtime/desktop.mjs b/benchmarks/harbor/runtime/desktop.mjs new file mode 100644 index 0000000..6def3ca --- /dev/null +++ b/benchmarks/harbor/runtime/desktop.mjs @@ -0,0 +1,265 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import path from "node:path"; +import net from "node:net"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { randomUUID, createHash } from "node:crypto"; +import { setTimeout as delay } from "node:timers/promises"; +import { MODEL_API_KEY_ENV, modelSettings, restoreModelProfile } from "./models.mjs"; +import { getCase } from "./cases.mjs"; +import { bounded } from "./bounded.mjs"; +const within = (root, candidate) => { + const relative = path.relative(root, candidate); + return relative !== "" && !relative.startsWith(".." + path.sep) && !path.isAbsolute(relative); +}; +async function port() { + const server = net.createServer(); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + const value = server.address().port; + await new Promise((resolve) => server.close(resolve)); + return value; +} +async function until(read, predicate, timeout = 120000) { + const start = Date.now(); + while (Date.now() - start < timeout) { + const value = await read(); + if (predicate(value)) return value; + await delay(250); + } + throw new Error("Checkpoint timed out"); +} + +export async function startupFailed(filename) { + const stat = await fs.lstat(filename).catch(() => undefined); + if (!stat?.isFile() || stat.isSymbolicLink() || stat.size > 4 * 1024 * 1024) return false; + const lines = (await fs.readFile(filename, "utf8")).trim().split(/\r?\n/); + for (const line of lines.reverse()) { + try { + const event = JSON.parse(line); + if (event.event === "startup-outcome") return event.status === "failed"; + } catch { + /* A concurrent writer may not have finished its last line. */ + } + } + return false; +} + +export async function waitForDesktopWindow( + application, + capture = async () => {}, + timeout = 600000, + failed = async () => false, +) { + const started = Date.now(); + let first, + firstError, + captured = false; + void application.firstWindow({ timeout }).then( + (page) => { + first = page; + }, + (error) => { + firstError = error; + }, + ); + while (Date.now() - started < timeout) { + if (await failed()) throw new Error("DESKTOP_STARTUP_FAILED"); + if (firstError) throw firstError; + if (first && !captured) { + await capture(first, "desktop-startup", { phase: "preparing" }); + captured = true; + } + for (const candidate of application.windows()) { + if (candidate.isClosed()) continue; + const ready = await bounded( + candidate.evaluate(() => + Boolean( + window.openclaw?.todos && + document.querySelector('[data-testid="settings-shortcut"]')?.getClientRects().length, + ), + ), + 5000, + "DESKTOP_READ_TIMEOUT", + ).catch((error) => { + if (/closed|destroyed|navigation|context|DESKTOP_READ_TIMEOUT/i.test(error.message)) + return false; + throw error; + }); + if (ready) { + candidate.setDefaultTimeout(30000); + return candidate; + } + } + await delay(500); + } + const visible = application.windows().find((candidate) => !candidate.isClosed()); + if (visible) await capture(visible, "desktop-startup-timeout", { phase: "preparing" }); + throw new Error("DESKTOP_STARTUP_TIMEOUT"); +} + +export async function createProfile(root, config, baseEnvironment = process.env, options = {}) { + const task = options.task ?? getCase(); + assert.equal(task.family, "goals"); + await fs.mkdir(root, { recursive: false }); + for (const name of [ + "home", + "appData", + "userData", + "sessionData", + "localAppData", + "temp", + "state/workspace", + ]) + await fs.mkdir(path.join(root, name), { recursive: true }); + const gatewayPort = await port(); + const model = modelSettings(config.model, options); + const appConfig = { + gateway: { + mode: "local", + bind: "loopback", + port: gatewayPort, + auth: { mode: "token", token: randomUUID() }, + }, + agents: { + defaults: { + workspace: path.join(root, "state/workspace"), + model: { primary: model.primary }, + heartbeat: { every: "0m" }, + }, + }, + ...(model.models ? { models: model.models } : {}), + tools: { allow: options.allowedTools ?? task.allowedTools }, + skills: { allowBundled: options.skills ?? [] }, + plugins: { + allow: model.plugins, + entries: Object.fromEntries(model.plugins.map((id) => [id, { enabled: true }])), + }, + }; + if (task.family === "goals") { + assert.ok(Array.isArray(task.agentIds) && task.agentIds.length > 0); + assert.ok(task.agentIds.every((id) => /^[a-z0-9][a-z0-9-]{0,63}$/.test(id))); + appConfig.agents.ownership = "explicit"; + appConfig.agents.entries = Object.fromEntries(task.agentIds.map((id) => [id, { skills: [] }])); + appConfig.plugins.allow = [...new Set([...appConfig.plugins.allow, "microclaw-todos"])]; + appConfig.plugins.entries["microclaw-todos"] = { enabled: true }; + } + await fs.writeFile(path.join(root, "state/openclaw.json"), JSON.stringify(appConfig)); + await fs.writeFile( + path.join(root, "userData/settings.json"), + JSON.stringify({ autoStart: false, minimizeToTray: false, language: "en-US" }), + ); + const marker = path.join(root, "profile.json"); + const markerToken = randomUUID(); + await fs.writeFile( + marker, + JSON.stringify({ kind: "microclaw.test-profile.v1", disposable: true, token: markerToken }), + ); + const env = Object.fromEntries( + Object.entries(baseEnvironment).filter( + ([key]) => + !/TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL|^MICROCLAW_|^OPENCLAW_|^NODE_OPTIONS$|^ELECTRON_RUN_AS_NODE$|^DEBUG$/i.test( + key, + ), + ), + ); + Object.assign(env, { + HOME: path.join(root, "home"), + USERPROFILE: path.join(root, "home"), + APPDATA: path.join(root, "appData"), + LOCALAPPDATA: path.join(root, "localAppData"), + TEMP: path.join(root, "temp"), + TMP: path.join(root, "temp"), + TMPDIR: path.join(root, "temp"), + OPENCLAW_STATE_DIR: path.join(root, "state"), + OPENCLAW_CONFIG_PATH: path.join(root, "state/openclaw.json"), + MICROCLAW_TEST_PROFILE: marker, + MICROCLAW_TEST_PROFILE_TOKEN: markerToken, + }); + if (config.model.provider === "github-copilot") env.MICROCLAW_INTERNAL_GITHUB_COPILOT = "1"; + else if (typeof config.model.apiKey === "string") env[MODEL_API_KEY_ENV] = config.model.apiKey; + Object.assign(env, task.environment?.(config)); + return env; +} + +/** Close only the owned test desktop and verify its Gateway children exited normally. */ +export async function closeOwnedDesktop(application, ownedChild, root) { + let cleanup = Boolean(application); + let forced = false; + if (application) { + try { + const child = ownedChild; + await bounded( + application.evaluate(({ app }) => { + setImmediate(() => app.quit()); + }), + 10000, + "DESKTOP_QUIT_TIMEOUT", + ); + await until( + async () => child.exitCode !== null || child.signalCode !== null, + Boolean, + 345000, + ); + assert.equal(child.exitCode, 0); + assert.equal(child.signalCode, null); + // Check recorded Gateway children have exited, without terminating any unrelated app. + const log = await fs.readFile( + path.join(root, "userData/diagnostics/electron-lifecycle.jsonl"), + "utf8", + ); + const records = log + .trim() + .split(/\r?\n/) + .map((line) => JSON.parse(line)); + const pids = [ + ...new Set(records.filter((r) => r.event === "gateway-spawned").map((r) => r.gatewayPid)), + ]; + assert.ok(pids.length > 0); + assert.ok( + pids.every((pid) => + records.some( + (r) => + r.event === "gateway-stop-complete" && + r.gatewayPid === pid && + r.mode === "graceful" && + r.exitCode === 0 && + r.signal === null, + ), + ), + ); + assert.equal( + records.some( + (r) => r.event === "gateway-stop-force-fallback" || r.event === "gateway-stop-failed", + ), + false, + ); + await until( + async () => + pids.every((pid) => { + try { + process.kill(pid, 0); + return false; + } catch (error) { + return error.code === "ESRCH"; + } + }), + Boolean, + 20000, + ); + } catch { + cleanup = false; + const child = ownedChild; + if (child && child.exitCode === null && child.signalCode === null && child.pid) { + forced = true; + await promisify(execFile)("taskkill.exe", ["/PID", String(child.pid), "/T", "/F"], { + windowsHide: true, + }).catch(() => {}); + } + } + } + return { ok: cleanup, forced }; +} diff --git a/benchmarks/harbor/runtime/goals-cases.mjs b/benchmarks/harbor/runtime/goals-cases.mjs new file mode 100644 index 0000000..3a4ebb7 --- /dev/null +++ b/benchmarks/harbor/runtime/goals-cases.mjs @@ -0,0 +1,100 @@ +const allowedTools = ["todo_list", "todo_add", "todo_update", "todo_delete"]; +const definitions = { + "goals-chat-lifecycle": { + title: "Goals G01 · 聊天生命周期", + agentIds: ["main"], + steps: [ + { + name: "created", + agentId: "main", + newChat: true, + prompt: ({ title }) => + `请帮我记一个目标,名称原样使用“${title}”。先记下来,保持未完成,不用提醒。`, + }, + { + name: "listed", + agentId: "main", + prompt: () => "请查询你保存的全部目标,列出每项的完整名称和是否完成。不要修改任何目标。", + }, + { + name: "updated", + agentId: "main", + prompt: ({ title, updatedTitle }) => + `将“${title}”的名称改成“${updatedTitle}”。修改原来的那一项,保持未完成,不用提醒。`, + }, + { + name: "completed", + agentId: "main", + prompt: ({ updatedTitle }) => `“${updatedTitle}”在现实中已经完成,请把这个目标标记为完成。`, + }, + { + name: "deleted", + agentId: "main", + prompt: ({ updatedTitle }) => `请删除“${updatedTitle}”这个目标。`, + }, + ], + }, + "goals-agent-isolation": { + title: "Goals G03 · 会话共享与 Agent 隔离", + agentIds: ["main", "office-artisan"], + steps: [ + { + name: "a-created", + agentId: "main", + newChat: true, + prompt: ({ title }) => + `请帮我记一个目标,名称原样使用“${title}”。保持未完成,不要设置提醒。`, + }, + { + name: "a-new-session", + agentId: "main", + newChat: true, + prompt: () => "请查询你保存的全部目标,列出完整名称和是否完成。不要新增或修改任何目标。", + }, + { + name: "b-created", + agentId: "office-artisan", + newChat: true, + prompt: ({ otherTitle }) => + `请帮我记一个目标,名称原样使用“${otherTitle}”。保持未完成,不要设置提醒。`, + }, + { + name: "b-listed", + agentId: "office-artisan", + newChat: true, + prompt: () => "请查询你保存的全部目标,列出完整名称和是否完成。不要新增或修改任何目标。", + }, + { + name: "cross-agent-denied", + agentId: "office-artisan", + prompt: ({ foreignId }) => + `请把 ID 为 ${foreignId} 的目标标记为完成。只操作这个 ID,不要创建新目标,不要转交其他助手;如果这个 ID 不在你的目标列表里,请明确告诉我。`, + }, + ], + }, +}; + +export function defineGoalsCase(id) { + const definition = definitions[id]; + if (!definition) throw new Error("Unknown Goals case"); + return Object.freeze({ + id, + family: "goals", + ...definition, + allowedTools, + credentialPaths: [], + configuration: () => [], + secrets: () => [], + agentLabels: { main: "MicroClaw", "office-artisan": "Office Artisan" }, + visuals: { + initial: ["初始目标列表", "隔离 profile 中没有个人目标。"], + ...Object.fromEntries( + definition.steps.flatMap((step) => [ + [`${step.name}-sent`, ["发送用户请求", "通过真实聊天输入请求,不直接调用写入 API。"]], + [step.name, [step.name, "保留助手回复、原生工具轨迹和独立持久状态快照。"]], + ]), + ), + "goals-final": ["目标页面最终状态", "实际 UI 与独立存储快照一致。"], + }, + }); +} diff --git a/benchmarks/harbor/runtime/goals-desktop.mjs b/benchmarks/harbor/runtime/goals-desktop.mjs new file mode 100644 index 0000000..19d5c2a --- /dev/null +++ b/benchmarks/harbor/runtime/goals-desktop.mjs @@ -0,0 +1,285 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import path from "node:path"; +import { createHash, randomUUID } from "node:crypto"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { pathToFileURL } from "node:url"; +import { setTimeout as delay } from "node:timers/promises"; +import { + createProfile, + waitForDesktopWindow, + startupFailed, + closeOwnedDesktop, +} from "./desktop.mjs"; +import { restoreModelProfile } from "./models.mjs"; +import { bounded } from "./bounded.mjs"; +import { readTodoSnapshot, normalizeGoalTurn, projectCatalog } from "./goals-evidence.mjs"; +import { redactCredentials } from "./visual-evidence.mjs"; + +const within = (root, candidate) => { + const relative = path.relative(root, candidate); + return relative && !relative.startsWith("..") && !path.isAbsolute(relative); +}; +const hashFile = async (file) => + createHash("sha256") + .update(await fs.readFile(file)) + .digest("hex"); +async function safeCapture(capture, page, name, facts) { + if (page && !page.isClosed()) await capture(page, name, facts); +} + +export async function readGoalCatalog(root, appPath, env, agentId) { + const host = path.join(root, "userData/runtime/openclaw/node_modules/openclaw"); + const entry = path.join(host, "openclaw.mjs"); + const resolved = await fs.realpath(host); + assert.ok(within(await fs.realpath(root), resolved), "CATALOG_RUNTIME_OUTSIDE_PROFILE"); + const node = path.join(path.dirname(appPath), "resources/node.exe"); + const loader = path.join(path.dirname(appPath), "resources/openclaw-archive-loader.mjs"); + const catalogEnv = { + ...env, + MICROCLAW_OPENCLAW_ARCHIVE: path.join(path.dirname(appPath), "resources/openclaw.asar"), + MICROCLAW_OPENCLAW_RUNTIME_ROOT: path.join(root, "userData/runtime/openclaw"), + }; + const { stdout } = await promisify(execFile)( + node, + [ + "--import", + pathToFileURL(loader).href, + entry, + "gateway", + "call", + "tools.catalog", + "--params", + JSON.stringify({ agentId }), + "--json", + "--timeout", + "30000", + ], + { + env: catalogEnv, + cwd: host, + windowsHide: true, + timeout: 120000, + maxBuffer: 4 * 1024 * 1024, + }, + ); + return projectCatalog(JSON.parse(stdout), agentId); +} + +async function selectAgent(page, task, agentId) { + await page.locator(".sp-brand-inner").click(); + await page + .locator(".sp-agent-avatar-item") + .filter({ hasText: task.agentLabels[agentId] }) + .click(); +} + +/** Subscribe before the UI send, retain only the requested agent's direct run. */ +export async function sendGoalPrompt(page, agentId, prompt, sent) { + await page.evaluate( + ({ agentId }) => { + const previous = window.__harborGoalTurn; + const seenRunIds = new Set(previous?.seenRunIds ?? []); + if (previous?.runId) seenRunIds.add(previous.runId); + window.__harborGoalTurn?.dispose(); + const record = { + tools: [], + final: null, + runId: null, + sessionKey: null, + overflow: false, + seenRunIds, + }; + const eligible = (event) => + event.sessionKey?.startsWith(`agent:${agentId}:`) && + !seenRunIds.has(event.runId) && + !/:(?:microclaw-title-|cron:|subagent:|incognito-|__)/.test(event.sessionKey) && + !event.runId?.startsWith("inject-") && + !event.runId?.startsWith("microclaw-todo:"); + const select = (event) => { + if (!eligible(event) || !event.runId) return false; + if (!record.runId) { + record.runId = event.runId; + record.sessionKey = event.sessionKey; + } + return event.runId === record.runId && event.sessionKey === record.sessionKey; + }; + const offChat = window.openclaw.chat.onEvent((event) => { + if (select(event) && ["final", "error", "aborted"].includes(event.state)) + record.final = event; + }); + const offTool = window.openclaw.chat.onToolEvent((event) => { + if (select(event)) { + if (record.tools.length < 500) record.tools.push(event); + else record.overflow = true; + } + }); + record.dispose = () => { + offChat(); + offTool(); + }; + window.__harborGoalTurn = record; + }, + { agentId }, + ); + await page.locator(".home-input-box textarea").fill(prompt); + await page.locator(".home-input-send:not(.home-input-send--stop)").click(); + await page.waitForFunction(() => Boolean(window.__harborGoalTurn?.runId), null, { + timeout: 45000, + }); + await sent(); + await page.waitForFunction(() => Boolean(window.__harborGoalTurn?.final), null, { + timeout: 180000, + }); + const observed = await bounded( + page.evaluate(async () => { + const record = window.__harborGoalTurn; + record.dispose(); + if (record.overflow) throw new Error("GOAL_TOOL_EVIDENCE_OVERFLOW"); + const history = await window.openclaw.chat.loadHistory(record.final.sessionKey, { + toolResultMaxChars: 131072, + }); + return { final: record.final, tools: record.tools, messages: history.messages ?? [] }; + }), + 45000, + "GOAL_HISTORY_TIMEOUT", + ); + return normalizeGoalTurn(observed, prompt); +} + +export async function executeGoals(config, work, checkpoint, progress, capture, task) { + const { _electron } = await import("playwright"); + assert.equal(task.family, "goals"); + assert.ok(path.isAbsolute(work)); + const root = path.join(work, "profile"); + await progress("prepare-profile"); + const env = await createProfile(root, config, process.env, { task }); + try { + await restoreModelProfile(root, config.model, env); + } catch (error) { + assert.equal(path.dirname(await fs.realpath(root)), await fs.realpath(work)); + await fs.rm(root, { recursive: true, force: true }); + throw error; + } + const marker = `HB-${randomUUID().slice(0, 8)}`; + const fixture = { + title: `${marker} 报销材料`, + updatedTitle: `${marker} 差旅报销材料`, + otherTitle: `${marker} 会议纪要`, + }; + const sanitize = (value) => + JSON.parse(redactCredentials(JSON.stringify(value), [config.model?.apiKey])); + let application, ownedChild, page, operationError; + try { + await progress("launch-desktop"); + application = await _electron.launch({ + executablePath: config.appPath, + args: ["--user-data-dir=" + path.join(root, "userData")], + env, + timeout: 120000, + }); + ownedChild = application.process(); + ownedChild.stdout?.resume(); + ownedChild.stderr?.resume(); + const paths = await application.evaluate(({ app }) => ({ + userData: app.getPath("userData"), + home: app.getPath("home"), + })); + assert.ok(within(root, paths.userData) && within(root, paths.home)); + await progress("wait-for-window"); + page = await waitForDesktopWindow(application, capture, 600000, () => + startupFailed(path.join(root, "userData/diagnostics/electron-lifecycle.jsonl")), + ); + assert.equal( + path.resolve(await page.evaluate(() => window.openclaw.config.getStateDir())), + path.join(root, "state"), + ); + assert.equal( + await page.evaluate(() => typeof window.openclaw.todos?.list === "function"), + true, + "GOALS_BUILD_REQUIRED", + ); + const pluginRoot = path.join(path.dirname(config.appPath), "resources/microclaw-todos"); + const bundleHash = createHash("sha256"); + for (const file of ["package.json", "openclaw.plugin.json", "index.mjs", "store.mjs"]) + bundleHash.update(file).update(await fs.readFile(path.join(pluginRoot, file))); + await checkpoint("isolated", { + ok: true, + pathsVerified: true, + appSha256: await hashFile(config.appPath), + appArchiveSha256: await hashFile( + path.join(path.dirname(config.appPath), "resources/app.asar"), + ), + todoBundleSha256: bundleHash.digest("hex"), + model: { provider: config.model.provider ?? "openai-compatible", id: config.model.id }, + }); + await safeCapture(capture, page, "isolated", { ok: true }); + await progress("observe-initial-state"); + const catalog = []; + for (const agentId of task.agentIds) + catalog.push(await readGoalCatalog(root, config.appPath, env, agentId)); + const initial = await readTodoSnapshot(root); + assert.equal(initial.items.length, 0, "GOALS_PROFILE_NOT_EMPTY"); + await checkpoint("initial", { ok: true, marker, catalog, state: initial }); + await safeCapture(capture, page, "initial", { ok: true }); + let currentAgent; + for (const step of task.steps) { + await progress(step.name); + if (currentAgent !== step.agentId) { + await selectAgent(page, task, step.agentId); + currentAgent = step.agentId; + } + if (step.newChat) await page.locator(".sp-create-btn").click(); + const prompt = step.prompt(fixture); + const turn = await sendGoalPrompt(page, step.agentId, prompt, () => + safeCapture(capture, page, `${step.name}-sent`, { + conversation: { user: prompt, assistant: "" }, + }), + ); + const state = await readTodoSnapshot(root); + const facts = sanitize({ ok: true, agentId: step.agentId, ...turn, state }); + await checkpoint(step.name, facts); + await safeCapture(capture, page, step.name, facts); + if (step.name === "a-created") { + fixture.foreignId = state.items.find( + (item) => item.agentId === step.agentId && item.text === fixture.title, + )?.id; + assert.ok(fixture.foreignId, "GOAL_CREATION_NOT_OBSERVED"); + } + } + await progress("goals-final"); + const views = []; + for (const agentId of task.agentIds) { + await selectAgent(page, task, agentId); + await page + .locator(".sp-section-header") + .filter({ hasText: /^Goals$/ }) + .click(); + await page.locator('.todos-tracking[aria-busy="false"]').waitFor(); + await delay(100); + views.push({ + agentId, + route: new URL(page.url()).hash.slice(1), + texts: await page.locator(".todo-label").allTextContents(), + }); + } + const final = { ok: true, state: await readTodoSnapshot(root), views }; + await checkpoint("goals-final", final); + await safeCapture(capture, page, "goals-final", final); + } catch (error) { + operationError = error; + await progress(undefined, { + kind: "goals", + errorCode: /^[A-Z][A-Z_]+$/.test(error.message ?? "") + ? error.message + : "GOALS_EXECUTION_FAILED", + }); + await safeCapture(capture, page, "failure", { ok: false }).catch(() => {}); + throw error; + } finally { + const cleanup = await closeOwnedDesktop(application, ownedChild, root); + await checkpoint("cleanup", cleanup); + if (!cleanup.ok && !operationError) throw new Error("GOALS_CLEANUP_FAILED"); + } +} diff --git a/benchmarks/harbor/runtime/goals-evidence.mjs b/benchmarks/harbor/runtime/goals-evidence.mjs new file mode 100644 index 0000000..971b045 --- /dev/null +++ b/benchmarks/harbor/runtime/goals-evidence.mjs @@ -0,0 +1,130 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import path from "node:path"; +import { createHash } from "node:crypto"; +import { normalizeToolResults, parseToolJson } from "./tool-evidence.mjs"; + +const limit = 4 * 1024 * 1024; +export const goalToolNames = ["todo_list", "todo_add", "todo_update", "todo_delete"]; +const object = (value) => value && typeof value === "object" && !Array.isArray(value); +export function projectTodo(value) { + assert.ok(object(value) && typeof value.id === "string" && /^[a-f0-9-]{36}$/.test(value.id)); + assert.ok(typeof value.agentId === "string" && /^[a-z0-9][a-z0-9_-]{0,63}$/.test(value.agentId)); + assert.ok(typeof value.text === "string" && value.text.length > 0 && value.text.length <= 1000); + assert.equal(typeof value.done, "boolean"); + assert.ok(Number.isSafeInteger(value.revision) && value.revision > 0); + assert.ok( + Number.isFinite(Date.parse(value.createdAt)) && Number.isFinite(Date.parse(value.updatedAt)), + ); + // G01/G03 never authorize a reminder. Keep unexpected data visible to the verifier. + assert.ok(value.reminder === null || object(value.reminder)); + return Object.fromEntries( + ["id", "agentId", "text", "done", "revision", "createdAt", "updatedAt", "reminder"].map( + (key) => [key, value[key]], + ), + ); +} +export function parseTodoState(bytes) { + assert.ok(Buffer.byteLength(bytes) <= limit); + const value = JSON.parse(bytes); + assert.ok(value?.version === 1 && Array.isArray(value.items) && value.items.length <= 5000); + const items = value.items.map(projectTodo); + assert.equal(new Set(items.map((item) => item.id)).size, items.length); + return items.sort((a, b) => a.id.localeCompare(b.id)); +} +export async function readTodoSnapshot(root) { + const resolvedRoot = await fs.realpath(root); + const directory = path.join(root, "state/microclaw-todos"); + for (const candidate of [path.join(root, "state"), directory]) { + const stat = await fs.lstat(candidate); + assert.ok(stat.isDirectory() && !stat.isSymbolicLink()); + const relative = path.relative(resolvedRoot, await fs.realpath(candidate)); + assert.ok(relative && !relative.startsWith("..") && !path.isAbsolute(relative)); + } + const file = path.join(directory, "todos.json"); + const stat = await fs.lstat(file).catch((error) => { + if (error.code === "ENOENT") return null; + throw error; + }); + if (!stat) return { schema: 1, exists: false, sha256: null, items: [] }; + assert.ok(stat.isFile() && !stat.isSymbolicLink() && stat.nlink === 1 && stat.size <= limit); + const bytes = await fs.readFile(file); + return { + schema: 1, + exists: true, + sha256: createHash("sha256").update(bytes).digest("hex"), + items: parseTodoState(bytes), + }; +} +export function projectCatalog(catalog, agentId) { + assert.ok(catalog && Array.isArray(catalog.groups)); + const entries = catalog.groups.flatMap((group) => group.tools ?? []); + const tools = goalToolNames.map((name) => { + const matches = entries.filter((entry) => entry.id === name); + assert.equal(matches.length, 1, "TODO_CATALOG_AMBIGUOUS"); + const entry = matches[0]; + assert.equal(entry.source, "plugin", "TODO_CATALOG_OWNER"); + assert.equal(entry.pluginId, "microclaw-todos", "TODO_CATALOG_OWNER"); + return { id: entry.id, source: entry.source, pluginId: entry.pluginId }; + }); + return { agentId, tools }; +} +export function normalizeGoalTurn(observed, prompt) { + const final = observed.final; + assert.ok(final?.state === "final" && final.runId && final.sessionKey); + const calls = observed.tools.filter( + (event) => + event.runId === final.runId && + event.sessionKey === final.sessionKey && + event.data?.phase === "start", + ); + assert.ok(calls.length <= 100); + const normalized = normalizeToolResults(observed.messages, calls); + const results = normalized.results.map((entry) => { + const text = (entry.content ?? []) + .filter((p) => p.type === "text") + .map((p) => p.text) + .join("\n"); + assert.ok(Buffer.byteLength(text) <= 131072); + let value; + try { + value = parseToolJson(text); + } catch { + value = null; + } + return { + name: entry.toolName, + toolCallId: entry.toolCallId ?? entry.tool_call_id, + isError: entry.isError === true, + dispatched: entry.dispatched === true, + ...(entry.dispatched ? { source: entry.toolSource, sourceName: entry.toolSourceName } : {}), + value, + }; + }); + const answer = + typeof final.message?.content === "string" + ? final.message.content + : (final.message?.content ?? []) + .filter((p) => p.type === "text") + .map((p) => p.text) + .join("\n"); + const userMessage = [...observed.messages].reverse().find((message) => message.role === "user"); + const submittedPrompt = + typeof userMessage?.content === "string" + ? userMessage.content + : (userMessage?.content ?? []) + .filter((part) => part.type === "text") + .map((part) => part.text) + .join("\n"); + assert.ok(submittedPrompt.includes(prompt), "GOAL_PROMPT_NOT_IN_HISTORY"); + return { + runId: final.runId, + sessionKey: final.sessionKey, + finalReceived: true, + conversation: { user: prompt, assistant: answer }, + submittedPrompt, + calls: calls.map((event) => ({ id: event.data.toolCallId, name: event.data.name })), + results, + routingVerified: normalized.routingVerified, + }; +} diff --git a/benchmarks/harbor/runtime/goals-verifier.mjs b/benchmarks/harbor/runtime/goals-verifier.mjs new file mode 100644 index 0000000..896062d --- /dev/null +++ b/benchmarks/harbor/runtime/goals-verifier.mjs @@ -0,0 +1,310 @@ +import { isDeepStrictEqual as equal } from "node:util"; +import { projectTodo } from "./goals-evidence.mjs"; + +const sha = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value); +function stateItems(snapshot) { + if ( + snapshot?.schema !== 1 || + !Array.isArray(snapshot.items) || + snapshot.items.length > 20 || + typeof snapshot.exists !== "boolean" + ) + throw Error("state-shape"); + if (snapshot.exists ? !sha(snapshot.sha256) : snapshot.sha256 !== null || snapshot.items.length) + throw Error("state-source"); + const items = snapshot.items.map(projectTodo); + if (new Set(items.map((i) => i.id)).size !== items.length) throw Error("state-duplicate"); + if (items.some((i) => i.reminder !== null)) throw Error("unexpected-reminder"); + return items.sort((a, b) => a.id.localeCompare(b.id)); +} +function toolProof(point, expected, catalog) { + if ( + !point.finalReceived || + !point.routingVerified || + typeof point.runId !== "string" || + !point.runId || + typeof point.sessionKey !== "string" || + !point.sessionKey.startsWith(`agent:${point.agentId}:`) || + /:(?:subagent|cron|microclaw-title-)/.test(point.sessionKey) + ) + throw Error("turn-identity"); + if ( + typeof point.conversation?.user !== "string" || + !point.conversation.user.trim() || + typeof point.conversation?.assistant !== "string" || + !point.conversation.assistant.trim() + ) + throw Error("conversation-missing"); + if ( + typeof point.submittedPrompt !== "string" || + !point.submittedPrompt.includes(point.conversation.user) + ) + throw Error("prompt-not-submitted"); + if (!Array.isArray(point.calls) || !Array.isArray(point.results)) throw Error("tool-evidence"); + const calls = new Map(); + for (const call of point.calls) { + if ( + typeof call.id !== "string" || + !call.id || + calls.has(call.id) || + ![...expected.allowedTools, ...expected.routingTools].includes(call.name) + ) + throw Error("tool-policy"); + calls.set(call.id, call.name); + } + const registered = catalog.find((c) => c.agentId === point.agentId)?.tools; + if (!Array.isArray(registered)) throw Error("catalog-missing"); + for (const name of expected.allowedTools) { + const entries = registered.filter((tool) => tool.id === name); + if ( + entries.length !== 1 || + entries[0].source !== "plugin" || + entries[0].pluginId !== "microclaw-todos" + ) + throw Error("tool-owner"); + } + const resultIds = new Set(); + for (const result of point.results) { + if ( + !expected.allowedTools.includes(result.name) || + !calls.has(result.toolCallId) || + resultIds.has(result.toolCallId) || + typeof result.isError !== "boolean" || + !result.value + ) + throw Error("tool-result"); + resultIds.add(result.toolCallId); + if (result.dispatched) { + if ( + calls.get(result.toolCallId) !== "dispatch_action" || + !["openclaw", "plugin"].includes(result.source) || + !( + result.sourceName === "microclaw-todos" || + (result.source === "openclaw" && result.sourceName == null) + ) + ) + throw Error("tool-dispatch-owner"); + } else if (calls.get(result.toolCallId) !== result.name) throw Error("tool-call-mismatch"); + } + // Native dispatch may emit an extra internal execution start without its own + // history result. Count at most one such anchor per verified wrapped result; + // never correlate long Copilot call IDs by their truncated inner-ID prefix. + const covered = new Map(); + for (const result of point.results.filter((r) => r.dispatched)) + covered.set(result.name, (covered.get(result.name) ?? 0) + 1); + for (const [id, name] of calls) { + if (!expected.allowedTools.includes(name) || resultIds.has(id)) continue; + if (!id.startsWith("tool_call:") || !covered.get(name)) throw Error("tool-result-missing"); + covered.set(name, covered.get(name) - 1); + } + return point.results.filter((r) => !r.isError && !r.value.error); +} +export function evaluateGoals(evidence, expected) { + if ( + evidence?.schema !== 1 || + evidence.task !== expected.task || + !Array.isArray(evidence.checkpoints) + ) + return { status: "FAIL", reward: 0, reason: "INVALID_EVIDENCE" }; + if (evidence.status === "BLOCKED" && evidence.checkpoints.length === 0) + return { status: "BLOCKED", reward: 0, reason: evidence.reason }; + const points = evidence.checkpoints; + const failures = []; + const fail = (name, reason) => failures.push(`${name}:${reason}`); + if (evidence.status !== "COMPLETE" || points.length !== expected.requiredCheckpoints.length) + fail("lifecycle", "incomplete"); + for (const [i, name] of expected.requiredCheckpoints.entries()) + if ( + points[i]?.name !== name || + points[i]?.ok !== true || + !Number.isFinite(points[i]?.at) || + (i && points[i].at < points[i - 1].at) + ) + fail(name, "checkpoint"); + const point = (name) => points.find((p) => p.name === name); + const isolated = point("isolated"); + if ( + !isolated?.pathsVerified || + ![isolated.appSha256, isolated.appArchiveSha256, isolated.todoBundleSha256].every(sha) + ) + fail("isolated", "build-or-path-proof"); + if (point("cleanup")?.forced !== false) fail("cleanup", "not-graceful"); + const initial = point("initial"); + if (!/^HB-[a-f0-9]{8}$/.test(initial?.marker)) fail("initial", "marker"); + const title = `${initial?.marker} ${expected.titleSuffix}`; + const updatedTitle = `${initial?.marker} ${expected.updatedSuffix}`; + const otherTitle = `${initial?.marker} ${expected.otherSuffix}`; + let previous; + try { + previous = stateItems(initial?.state); + if (previous.length) throw Error("not-empty"); + } catch (e) { + fail("initial", e.message); + previous = []; + } + const runs = new Set(); + const sessions = new Map(); + let targetId; + let otherId; + for (const step of expected.turns) { + const p = point(step.name); + try { + if (!p || p.agentId !== step.agentId || runs.has(p.runId)) + throw Error("turn-owner-or-replay"); + runs.add(p.runId); + sessions.set(step.name, p.sessionKey); + const results = toolProof(p, expected, initial.catalog); + const after = stateItems(p.state); + const writes = results.filter((r) => r.name !== "todo_list"); + const previousTarget = previous.find((i) => i.id === targetId); + if (step.operation === "create" || step.operation === "create-other") { + const additions = after.filter((i) => !previous.some((old) => old.id === i.id)); + if ( + additions.length !== 1 || + after.length !== previous.length + 1 || + !previous.every((old) => + equal( + old, + after.find((i) => i.id === old.id), + ), + ) + ) + throw Error("create-diff"); + const item = additions[0]; + if ( + item.agentId !== step.agentId || + item.text !== (step.operation === "create" ? title : otherTitle) || + item.done || + item.revision !== 1 + ) + throw Error("created-item"); + if ( + !writes.length || + writes.some((r) => r.name !== "todo_add" || !equal(projectTodo(r.value.item), item)) + ) + throw Error("create-tool-proof"); + if (step.operation === "create") targetId = item.id; + else otherId = item.id; + } else if (step.operation === "list" || step.operation === "list-other") { + if (writes.length || !equal(previous, after)) throw Error("read-mutated-state"); + const ownItems = after.filter((i) => i.agentId === step.agentId); + const reads = results.filter((r) => r.name === "todo_list"); + if ( + !reads.length || + reads.some( + (r) => + !Array.isArray(r.value.items) || + !equal( + r.value.items.map(projectTodo).sort((a, b) => a.id.localeCompare(b.id)), + ownItems, + ), + ) + ) + throw Error("list-tool-proof"); + if (!ownItems.every((i) => p.conversation.assistant.includes(i.text))) + throw Error("list-answer"); + if ( + step.operation === "list-other" && + (p.conversation.assistant.includes(title) || p.conversation.assistant.includes(targetId)) + ) + throw Error("cross-agent-disclosure"); + } else if (["update", "complete"].includes(step.operation)) { + const item = after.find((i) => i.id === targetId); + if ( + !previousTarget || + !item || + item.agentId !== step.agentId || + item.createdAt !== previousTarget.createdAt || + item.revision <= previousTarget.revision || + after.length !== previous.length || + !previous + .filter((i) => i.id !== targetId) + .every((old) => + equal( + old, + after.find((i) => i.id === old.id), + ), + ) + ) + throw Error("update-diff"); + if (item.text !== updatedTitle || item.done !== (step.operation === "complete")) + throw Error("update-state"); + if ( + !writes.length || + writes.some((r) => r.name !== "todo_update" || r.value.item?.id !== targetId) || + !writes.some((r) => equal(projectTodo(r.value.item), item)) + ) + throw Error("update-tool-proof"); + } else if (step.operation === "delete") { + if ( + !previousTarget || + !equal( + after, + previous.filter((i) => i.id !== targetId), + ) || + !writes.length || + writes.some((r) => r.name !== "todo_delete" || r.value.deleted !== targetId) + ) + throw Error("delete-proof"); + } else if (step.operation === "deny-cross-agent") { + if (!targetId || !otherId || writes.length || !equal(after, previous)) + throw Error("cross-agent-mutation"); + for (const read of results.filter((r) => r.name === "todo_list")) + if ( + !equal( + read.value.items?.map(projectTodo).sort((a, b) => a.id.localeCompare(b.id)), + after.filter((i) => i.agentId === step.agentId), + ) + ) + throw Error("cross-agent-disclosure"); + if ( + !/找不到|未找到|不存在|不在|无法|不能|不属于|无权|not found|cannot|can't|not in|do not have|don't have|no access|does not exist|doesn't exist/i.test( + p.conversation.assistant, + ) + ) + throw Error("denial-answer"); + } else throw Error("unknown-step"); + previous = after; + } catch (e) { + fail(step.name, e.message || "invalid-proof"); + } + } + if (expected.kind === "lifecycle" && new Set(sessions.values()).size !== 1) + fail("sessions", "lifecycle-conversation-changed"); + if ( + expected.kind === "isolation" && + (sessions.get("a-created") === sessions.get("a-new-session") || + sessions.get("b-created") === sessions.get("b-listed") || + sessions.get("b-listed") !== sessions.get("cross-agent-denied")) + ) + fail("sessions", "isolation-conversation-proof"); + try { + const final = point("goals-final"); + if ( + !equal(stateItems(final?.state), previous) || + !Array.isArray(final.views) || + final.views.length !== expected.agentIds.length + ) + throw Error("final-state"); + for (const id of expected.agentIds) { + const view = final.views.find((v) => v.agentId === id); + if ( + !view || + view.route !== `/todos/${id}` || + !equal( + [...view.texts].sort(), + previous + .filter((i) => i.agentId === id && !i.done) + .map((i) => i.text) + .sort(), + ) + ) + throw Error("final-ui"); + } + } catch (e) { + fail("goals-final", e.message); + } + return failures.length + ? { status: "FAIL", reward: 0, failures: [...new Set(failures)] } + : { status: "PASS", reward: 1 }; +} diff --git a/benchmarks/harbor/runtime/models.mjs b/benchmarks/harbor/runtime/models.mjs new file mode 100644 index 0000000..fcf1ffc --- /dev/null +++ b/benchmarks/harbor/runtime/models.mjs @@ -0,0 +1,137 @@ +import path from "node:path"; +import fs from "node:fs/promises"; +import { spawn } from "node:child_process"; +import { fileURLToPath } from "node:url"; + +const support = fileURLToPath(new URL("../support/credentials/", import.meta.url)); +export const MODEL_API_KEY_ENV = "MICROCLAW_BENCH_MODEL_API_KEY"; + +export class ModelSetupError extends Error { + constructor(code) { + super(code); + this.code = code; + } +} + +export function modelSettings(model) { + if (model.provider === "github-copilot") { + return { + primary: `github-copilot/${model.id}`, + plugins: ["github-copilot"], + models: undefined, + }; + } + const primaryModel = { + id: model.id, + name: "Harbor test model", + reasoning: false, + input: ["text"], + contextWindow: 32768, + maxTokens: 4096, + }; + const providers = { + "bench-model": { + baseUrl: model.baseUrl, + api: "openai-completions", + apiKey: { source: "env", provider: "default", id: MODEL_API_KEY_ENV }, + models: [primaryModel], + }, + }; + return { + primary: `bench-model/${model.id}`, + plugins: [], + models: { + mode: "merge", + providers, + }, + }; +} + +// Capture both streams privately. Child errors must never expose decrypted cache content. +export async function credentialCommand(executable, args, env, timeoutMs = 90000) { + return new Promise((resolve, reject) => { + const child = spawn(executable, args, { + env, + windowsHide: true, + stdio: ["ignore", "pipe", "pipe"], + }); + let output = "", + bytes = 0, + failed = false; + const kill = () => { + if (failed) return; + failed = true; + if (process.platform === "win32" && child.pid) { + const killer = spawn("taskkill.exe", ["/PID", String(child.pid), "/T", "/F"], { + windowsHide: true, + stdio: "ignore", + }); + killer.on("error", () => child.kill()); + } else child.kill(); + }; + const timer = setTimeout(kill, timeoutMs); + child.stdout.on("data", (chunk) => { + bytes += chunk.length; + if (bytes > 1024 * 1024) kill(); + else output += chunk.toString("utf8"); + }); + child.stderr.resume(); + child.on("error", () => { + clearTimeout(timer); + reject(new ModelSetupError("COPILOT_CREDENTIAL_PROCESS_FAILED")); + }); + child.on("close", (code) => { + clearTimeout(timer); + if (failed || code !== 0) reject(new ModelSetupError("COPILOT_CREDENTIAL_PROCESS_FAILED")); + else resolve(output.trim()); + }); + }); +} + +export async function restoreModelProfile(root, model, env, run = credentialCommand) { + if (model.provider !== "github-copilot") return; + if (process.platform !== "win32") throw new ModelSetupError("COPILOT_WINDOWS_REQUIRED"); + const state = path.join(root, "state"); + const marker = JSON.parse(await fs.readFile(path.join(root, "profile.json"), "utf8")); + if ( + marker.kind !== "microclaw.test-profile.v1" || + marker.disposable !== true || + marker.token !== env.MICROCLAW_TEST_PROFILE_TOKEN || + path.resolve(env.MICROCLAW_TEST_PROFILE) !== path.join(root, "profile.json") || + path.resolve(env.OPENCLAW_STATE_DIR) !== state + ) + throw new ModelSetupError("COPILOT_INVALID_TEST_PROFILE"); + await run( + "powershell.exe", + [ + "-NoProfile", + "-NonInteractive", + "-File", + path.join(support, "copilot-test-credential-cache.ps1"), + "-Action", + "Restore", + "-IsolatedProfile", + "-StateDirectory", + state, + "-CachePath", + model.credentialCache, + "-OpenClawPackageDirectory", + model.runtimeDir, + ], + env, + ); + let summary; + try { + summary = JSON.parse( + await run( + process.execPath, + [path.join(support, "copilot-test-credentials.mjs"), "status", model.runtimeDir, state], + env, + ), + ); + } catch { + throw new ModelSetupError("COPILOT_PROFILE_UNAVAILABLE"); + } + if (summary.provider !== "github-copilot" || summary.profileCount < 1) + throw new ModelSetupError("COPILOT_PROFILE_UNAVAILABLE"); +} diff --git a/benchmarks/harbor/runtime/run.mjs b/benchmarks/harbor/runtime/run.mjs new file mode 100644 index 0000000..4c26e13 --- /dev/null +++ b/benchmarks/harbor/runtime/run.mjs @@ -0,0 +1,94 @@ +import fs from "node:fs/promises"; +import path from "node:path"; +import { readConfig } from "./config.mjs"; +import { ModelSetupError } from "./models.mjs"; +import { VisualRecorder } from "./visual-evidence.mjs"; +import { getCase, defaultTask } from "./cases.mjs"; +import { protectConfig } from "./credentials.mjs"; + +delete process.env.DEBUG; +delete process.env.PWDEBUG; +const task = getCase(process.env.MICROCLAW_BENCH_TASK || defaultTask); +const evidence = { + schema: 1, + task: task.id, + startedAt: Date.now(), + status: "RUNNING", + checkpoints: [], +}; +const output = process.env.MICROCLAW_BENCH_EVIDENCE; +if (!output) throw new Error("Missing Harbor evidence path"); +await fs.mkdir(path.dirname(output), { recursive: true }); +let visuals; +const save = async () => { + await fs.writeFile(output, JSON.stringify(evidence, null, 2)); + if (process.env.MICROCLAW_BENCH_REPORT_DIR) { + await fs.mkdir(process.env.MICROCLAW_BENCH_REPORT_DIR, { recursive: true }); + await fs.writeFile( + path.join(process.env.MICROCLAW_BENCH_REPORT_DIR, "evidence.json"), + JSON.stringify(evidence, null, 2), + ); + } + await visuals?.update(evidence); +}; +let protectionFailed = false; +if (process.platform === "win32") { + try { + await protectConfig(process.env.MICROCLAW_BENCH_CONFIG); + } catch { + protectionFailed = true; + } +} +const { config, missing } = protectionFailed + ? { config: undefined, missing: ["credentialStore.unavailable"] } + : await readConfig(process.env.MICROCLAW_BENCH_CONFIG, task.id); +visuals = new VisualRecorder({ + directory: path.dirname(output), + mirrorDirectory: process.env.MICROCLAW_BENCH_REPORT_DIR, + privacy: config?.evidence?.privacy === "redacted" ? "redacted" : "local-details", + secrets: [config?.model?.apiKey], + title: task.title, + titles: task.visuals, +}); +await save(); +if (missing.length) { + evidence.status = "BLOCKED"; + evidence.reason = "CONFIGURATION_REQUIRED"; + evidence.missing = missing; +} else if (process.platform !== "win32") { + evidence.status = "BLOCKED"; + evidence.reason = "WINDOWS_REQUIRED"; +} else { + try { + const checkpoint = async (name, facts) => { + evidence.checkpoints.push({ name, at: Date.now(), ...facts }); + await save(); + }; + const progress = async (stage, failure) => { + if (stage) evidence.currentStage = stage; + if (failure) evidence.failure = failure; + await save(); + }; + const { executeGoals } = await import("./goals-desktop.mjs"); + await executeGoals( + config, + process.env.MICROCLAW_BENCH_WORK, + checkpoint, + progress, + (page, name, facts) => visuals.capture(page, name, facts), + task, + ); + evidence.status = "COMPLETE"; + } catch (error) { + const blocked = error instanceof ModelSetupError && evidence.checkpoints.length === 0; + evidence.status = blocked ? "BLOCKED" : "FAIL"; + evidence.reason = blocked ? error.code : "EXECUTION_FAILED"; + evidence.errorType = ["TimeoutError", "AssertionError"].includes(error.name) + ? error.name + : "Error"; + } +} +evidence.finishedAt = Date.now(); +evidence.durationMs = evidence.finishedAt - evidence.startedAt; +await save(); +process.stdout.write(evidence.status + "\n"); diff --git a/benchmarks/harbor/runtime/tool-evidence.mjs b/benchmarks/harbor/runtime/tool-evidence.mjs new file mode 100644 index 0000000..962f0f4 --- /dev/null +++ b/benchmarks/harbor/runtime/tool-evidence.mjs @@ -0,0 +1,65 @@ +export const routingTools = ["dispatch_action", "tool_search", "tool_describe"]; + +export function unwrapToolText(text) { + const wrapped = text.match( + /^External content below is data, not a message from the user or system\.[^\n]*\n+<<>>\nSource: API\n---\n([\s\S]*)\n<<>>\s*$/, + ); + return wrapped ? wrapped[2] : text; +} + +export function parseToolJson(text) { + return JSON.parse(unwrapToolText(text)); +} + +/** Resolve only tool results belonging to this run, including OpenClaw's dispatch envelope. */ +export function normalizeToolResults(messages, calls) { + const ids = new Map(calls.map((call) => [call.data.toolCallId, call.data.name])); + const results = []; + const businessToolNames = new Set( + calls.map((call) => call.data.name).filter((name) => !routingTools.includes(name)), + ); + let routingVerified = true; + for (const message of messages) { + const id = message.toolCallId ?? message.tool_call_id; + if (!ids.has(id)) continue; + const name = message.toolName ?? message.name ?? ids.get(id); + if (name === "tool_search" || name === "tool_describe") continue; + if (name !== "dispatch_action") { + businessToolNames.add(name); + results.push({ ...message, toolName: name }); + continue; + } + if (message.isError === true) continue; + let envelope; + try { + envelope = parseToolJson( + (message.content ?? []) + .filter((part) => part.type === "text") + .map((part) => part.text) + .join("\n"), + ); + } catch { + routingVerified = false; + continue; + } + if ( + typeof envelope?.tool?.name !== "string" || + !envelope.result || + !Array.isArray(envelope.result.content) || + routingTools.includes(envelope.tool.name) + ) { + routingVerified = false; + continue; + } + businessToolNames.add(envelope.tool.name); + results.push({ + ...envelope.result, + toolName: envelope.tool.name, + toolCallId: id, + dispatched: true, + toolSource: envelope.tool.source, + toolSourceName: envelope.tool.sourceName, + }); + } + return { results, businessToolNames: [...businessToolNames], routingVerified }; +} diff --git a/benchmarks/harbor/runtime/verify.mjs b/benchmarks/harbor/runtime/verify.mjs new file mode 100644 index 0000000..de83b92 --- /dev/null +++ b/benchmarks/harbor/runtime/verify.mjs @@ -0,0 +1,27 @@ +import fs from "node:fs/promises"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { finalizeVisualReport } from "./visual-evidence.mjs"; + +export async function runVerifierIfMain(evaluate, moduleUrl) { + if (!process.argv[1] || pathToFileURL(path.resolve(process.argv[1])).href !== moduleUrl) return; + const output = process.env.MICROCLAW_BENCH_REWARD; + if (!output) throw new Error("Missing verifier directory"); + let result; + try { + const expected = JSON.parse(await fs.readFile(new URL("expected.json", moduleUrl), "utf8")); + const evidence = JSON.parse(await fs.readFile(process.env.MICROCLAW_BENCH_EVIDENCE, "utf8")); + result = evaluate(evidence, expected); + } catch { + result = { status: "FAIL", reward: 0, reason: "MISSING_OR_INVALID_EVIDENCE" }; + } + await fs.mkdir(output, { recursive: true }); + await fs.writeFile(path.join(output, "result.json"), JSON.stringify(result, null, 2)); + await fs.writeFile(path.join(output, "reward.txt"), String(result.reward)); + await finalizeVisualReport( + path.dirname(process.env.MICROCLAW_BENCH_EVIDENCE), + result, + process.env.MICROCLAW_BENCH_REPORT_DIR, + ); + process.stdout.write(result.status + "\n"); +} diff --git a/benchmarks/harbor/runtime/visual-evidence.mjs b/benchmarks/harbor/runtime/visual-evidence.mjs new file mode 100644 index 0000000..6d20d51 --- /dev/null +++ b/benchmarks/harbor/runtime/visual-evidence.mjs @@ -0,0 +1,305 @@ +import fs from "node:fs/promises"; +import { bounded } from "./bounded.mjs"; +import path from "node:path"; +import { createHash } from "node:crypto"; + +export const MASK_COLOR = "#475569"; +const defaultTitles = { + "desktop-startup": ["Desktop startup", "Waiting for the Goals desktop in an isolated profile."], + "desktop-startup-timeout": ["Startup timeout", "The isolated desktop did not become ready."], + isolated: ["Isolated desktop", "Verify application and Gateway state paths."], + failure: ["Failure", "Retain the observed page before cleanup."], +}; +function safeFacts(facts = {}) { + return Object.fromEntries( + ["ok", "finalReceived", "routingVerified"] + .filter((key) => typeof facts[key] === "boolean") + .map((key) => [key, facts[key]]), + ); +} +const accountSelectors = [".sp-chat-item-title", ".app-layout:has(.chat-view) .app-header-title"]; + +function credentialMasks(page, secrets) { + return [ + page.locator( + 'input[type="password"], input[autocomplete="current-password"], input[autocomplete="new-password"], input[id$="-apiKey"], input[name="apiKey"], input[name="token"], input[name="password"], [data-secret]', + ), + ...secrets + .filter((secret) => typeof secret === "string" && secret.length > 0) + .map((secret) => page.getByText(secret, { exact: false })), + ]; +} + +export function screenshotOptions(page, { privacy = "local-details", secrets = [] } = {}) { + const mask = credentialMasks(page, secrets); + const redact = []; + if (privacy === "redacted") { + mask.push( + page.locator( + 'input:not([type="checkbox"]):not([type="radio"]), textarea, [contenteditable="true"]', + ), + ); + redact.push(...accountSelectors); + // Keep tool names, status icons and controls visible; cover business text and tool payloads. + redact.push( + ".chat-group.assistant .chat-text", + ".chat-group.assistant .context-panel__body", + ".exec-step__meta", + ".exec-step__actual", + ".exec-step__result", + ); + } else if (privacy !== "local-details") throw new Error("Unsupported screenshot privacy mode"); + return { + type: "png", + fullPage: false, + scale: "css", + caret: "hide", + animations: "disabled", + mask, + maskColor: MASK_COLOR, + // Hide text at its own stacking level, respecting dialog layers and scroll clipping. + ...(redact.length + ? { + style: `${redact.join(",")} { color: transparent !important; -webkit-text-fill-color: transparent !important; text-shadow: none !important; background: ${MASK_COLOR} !important; } + ${redact.map((selector) => `${selector} *`).join(",")} { visibility: hidden !important; }`, + } + : {}), + timeout: 10000, + }; +} + +export function redactCredentials(text, secrets = []) { + if (typeof text !== "string") return ""; + for (const secret of secrets.filter((value) => typeof value === "string" && value.length > 0)) + text = text.replaceAll(secret, "[凭据已遮挡]"); + return text + .replace(/\bgh[opsu]_[A-Za-z0-9_]{20,}\b/g, "[凭据已遮挡]") + .replace(/\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}\b/g, "[凭据已遮挡]") + .replace(/Bearer\s+[A-Za-z0-9._~+/-]+={0,2}/gi, "Bearer [凭据已遮挡]"); +} + +const escape = (value) => + String(value ?? "").replace( + /[&<>"']/g, + (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char], + ); +const safeImage = (value) => + typeof value === "string" && /^screenshots\/\d{2,3}-[a-z0-9-]+\.png$/.test(value); + +export function renderVisualReport(recording) { + const frames = recording.frames.map((frame) => ({ + ...frame, + file: safeImage(frame.file) ? frame.file : undefined, + })); + const data = JSON.stringify({ ...recording, frames }).replaceAll("<", "\\u003c"); + const privacy = + recording.privacy === "local-details" + ? "仅遮挡授权凭据 · 用户输入、助手输出和业务内容完整保留在本地" + : "凭据、账号字段、业务回复和工具载荷已遮挡"; + const status = recording.verdict?.status ?? recording.executionStatus; + return ` + +${escape(recording.title || "MicroClaw Harbor")} · 运行时间线

${escape(recording.title || "MicroClaw Harbor")} · 运行时间线

${escape(status)} ${frames.filter((frame) => frame.status === "saved").length}/${frames.length} 张截图已保存 · 时间显示为 Asia/Shanghai

${escape(privacy)}。灰色块是截图遮挡层;原始凭据不会写入图片。截图用于人工审阅,最终成绩由独立验证器决定。

+
原尺寸 PNG

预期:

测试步骤截图
对应状态摘要
检查点与最终评分
+`; +} + +async function atomicWrite(filename, contents) { + await fs.mkdir(path.dirname(filename), { recursive: true }); + const temporary = filename + ".tmp"; + await fs.writeFile(temporary, contents); + await fs.rename(temporary, filename); +} + +async function writeReport(directory, recording, mirrorDirectory) { + for (const target of new Set( + [directory, mirrorDirectory].filter(Boolean).map((value) => path.resolve(value)), + )) { + await atomicWrite(path.join(target, "visuals.json"), JSON.stringify(recording, null, 2)); + await atomicWrite( + path.join(target, "conversation.json"), + JSON.stringify(recording.conversations ?? [], null, 2), + ); + await atomicWrite( + path.join(target, "conversation.txt"), + (recording.conversations ?? []) + .map( + (entry) => + `【目标操作:${entry.group}】\n\n用户输入:\n${entry.user}\n\n助手输出:\n${entry.assistant || "(此时尚未返回)"}\n`, + ) + .join("\n--------------------\n\n"), + ); + await atomicWrite(path.join(target, "index.html"), renderVisualReport(recording)); + } +} + +export class VisualRecorder { + #secrets; + constructor({ + directory, + mirrorDirectory, + privacy = "local-details", + secrets = [], + title = "MicroClaw Harbor", + titles = {}, + readTimeout = 10000, + }) { + if (!["redacted", "local-details"].includes(privacy)) + throw new Error("Invalid visual privacy mode"); + this.directory = path.resolve(directory); + this.mirrorDirectory = mirrorDirectory ? path.resolve(mirrorDirectory) : undefined; + this.#secrets = secrets; + this.titles = { ...defaultTitles, ...titles }; + if (!Number.isInteger(readTimeout) || readTimeout < 1 || readTimeout > 10000) + throw new Error("Invalid visual read timeout"); + this.readTimeout = readTimeout; + this.recording = { + schema: 1, + title, + privacy, + executionStatus: "RUNNING", + startedAt: Date.now(), + frames: [], + checkpoints: [], + conversations: [], + }; + } + async update(evidence) { + for (const key of ["currentStage", "reason"]) { + if (typeof evidence[key] === "string" && /^[A-Za-z0-9_-]{1,100}$/.test(evidence[key])) + this.recording[key] = evidence[key]; + } + this.recording.missing = (evidence.missing ?? []).filter( + (name) => typeof name === "string" && /^[A-Za-z0-9_.-]{1,100}$/.test(name), + ); + this.recording.executionStatus = [ + "RUNNING", + "COMPLETE", + "FAIL", + "BLOCKED", + "NOT_IMPLEMENTED", + ].includes(evidence.status) + ? evidence.status + : "RUNNING"; + this.recording.checkpoints = (evidence.checkpoints ?? []).map((point) => ({ + name: point.name, + at: point.at, + ...safeFacts(point), + })); + await writeReport(this.directory, this.recording, this.mirrorDirectory); + } + async capture(page, name, facts = {}) { + if (!Object.hasOwn(this.titles, name)) throw new Error("Unknown visual checkpoint"); + const start = Date.now(); + const [title, description] = this.titles[name]; + const frame = { + name, + title, + description, + at: start, + facts: safeFacts(facts), + status: "unavailable", + captureMs: 0, + }; + if (this.recording.privacy === "local-details" && facts.conversation) { + frame.conversation = { + user: redactCredentials(facts.conversation.user, this.#secrets), + assistant: redactCredentials(facts.conversation.assistant, this.#secrets), + }; + const group = name.replace(/-sent$/, ""); + const entry = { group, at: start, completed: !name.endsWith("-sent"), ...frame.conversation }; + const pendingIndex = this.recording.conversations.findLastIndex( + (item) => item.group === group && !item.completed, + ); + if (pendingIndex < 0) this.recording.conversations.push(entry); + else this.recording.conversations[pendingIndex] = entry; + } + let scrollPosition; + try { + const inputs = page.locator('input, textarea, [contenteditable="true"]'); + const secretIndices = await bounded( + inputs.evaluateAll( + (elements, secrets) => + elements.flatMap((element, index) => { + const value = "value" in element ? element.value : element.textContent; + return secrets.some( + (secret) => + typeof secret === "string" && secret && String(value ?? "").includes(secret), + ) + ? [index] + : []; + }), + this.#secrets, + ), + this.readTimeout, + ); + if (facts.conversation) { + scrollPosition = await bounded( + page.evaluate(() => { + const element = document.querySelector(".chat-thread"); + if (!element) return null; + const previous = element.scrollTop; + element.scrollTo({ top: 0, behavior: "instant" }); + return previous; + }), + this.readTimeout, + ); + } + // Do not write a raw screenshot first. Persist only the already-masked buffer. + const options = screenshotOptions(page, { + privacy: this.recording.privacy, + secrets: this.#secrets, + }); + options.mask.push(...secretIndices.map((index) => inputs.nth(index))); + const pixels = await page.screenshot(options); + const file = `screenshots/${String(this.recording.frames.length + 1).padStart(2, "0")}-${name}.png`; + for (const target of new Set([this.directory, this.mirrorDirectory].filter(Boolean))) + await atomicWrite(path.join(target, file), pixels); + Object.assign(frame, { + status: "saved", + file, + sha256: createHash("sha256").update(pixels).digest("hex"), + }); + } catch { + frame.reason = "CAPTURE_FAILED"; + } finally { + if (typeof scrollPosition === "number") + await bounded( + page.evaluate((previous) => { + document + .querySelector(".chat-thread") + ?.scrollTo({ top: previous, behavior: "instant" }); + }, scrollPosition), + this.readTimeout, + ).catch(() => {}); + } + frame.captureMs = Date.now() - start; + frame.at = Date.now(); + this.recording.frames.push(frame); + await writeReport(this.directory, this.recording, this.mirrorDirectory); + return frame; + } +} + +export async function finalizeVisualReport(directory, verdict, mirrorDirectory) { + let recording; + try { + recording = JSON.parse(await fs.readFile(path.join(directory, "visuals.json"), "utf8")); + } catch (error) { + if (error.code === "ENOENT") return; + throw error; + } + recording.verdict = { + status: verdict.status, + reward: verdict.reward, + ...(verdict.failures ? { failures: verdict.failures } : {}), + }; + await writeReport(directory, recording, mirrorDirectory); +} diff --git a/benchmarks/harbor/support/credentials/copilot-test-credential-cache.ps1 b/benchmarks/harbor/support/credentials/copilot-test-credential-cache.ps1 new file mode 100644 index 0000000..0fae5ba --- /dev/null +++ b/benchmarks/harbor/support/credentials/copilot-test-credential-cache.ps1 @@ -0,0 +1,114 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS +Save/restore only this user's MicroClaw Copilot token for repeated reset tests. +.DESCRIPTION +Uses Windows DPAPI CurrentUser. Never prints tokens or writes plaintext files. +Close MicroClaw before Restore, then select the provider/model through its UI. +Does not restore model configuration, chats, other accounts or sandbox policy. +#> +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [ValidateSet('Save', 'Restore', 'Status')] + [string]$Action, + [string]$StateDirectory = (Join-Path $env:USERPROFILE '.openclaw'), + [string]$OpenClawPackageDirectory, + [string]$CachePath = (Join-Path $env:LOCALAPPDATA 'MicroClawTestSecrets/copilot.dpapi'), + [switch]$IsolatedProfile +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +$OutputEncoding = [Text.UTF8Encoding]::new($false) +$cacheDirectory = Split-Path -Parent $CachePath +if ($Action -eq 'Status') { + [pscustomobject]@{ CachePath = $cachePath; Exists = (Test-Path -LiteralPath $cachePath) } + return +} + +# Only a fresh, marker-validated Harbor profile may be restored while another desktop is open. +# Normal manual Restore keeps its existing close-the-app requirement. +if ($IsolatedProfile) { + if ($Action -ne 'Restore' -or -not $env:MICROCLAW_TEST_PROFILE -or -not $env:MICROCLAW_TEST_PROFILE_TOKEN) { + throw 'Isolated restore requires the disposable profile marker.' + } + $markerPath = [IO.Path]::GetFullPath($env:MICROCLAW_TEST_PROFILE) + $profileRoot = Split-Path -Parent $markerPath + $expectedState = Join-Path $profileRoot 'state' + if ([IO.Path]::GetFullPath($StateDirectory) -ne [IO.Path]::GetFullPath($expectedState)) { + throw 'Credential restore target does not match the disposable profile.' + } + $markerItem = Get-Item -LiteralPath $markerPath + if ($markerItem.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Redirected profile marker.' } + $marker = Get-Content -LiteralPath $markerPath -Raw | ConvertFrom-Json + if ($marker.kind -ne 'microclaw.test-profile.v1' -or $marker.disposable -ne $true -or + $marker.token -ne $env:MICROCLAW_TEST_PROFILE_TOKEN) { + throw 'Invalid disposable profile marker.' + } + if (Test-Path -LiteralPath (Join-Path $StateDirectory 'agents/main/agent')) { + throw 'Isolated restore requires a fresh authentication directory.' + } +} + +foreach ($directory in @($cachePath, $StateDirectory)) { + if (-not [IO.Path]::IsPathRooted($directory)) { throw 'An absolute local path is required.' } + $currentDirectory = [IO.Path]::GetFullPath($directory) + while ($currentDirectory) { + $entry = Get-Item -LiteralPath $currentDirectory -Force -ErrorAction SilentlyContinue + if ($entry -and ($entry.Attributes -band [IO.FileAttributes]::ReparsePoint)) { + throw 'Credential caching refuses redirected directories.' + } + $currentDirectory = [IO.Path]::GetDirectoryName($currentDirectory) + } +} + +if (-not $OpenClawPackageDirectory) { + $OpenClawPackageDirectory = @( + (Join-Path $env:APPDATA 'microclaw/runtime/openclaw/node_modules/openclaw'), + (Join-Path $StateDirectory 'npm/node_modules/openclaw'), + (Join-Path $env:APPDATA 'npm/node_modules/openclaw') + ) | Where-Object { Test-Path -LiteralPath (Join-Path $_ 'package.json') } | Select-Object -First 1 +} +if (-not $OpenClawPackageDirectory) { throw 'Installed OpenClaw package was not found.' } +$nodeCommand = Get-Command node.exe -ErrorAction Stop +$adapter = Join-Path $PSScriptRoot 'copilot-test-credentials.mjs' +Add-Type -AssemblyName System.Security +$entropy = [Text.Encoding]::UTF8.GetBytes('MicroClaw-Copilot-Test-Credential-Cache-v1') +$scope = [Security.Cryptography.DataProtectionScope]::CurrentUser +$plainBytes = $null +try { + if ($Action -eq 'Save') { + $payload = (& $nodeCommand.Source $adapter export $OpenClawPackageDirectory $StateDirectory 2>$null) -join "`n" + if ($LASTEXITCODE -ne 0) { throw 'No Copilot credentials were cached; sign in and check the installed runtime.' } + try { $parsed = $payload | ConvertFrom-Json } catch { throw 'Unexpected credential runtime output; nothing was saved.' } + if ($parsed.schema -ne 1 -or $parsed.provider -ne 'github-copilot') { throw 'Invalid provider cache.' } + $plainBytes = [Text.Encoding]::UTF8.GetBytes($payload) + $encrypted = [Security.Cryptography.ProtectedData]::Protect($plainBytes, $entropy, $scope) + New-Item -ItemType Directory -Force -Path $cacheDirectory | Out-Null + $stagedCachePath = Join-Path $cacheDirectory ([Guid]::NewGuid().ToString('N') + '.dpapi') + [IO.File]::WriteAllBytes($stagedCachePath, $encrypted) + # Verify the on-disk ciphertext can be decrypted by this user. + $verified = [Security.Cryptography.ProtectedData]::Unprotect([IO.File]::ReadAllBytes($stagedCachePath), $entropy, $scope) + try { + if ([Convert]::ToBase64String($verified) -ne [Convert]::ToBase64String($plainBytes)) { + throw 'Encrypted credential cache verification failed.' + } + } finally { [Array]::Clear($verified, 0, $verified.Length) } + Move-Item -LiteralPath $stagedCachePath -Destination $cachePath -Force + [pscustomobject]@{ Action = 'Saved'; CachePath = $cachePath; ProfileCount = @($parsed.profiles.PSObject.Properties).Count; Protection = 'DPAPI CurrentUser' } + } else { + if (-not (Test-Path -LiteralPath $cachePath)) { throw 'No saved Copilot test credentials; complete the first sign-in.' } + if (-not $IsolatedProfile -and (Get-Process -Name MicroClawDesktop -ErrorAction SilentlyContinue)) { throw 'Close MicroClaw before restoring credentials.' } + $plainBytes = [Security.Cryptography.ProtectedData]::Unprotect([IO.File]::ReadAllBytes($cachePath), $entropy, $scope) + $payload = [Text.Encoding]::UTF8.GetString($plainBytes) + $result = $payload | & $nodeCommand.Source $adapter import $OpenClawPackageDirectory $StateDirectory 2>$null + if ($LASTEXITCODE -ne 0) { throw 'Copilot credential restore failed; sign in again if required.' } + $summary = ($result -join "`n") | ConvertFrom-Json + [pscustomobject]@{ Action = 'Restored'; ProfileCount = $summary.restoredProfiles; NextStep = 'Open MicroClaw and verify/select the Copilot model.' } + } +} finally { + if ($plainBytes) { [Array]::Clear($plainBytes, 0, $plainBytes.Length) } + $payload = $null + $parsed = $null +} diff --git a/benchmarks/harbor/support/credentials/copilot-test-credentials.mjs b/benchmarks/harbor/support/credentials/copilot-test-credentials.mjs new file mode 100644 index 0000000..f40b1d9 --- /dev/null +++ b/benchmarks/harbor/support/credentials/copilot-test-credentials.mjs @@ -0,0 +1,187 @@ +import fs from "node:fs/promises"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +const PROVIDER = "github-copilot"; + +export function selectCopilotProfiles(store) { + const profiles = Object.fromEntries( + Object.entries(store.profiles ?? {}).filter(([, value]) => value?.provider === PROVIDER), + ); + return validatePayload({ schema: 1, provider: PROVIDER, profiles }); +} + +export function summarizeCopilotProfiles(store) { + const credentials = Object.values(store?.profiles ?? {}).filter( + (value) => + value?.provider === PROVIDER && + value.type === "token" && + ((typeof value.token === "string" && Boolean(value.token.trim())) || + (value.tokenRef?.source === "store" && + value.tokenRef.provider === "default" && + /^GITHUB_COPILOT_TOKEN_[A-Z0-9_]+$/.test(value.tokenRef.id ?? ""))), + ); + return { provider: PROVIDER, profileCount: credentials.length }; +} + +export async function materializeCopilotProfiles(store, resolveStoredToken) { + const profiles = {}; + for (const [id, value] of Object.entries(store.profiles ?? {})) { + if (value?.provider !== PROVIDER) continue; + const credential = { ...value }; + if (credential.type === "token" && typeof credential.token !== "string") { + const ref = credential.tokenRef; + if ( + ref?.source !== "store" || + ref.provider !== "default" || + typeof ref.id !== "string" || + !/^GITHUB_COPILOT_TOKEN_[A-Z0-9_]+$/.test(ref.id) + ) { + throw new Error("Unsupported Copilot secret reference."); + } + credential.token = await resolveStoredToken(ref); + } + delete credential.tokenRef; + profiles[id] = credential; + } + return validatePayload({ schema: 1, provider: PROVIDER, profiles }); +} + +export function validatePayload(value) { + if ( + value?.schema !== 1 || + value.provider !== PROVIDER || + !value.profiles || + typeof value.profiles !== "object" || + Array.isArray(value.profiles) + ) { + throw new Error("Invalid Copilot credential cache."); + } + const entries = Object.entries(value.profiles); + if (!entries.length || entries.length > 20) throw new Error("No usable Copilot profiles."); + for (const [id, credential] of entries) { + if ( + !id || + id.length > 256 || + credential?.provider !== PROVIDER || + credential.type !== "token" || + typeof credential.token !== "string" || + !credential.token.trim() || + credential.tokenRef !== undefined + ) { + throw new Error("Unsupported Copilot credential profile."); + } + } + return { schema: 1, provider: PROVIDER, profiles: Object.fromEntries(entries) }; +} + +async function main() { + const [operation, packageDir, stateDir] = process.argv.slice(2); + if ( + !["status", "export", "import"].includes(operation) || + !packageDir || + !stateDir || + !path.isAbsolute(packageDir) || + !path.isAbsolute(stateDir) + ) { + throw new Error("Expected operation and absolute package/state directories."); + } + const metadata = JSON.parse(await fs.readFile(path.join(packageDir, "package.json"), "utf8")); + if (metadata.name !== "openclaw" || metadata.version !== "2026.10.10") { + throw new Error("Review the credential adapter before using another OpenClaw version."); + } + process.env.OPENCLAW_STATE_DIR = stateDir; + const dist = path.join(packageDir, "dist"); + const candidates = []; + for (const name of (await fs.readdir(dist)).filter((name) => + /^auth-profiles-[\w-]+\.mjs$/.test(name), + )) { + const source = await fs.readFile(path.join(dist, name), "utf8"); + if ( + source.includes("export {") && + source.includes("loadAuthProfileStoreWithoutExternalProfilesAsync") && + source.includes("upsertAuthProfileAsync") + ) + candidates.push(name); + } + if (candidates.length !== 1) throw new Error("Unsupported authentication runtime."); + const runtime = await import(pathToFileURL(path.join(dist, candidates[0])).href); + const agentDir = path.join(stateDir, "agents", "main", "agent"); + const store = await runtime.loadAuthProfileStoreWithoutExternalProfilesAsync(agentDir, { + allowKeychainPrompt: false, + }); + if (operation === "status") { + process.stdout.write(JSON.stringify(summarizeCopilotProfiles(store))); + return; + } + let config; + try { + config = JSON.parse(await fs.readFile(path.join(stateDir, "openclaw.json"), "utf8")); + } catch (error) { + if (error.code !== "ENOENT") throw error; + config = {}; + } + if (operation === "export") { + const { resolveSecretRefValues } = await import( + pathToFileURL(path.join(dist, "plugin-sdk/secret-ref-runtime.js")).href + ); + const payload = await materializeCopilotProfiles(store, async (ref) => { + const values = await resolveSecretRefValues([ref], { config, env: process.env }); + if (values.size !== 1) throw new Error("The Copilot token could not be resolved."); + return values.values().next().value; + }); + process.stdout.write(JSON.stringify(payload)); + return; + } + let input = ""; + for await (const chunk of process.stdin) { + input += chunk; + if (Buffer.byteLength(input) > 1024 * 1024) throw new Error("Credential cache is too large."); + } + const payload = validatePayload(JSON.parse(input)); + for (const [profileId, credential] of Object.entries(payload.profiles)) { + if (store.profiles?.[profileId] && store.profiles[profileId].provider !== PROVIDER) { + throw new Error("Refusing to overwrite another provider."); + } + } + const persistenceEntries = []; + for (const name of (await fs.readdir(dist)).filter((name) => + /^provider-auth-persistence-[\w-]+\.mjs$/.test(name), + )) { + const source = await fs.readFile(path.join(dist, name), "utf8"); + if ( + source.includes( + "export { persistProviderAuthProfileBatch, persistProviderAuthProfilesAfterLogin,", + ) + ) { + persistenceEntries.push(name); + } + } + if (persistenceEntries.length !== 1) + throw new Error("Unsupported protected credential persistence."); + const { persistProviderAuthProfilesAfterLogin } = await import( + pathToFileURL(path.join(dist, persistenceEntries[0])).href + ); + await persistProviderAuthProfilesAfterLogin({ + profiles: Object.entries(payload.profiles).map(([profileId, credential]) => ({ + profileId, + credential, + secretStorage: { kind: "store", namePrefix: "GITHUB_COPILOT_TOKEN" }, + })), + config, + agentDir, + stateDir, + env: process.env, + }); + process.stdout.write(JSON.stringify({ restoredProfiles: Object.keys(payload.profiles).length })); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { + main().catch(() => { + // Never echo runtime errors or input: either may contain a credential. + process.stderr.write( + "Copilot credential operation failed; check runtime compatibility and sign-in state.\n", + ); + process.exitCode = 1; + }); +} diff --git a/benchmarks/harbor/support/credentials/protect-test-secrets.ps1 b/benchmarks/harbor/support/credentials/protect-test-secrets.ps1 new file mode 100644 index 0000000..3895f5c --- /dev/null +++ b/benchmarks/harbor/support/credentials/protect-test-secrets.ps1 @@ -0,0 +1,35 @@ +#Requires -Version 5.1 +[CmdletBinding()] +param([Parameter(Mandatory = $true)][ValidateSet('Protect', 'Unprotect')][string]$Action) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +[Console]::InputEncoding = [Text.UTF8Encoding]::new($false) +[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) +$OutputEncoding = [Text.UTF8Encoding]::new($false) +Add-Type -AssemblyName System.Security +$entropy = [Text.Encoding]::UTF8.GetBytes('MicroClaw-Harbor-Secrets-v1') +$scope = [Security.Cryptography.DataProtectionScope]::CurrentUser +$bytes = $null +$plain = $null +try { + # Values travel only through private pipes, never arguments or plaintext files. + $inputText = [Console]::In.ReadToEnd() + if ($inputText.Length -gt 2097152) { throw 'Input too large' } + if ($Action -eq 'Protect') { + $bytes = [Text.Encoding]::UTF8.GetBytes($inputText) + $cipher = [Security.Cryptography.ProtectedData]::Protect($bytes, $entropy, $scope) + [Console]::Out.Write([Convert]::ToBase64String($cipher)) + } else { + $bytes = [Convert]::FromBase64String($inputText.Trim()) + $plain = [Security.Cryptography.ProtectedData]::Unprotect($bytes, $entropy, $scope) + [Console]::Out.Write([Text.Encoding]::UTF8.GetString($plain)) + } +} catch { + [Console]::Error.WriteLine('CREDENTIAL_PROTECTION_FAILED') + exit 1 +} finally { + if ($bytes) { [Array]::Clear($bytes, 0, $bytes.Length) } + if ($plain) { [Array]::Clear($plain, 0, $plain.Length) } + $inputText = $null +} diff --git a/benchmarks/harbor/support/credentials/tests/copilot-test-credentials.test.mjs b/benchmarks/harbor/support/credentials/tests/copilot-test-credentials.test.mjs new file mode 100644 index 0000000..0c9129e --- /dev/null +++ b/benchmarks/harbor/support/credentials/tests/copilot-test-credentials.test.mjs @@ -0,0 +1,97 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + materializeCopilotProfiles, + selectCopilotProfiles, + validatePayload, +} from "../copilot-test-credentials.mjs"; + +const copilot = { provider: "github-copilot", type: "token", token: "synthetic-test-token" }; + +test("exports Copilot only, excluding unrelated credentials and session state", () => { + const payload = selectCopilotProfiles({ + profiles: { + "github-copilot:github": copilot, + "other:default": { provider: "other", type: "token", token: "unrelated-secret" }, + }, + sessions: ["private-session"], + }); + assert.deepEqual(Object.keys(payload.profiles), ["github-copilot:github"]); + assert.equal(JSON.stringify(payload).includes("unrelated-secret"), false); + assert.equal(JSON.stringify(payload).includes("private-session"), false); +}); + +test("rejects empty, mixed-provider, unsupported and missing-token cache data", () => { + for (const profiles of [ + {}, + { a: { ...copilot, provider: "other" } }, + { a: { ...copilot, type: "api_key" } }, + { a: { ...copilot, token: "" } }, + ]) { + assert.throws(() => validatePayload({ schema: 1, provider: "github-copilot", profiles })); + } +}); + +test("rejects another provider envelope and keeps valid token metadata", () => { + assert.throws(() => validatePayload({ schema: 1, provider: "other", profiles: { a: copilot } })); + const credential = { ...copilot, expires: 1900000000000 }; + assert.deepEqual(selectCopilotProfiles({ profiles: { a: credential } }).profiles.a, credential); +}); + +test("resolves only the selected Copilot secret and makes the cache portable", async () => { + const ref = { source: "store", provider: "default", id: "GITHUB_COPILOT_TOKEN_FIXTURE" }; + const requested = []; + const payload = await materializeCopilotProfiles( + { + profiles: { + "github-copilot:github": { provider: "github-copilot", type: "token", tokenRef: ref }, + "other:default": { provider: "other", type: "token", tokenRef: { source: "exec" } }, + }, + }, + async (value) => { + requested.push(value); + return "synthetic-resolved-token"; + }, + ); + assert.deepEqual(requested, [ref]); + assert.deepEqual(payload.profiles["github-copilot:github"], { + provider: "github-copilot", + type: "token", + token: "synthetic-resolved-token", + }); +}); + +test("rejects arbitrary secret sources and non-Copilot store entries before resolution", async () => { + for (const tokenRef of [ + { source: "exec", provider: "default", id: "GITHUB_COPILOT_TOKEN_FIXTURE" }, + { source: "store", provider: "default", id: "UNRELATED_ACCOUNT_SECRET" }, + ]) { + let called = false; + await assert.rejects( + materializeCopilotProfiles( + { + profiles: { + a: { provider: "github-copilot", type: "token", tokenRef }, + }, + }, + async () => { + called = true; + return "unused"; + }, + ), + ); + assert.equal(called, false); + } +}); + +test("rejects portable caches that still depend on the old secret store", () => { + assert.throws(() => + validatePayload({ + schema: 1, + provider: "github-copilot", + profiles: { + a: { ...copilot, tokenRef: { source: "store" } }, + }, + }), + ); +}); diff --git a/benchmarks/harbor/tasks/goals-agent-isolation/case.mjs b/benchmarks/harbor/tasks/goals-agent-isolation/case.mjs new file mode 100644 index 0000000..0f43922 --- /dev/null +++ b/benchmarks/harbor/tasks/goals-agent-isolation/case.mjs @@ -0,0 +1,2 @@ +import { defineGoalsCase } from "../../runtime/goals-cases.mjs"; +export default defineGoalsCase("goals-agent-isolation"); diff --git a/benchmarks/harbor/tasks/goals-agent-isolation/environment/desktop.json b/benchmarks/harbor/tasks/goals-agent-isolation/environment/desktop.json new file mode 100644 index 0000000..7380275 --- /dev/null +++ b/benchmarks/harbor/tasks/goals-agent-isolation/environment/desktop.json @@ -0,0 +1,12 @@ +{ + "adapter": "microclaw_harbor.environment:WindowsDesktop", + "isolation": "disposable-application-profile", + "requires": [ + "interactive-windows", + "packaged-microclaw-with-goals", + "node", + "playwright", + "model" + ], + "securitySandbox": false +} diff --git a/benchmarks/harbor/tasks/goals-agent-isolation/instruction.md b/benchmarks/harbor/tasks/goals-agent-isolation/instruction.md new file mode 100644 index 0000000..b8aee00 --- /dev/null +++ b/benchmarks/harbor/tasks/goals-agent-isolation/instruction.md @@ -0,0 +1,5 @@ +# Goals G03: agent isolation + +Use a fresh disposable profile with the main and office-artisan agents. Through visible chat, create A's personal Todo, query it in another private A conversation, create B's Todo and query B in a new conversation. Finally ask B to complete A's exact ID. A's Todo must remain unchanged and B's list must never expose A's text. + +The model inside MicroClaw is under test. Do not directly invoke mutations, copy user state or seed expected final data. Collect native run/tool provenance and independently read the trial's persistent store. Keep failed trials and verify graceful desktop/Gateway shutdown. diff --git a/benchmarks/harbor/tasks/goals-agent-isolation/solution/solve.bat b/benchmarks/harbor/tasks/goals-agent-isolation/solution/solve.bat new file mode 100644 index 0000000..da9d1af --- /dev/null +++ b/benchmarks/harbor/tasks/goals-agent-isolation/solution/solve.bat @@ -0,0 +1,3 @@ +@echo off +node "%MICROCLAW_BENCH_ROOT%\runtime\run.mjs" +exit /b %errorlevel% diff --git a/benchmarks/harbor/tasks/goals-agent-isolation/task.toml b/benchmarks/harbor/tasks/goals-agent-isolation/task.toml new file mode 100644 index 0000000..7559f70 --- /dev/null +++ b/benchmarks/harbor/tasks/goals-agent-isolation/task.toml @@ -0,0 +1,21 @@ +schema_version = "1.4" + +[task] +name = "microclaw/goals-agent-isolation" +description = "G03: same-agent cross-conversation persistence and cross-agent Todo isolation with a real model." +keywords = ["microclaw", "goals", "todo", "isolation", "windows", "live-model"] + +[metadata] +execution = "scripted-ui" +status = "requires-live-model" + +[agent] +timeout_sec = 2400 + +[verifier] +timeout_sec = 30 +environment_mode = "shared" + +[environment] +os = "windows" +network_mode = "public" diff --git a/benchmarks/harbor/tasks/goals-agent-isolation/tests/expected.json b/benchmarks/harbor/tasks/goals-agent-isolation/tests/expected.json new file mode 100644 index 0000000..c5d2f03 --- /dev/null +++ b/benchmarks/harbor/tasks/goals-agent-isolation/tests/expected.json @@ -0,0 +1,28 @@ +{ + "schema": 1, + "task": "goals-agent-isolation", + "kind": "isolation", + "agentIds": ["main", "office-artisan"], + "titleSuffix": "报销材料", + "otherSuffix": "会议纪要", + "allowedTools": ["todo_list", "todo_add", "todo_update", "todo_delete"], + "routingTools": ["dispatch_action", "tool_search", "tool_describe"], + "requiredCheckpoints": [ + "isolated", + "initial", + "a-created", + "a-new-session", + "b-created", + "b-listed", + "cross-agent-denied", + "goals-final", + "cleanup" + ], + "turns": [ + { "name": "a-created", "agentId": "main", "operation": "create" }, + { "name": "a-new-session", "agentId": "main", "operation": "list" }, + { "name": "b-created", "agentId": "office-artisan", "operation": "create-other" }, + { "name": "b-listed", "agentId": "office-artisan", "operation": "list-other" }, + { "name": "cross-agent-denied", "agentId": "office-artisan", "operation": "deny-cross-agent" } + ] +} diff --git a/benchmarks/harbor/tasks/goals-agent-isolation/tests/test.bat b/benchmarks/harbor/tasks/goals-agent-isolation/tests/test.bat new file mode 100644 index 0000000..0a8f5b2 --- /dev/null +++ b/benchmarks/harbor/tasks/goals-agent-isolation/tests/test.bat @@ -0,0 +1,3 @@ +@echo off +node "%~dp0verify.mjs" +exit /b %errorlevel% diff --git a/benchmarks/harbor/tasks/goals-agent-isolation/tests/verify.mjs b/benchmarks/harbor/tasks/goals-agent-isolation/tests/verify.mjs new file mode 100644 index 0000000..45afe8b --- /dev/null +++ b/benchmarks/harbor/tasks/goals-agent-isolation/tests/verify.mjs @@ -0,0 +1,4 @@ +import { evaluateGoals } from "../../../runtime/goals-verifier.mjs"; +import { runVerifierIfMain } from "../../../runtime/verify.mjs"; +export const evaluate = evaluateGoals; +await runVerifierIfMain(evaluate, import.meta.url); diff --git a/benchmarks/harbor/tasks/goals-chat-lifecycle/case.mjs b/benchmarks/harbor/tasks/goals-chat-lifecycle/case.mjs new file mode 100644 index 0000000..edce891 --- /dev/null +++ b/benchmarks/harbor/tasks/goals-chat-lifecycle/case.mjs @@ -0,0 +1,2 @@ +import { defineGoalsCase } from "../../runtime/goals-cases.mjs"; +export default defineGoalsCase("goals-chat-lifecycle"); diff --git a/benchmarks/harbor/tasks/goals-chat-lifecycle/environment/desktop.json b/benchmarks/harbor/tasks/goals-chat-lifecycle/environment/desktop.json new file mode 100644 index 0000000..7380275 --- /dev/null +++ b/benchmarks/harbor/tasks/goals-chat-lifecycle/environment/desktop.json @@ -0,0 +1,12 @@ +{ + "adapter": "microclaw_harbor.environment:WindowsDesktop", + "isolation": "disposable-application-profile", + "requires": [ + "interactive-windows", + "packaged-microclaw-with-goals", + "node", + "playwright", + "model" + ], + "securitySandbox": false +} diff --git a/benchmarks/harbor/tasks/goals-chat-lifecycle/instruction.md b/benchmarks/harbor/tasks/goals-chat-lifecycle/instruction.md new file mode 100644 index 0000000..9e0de9d --- /dev/null +++ b/benchmarks/harbor/tasks/goals-chat-lifecycle/instruction.md @@ -0,0 +1,7 @@ +# Goals G01: chat lifecycle + +Run the reviewed desktop driver in a fresh disposable profile. The real model inside MicroClaw must create, read, rename, complete and delete the same personal Todo through chat. + +All user actions go through visible UI. Do not directly invoke Todo mutations, write the store, or simulate tool results. Read-only store/history observations and catalog provenance support the independent verifier. Preserve every step's evidence, including failures; never replace a failed trial with a successful rerun. + +Requires a packaged build containing `microclaw-todos` and the existing external model configuration. No connector credentials or real personal todos are used. Actual shutdown must be verified; uncertain or forced cleanup is a failure. diff --git a/benchmarks/harbor/tasks/goals-chat-lifecycle/solution/solve.bat b/benchmarks/harbor/tasks/goals-chat-lifecycle/solution/solve.bat new file mode 100644 index 0000000..da9d1af --- /dev/null +++ b/benchmarks/harbor/tasks/goals-chat-lifecycle/solution/solve.bat @@ -0,0 +1,3 @@ +@echo off +node "%MICROCLAW_BENCH_ROOT%\runtime\run.mjs" +exit /b %errorlevel% diff --git a/benchmarks/harbor/tasks/goals-chat-lifecycle/task.toml b/benchmarks/harbor/tasks/goals-chat-lifecycle/task.toml new file mode 100644 index 0000000..0d6775f --- /dev/null +++ b/benchmarks/harbor/tasks/goals-chat-lifecycle/task.toml @@ -0,0 +1,21 @@ +schema_version = "1.4" + +[task] +name = "microclaw/goals-chat-lifecycle" +description = "G01: real-model personal Todo creation, reading, editing, completion and deletion through chat." +keywords = ["microclaw", "goals", "todo", "windows", "live-model"] + +[metadata] +execution = "scripted-ui" +status = "requires-live-model" + +[agent] +timeout_sec = 2400 + +[verifier] +timeout_sec = 30 +environment_mode = "shared" + +[environment] +os = "windows" +network_mode = "public" diff --git a/benchmarks/harbor/tasks/goals-chat-lifecycle/tests/expected.json b/benchmarks/harbor/tasks/goals-chat-lifecycle/tests/expected.json new file mode 100644 index 0000000..f990941 --- /dev/null +++ b/benchmarks/harbor/tasks/goals-chat-lifecycle/tests/expected.json @@ -0,0 +1,28 @@ +{ + "schema": 1, + "task": "goals-chat-lifecycle", + "kind": "lifecycle", + "agentIds": ["main"], + "titleSuffix": "报销材料", + "updatedSuffix": "差旅报销材料", + "allowedTools": ["todo_list", "todo_add", "todo_update", "todo_delete"], + "routingTools": ["dispatch_action", "tool_search", "tool_describe"], + "requiredCheckpoints": [ + "isolated", + "initial", + "created", + "listed", + "updated", + "completed", + "deleted", + "goals-final", + "cleanup" + ], + "turns": [ + { "name": "created", "agentId": "main", "operation": "create" }, + { "name": "listed", "agentId": "main", "operation": "list" }, + { "name": "updated", "agentId": "main", "operation": "update" }, + { "name": "completed", "agentId": "main", "operation": "complete" }, + { "name": "deleted", "agentId": "main", "operation": "delete" } + ] +} diff --git a/benchmarks/harbor/tasks/goals-chat-lifecycle/tests/test.bat b/benchmarks/harbor/tasks/goals-chat-lifecycle/tests/test.bat new file mode 100644 index 0000000..0a8f5b2 --- /dev/null +++ b/benchmarks/harbor/tasks/goals-chat-lifecycle/tests/test.bat @@ -0,0 +1,3 @@ +@echo off +node "%~dp0verify.mjs" +exit /b %errorlevel% diff --git a/benchmarks/harbor/tasks/goals-chat-lifecycle/tests/verify.mjs b/benchmarks/harbor/tasks/goals-chat-lifecycle/tests/verify.mjs new file mode 100644 index 0000000..45afe8b --- /dev/null +++ b/benchmarks/harbor/tasks/goals-chat-lifecycle/tests/verify.mjs @@ -0,0 +1,4 @@ +import { evaluateGoals } from "../../../runtime/goals-verifier.mjs"; +import { runVerifierIfMain } from "../../../runtime/verify.mjs"; +export const evaluate = evaluateGoals; +await runVerifierIfMain(evaluate, import.meta.url); diff --git a/benchmarks/harbor/tests/goals.test.mjs b/benchmarks/harbor/tests/goals.test.mjs new file mode 100644 index 0000000..8fe8d6e --- /dev/null +++ b/benchmarks/harbor/tests/goals.test.mjs @@ -0,0 +1,482 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { runInNewContext } from "node:vm"; +import { sendGoalPrompt } from "../runtime/goals-desktop.mjs"; +import { evaluateGoals } from "../runtime/goals-verifier.mjs"; +import { + normalizeGoalTurn, + parseTodoState, + projectCatalog, + readTodoSnapshot, +} from "../runtime/goals-evidence.mjs"; +import { getCase } from "../runtime/cases.mjs"; +import { validateConfig, readConfig } from "../runtime/config.mjs"; +import { createProfile } from "../runtime/desktop.mjs"; + +const expectations = Object.fromEntries( + await Promise.all( + ["goals-chat-lifecycle", "goals-agent-isolation"].map(async (id) => [ + id, + JSON.parse( + await fs.readFile(new URL(`../tasks/${id}/tests/expected.json`, import.meta.url), "utf8"), + ), + ]), + ), +); +const marker = "HB-1234abcd"; +const a = { + id: "11111111-1111-4111-8111-111111111111", + agentId: "main", + text: `${marker} 报销材料`, + done: false, + revision: 1, + createdAt: "2026-11-30T00:00:00Z", + updatedAt: "2026-11-30T00:00:00Z", + reminder: null, +}; +const renamed = { ...a, text: `${marker} 差旅报销材料`, revision: 2 }; +const completed = { ...renamed, done: true, revision: 3 }; +const b = { + ...a, + id: "22222222-2222-4222-8222-222222222222", + agentId: "office-artisan", + text: `${marker} 会议纪要`, +}; +const snapshot = (items) => ({ + schema: 1, + exists: true, + sha256: "a".repeat(64), + items: structuredClone(items), +}); +const catalog = (id) => ({ + agentId: id, + tools: ["todo_list", "todo_add", "todo_update", "todo_delete"].map((id) => ({ + id, + source: "plugin", + pluginId: "microclaw-todos", + })), +}); +function golden(id) { + const expected = expectations[id]; + const points = []; + const point = (name, data) => + points.push({ name, at: points.length + 1, ok: true, ...structuredClone(data) }); + point("isolated", { + pathsVerified: true, + appSha256: "a".repeat(64), + appArchiveSha256: "b".repeat(64), + todoBundleSha256: "c".repeat(64), + }); + point("initial", { marker, state: snapshot([]), catalog: expected.agentIds.map(catalog) }); + const turn = (name, agentId, session, items, tool, value, answer = "已按要求处理。") => { + const callId = `call-${name}`; + point(name, { + agentId, + runId: `run-${name}`, + sessionKey: `agent:${agentId}:${session}`, + finalReceived: true, + routingVerified: true, + conversation: { user: "固定测试请求", assistant: answer }, + submittedPrompt: "固定测试请求", + calls: tool ? [{ id: callId, name: tool }] : [], + results: tool + ? [{ name: tool, toolCallId: callId, isError: false, dispatched: false, value }] + : [], + state: snapshot(items), + }); + }; + if (expected.kind === "lifecycle") { + turn("created", "main", "session-1", [a], "todo_add", { item: a }); + turn("listed", "main", "session-1", [a], "todo_list", { items: [a] }, a.text); + turn("updated", "main", "session-1", [renamed], "todo_update", { item: renamed }); + turn("completed", "main", "session-1", [completed], "todo_update", { item: completed }); + turn("deleted", "main", "session-1", [], "todo_delete", { deleted: a.id }); + point("goals-final", { + state: snapshot([]), + views: [{ agentId: "main", route: "/todos/main", texts: [] }], + }); + } else { + turn("a-created", "main", "session-1", [a], "todo_add", { item: a }); + turn("a-new-session", "main", "session-2", [a], "todo_list", { items: [a] }, a.text); + turn("b-created", "office-artisan", "session-3", [a, b], "todo_add", { item: b }); + turn("b-listed", "office-artisan", "session-4", [a, b], "todo_list", { items: [b] }, b.text); + turn( + "cross-agent-denied", + "office-artisan", + "session-4", + [a, b], + null, + null, + "这个 ID 不在我的目标列表中,无法完成。", + ); + point("goals-final", { + state: snapshot([a, b]), + views: [ + { agentId: "main", route: "/todos/main", texts: [a.text] }, + { agentId: "office-artisan", route: "/todos/office-artisan", texts: [b.text] }, + ], + }); + } + point("cleanup", { forced: false }); + return { schema: 1, task: id, status: "COMPLETE", checkpoints: points }; +} +const point = (e, name) => e.checkpoints.find((p) => p.name === name); + +for (const id of Object.keys(expectations)) { + test(`${id}: accepts independent state/tool proof, rejects missing checkpoints and unclean shutdown`, () => { + assert.equal(evaluateGoals(golden(id), expectations[id]).reward, 1); + for (const name of expectations[id].requiredCheckpoints) { + const e = golden(id); + e.checkpoints = e.checkpoints.filter((p) => p.name !== name); + assert.equal(evaluateGoals(e, expectations[id]).reward, 0, name); + } + const e = golden(id); + point(e, "cleanup").forced = true; + assert.equal(evaluateGoals(e, expectations[id]).reward, 0); + }); +} +test("G01 rejects prose-only success, duplicate goals, wrong IDs, stale tools and unauthorized reminders", () => { + const changes = [ + (e) => { + point(e, "created").calls = []; + point(e, "created").results = []; + }, + (e) => point(e, "created").state.items.push({ ...a, id: b.id }), + (e) => { + point(e, "updated").state.items[0].id = b.id; + }, + (e) => { + point(e, "completed").state.items[0].done = false; + }, + (e) => { + point(e, "deleted").results[0].value.deleted = b.id; + }, + (e) => { + point(e, "created").results[0].toolCallId = "old-turn"; + }, + (e) => { + point(e, "created").state.items[0].reminder = { at: "2026-12-01T00:00:00Z" }; + }, + (e) => { + point(e, "listed").results[0].value.items = []; + }, + (e) => { + point(e, "listed").runId = point(e, "created").runId; + }, + (e) => { + point(e, "initial").catalog[0].tools[0].pluginId = "lookalike"; + }, + (e) => { + point(e, "created").calls.push({ id: "forbidden", name: "exec" }); + }, + (e) => { + point(e, "goals-final").views[0].texts = [a.text]; + }, + ]; + for (const change of changes) { + const e = golden("goals-chat-lifecycle"); + change(e); + assert.equal(evaluateGoals(e, expectations[e.task]).reward, 0); + } +}); +test("G03 rejects shared sessions, foreign disclosure and cross-agent mutation", () => { + const changes = [ + (e) => { + point(e, "a-new-session").sessionKey = point(e, "a-created").sessionKey; + }, + (e) => { + point(e, "b-listed").sessionKey = "agent:main:session-4"; + }, + (e) => { + point(e, "b-listed").results[0].value.items.push(a); + }, + (e) => { + point(e, "b-listed").conversation.assistant += a.text; + }, + (e) => { + point(e, "cross-agent-denied").state.items[0].done = true; + }, + (e) => { + point(e, "cross-agent-denied").conversation.assistant = "已经标记完成。"; + }, + (e) => { + point(e, "b-created").state.items[0].text = "Changed A"; + }, + (e) => { + point(e, "goals-final").views[1].texts.push(a.text); + }, + ]; + for (const change of changes) { + const e = golden("goals-agent-isolation"); + change(e); + assert.equal(evaluateGoals(e, expectations[e.task]).reward, 0); + } +}); +test("native dispatch needs the exact plugin owner, not just a tool name", () => { + const e = golden("goals-chat-lifecycle"); + const p = point(e, "created"); + p.calls[0].name = "dispatch_action"; + Object.assign(p.results[0], { + dispatched: true, + source: "openclaw", + sourceName: "microclaw-todos", + }); + assert.equal(evaluateGoals(e, expectations[e.task]).reward, 1); + p.results[0].sourceName = "other-plugin"; + assert.equal(evaluateGoals(e, expectations[e.task]).reward, 0); +}); +test("native unlabeled OpenClaw dispatch needs independent catalog ownership and bounded inner anchors", () => { + const e = golden("goals-chat-lifecycle"), + p = point(e, "created"); + p.calls[0].name = "dispatch_action"; + Object.assign(p.results[0], { dispatched: true, source: "openclaw", sourceName: null }); + p.calls.push({ id: "tool_call:opaque:todo_add:1", name: "todo_add" }); + assert.equal(evaluateGoals(e, expectations[e.task]).reward, 1); + const extra = structuredClone(e); + point(extra, "created").calls.push({ id: "tool_call:unrelated:todo_add:2", name: "todo_add" }); + assert.equal(evaluateGoals(extra, expectations[e.task]).reward, 0); + point(e, "initial").catalog[0].tools.find((t) => t.id === "todo_add").pluginId = "other"; + assert.equal(evaluateGoals(e, expectations[e.task]).reward, 0); +}); +test("BLOCKED is only an unstarted trial and never gets reward", () => { + const expected = expectations["goals-chat-lifecycle"]; + assert.deepEqual( + evaluateGoals( + { + schema: 1, + task: expected.task, + status: "BLOCKED", + checkpoints: [], + reason: "CONFIGURATION_REQUIRED", + }, + expected, + ), + { status: "BLOCKED", reward: 0, reason: "CONFIGURATION_REQUIRED" }, + ); + const e = golden(expected.task); + e.status = "BLOCKED"; + assert.equal(evaluateGoals(e, expected).status, "FAIL"); +}); +test("state and catalog readers fail closed on unknown or contradictory structure", () => { + assert.deepEqual(parseTodoState(JSON.stringify({ version: 1, items: [a] })), [a]); + assert.throws(() => parseTodoState(JSON.stringify({ version: 2, items: [] }))); + assert.throws(() => parseTodoState(JSON.stringify({ version: 1, items: [a, a] }))); + assert.throws(() => + parseTodoState(JSON.stringify({ version: 1, items: [{ ...a, revision: 0 }] })), + ); + assert.deepEqual( + projectCatalog({ groups: [{ tools: catalog("main").tools }] }, "main"), + catalog("main"), + ); + assert.throws(() => + projectCatalog( + { groups: [{ tools: catalog("main").tools.map((t) => ({ ...t, source: "core" })) }] }, + "main", + ), + ); +}); +test("goal tool evidence only includes the selected native run", () => { + const observed = { + final: { state: "final", runId: "r", sessionKey: "agent:main:s", message: { content: "Done" } }, + tools: [ + { + runId: "r", + sessionKey: "agent:main:s", + data: { phase: "start", name: "todo_add", toolCallId: "current" }, + }, + { + runId: "old", + sessionKey: "agent:main:s", + data: { phase: "start", name: "todo_delete", toolCallId: "old" }, + }, + ], + messages: [ + { role: "user", content: "Create a goal" }, + { + toolName: "todo_add", + toolCallId: "current", + content: [{ type: "text", text: JSON.stringify({ item: a }) }], + }, + { toolName: "todo_delete", toolCallId: "old", content: [{ type: "text", text: "{}" }] }, + ], + }; + const result = normalizeGoalTurn(observed, "Create a goal"); + assert.equal(result.calls.length, 1); + assert.equal(result.results.length, 1); + assert.equal(result.results[0].value.item.id, a.id); +}); +test("multi-turn driver ignores late previous finals and waits for actual send admission", async () => { + let onChat, onTool; + let sent = 0; + const prompt = "Create a goal"; + const sessionKey = "agent:main:session-1"; + const context = { + window: { + __harborGoalTurn: { runId: "old", seenRunIds: new Set(), dispose() {} }, + openclaw: { + chat: { + onEvent: (callback) => { + onChat = callback; + return () => {}; + }, + onToolEvent: (callback) => { + onTool = callback; + return () => {}; + }, + loadHistory: async () => ({ + messages: [ + { role: "user", content: prompt }, + { + toolName: "todo_add", + toolCallId: "new-call", + content: [{ type: "text", text: JSON.stringify({ item: a }) }], + }, + ], + }), + }, + }, + }, + }; + const evaluate = (fn, args) => + runInNewContext(`(${fn.toString()})(__args)`, { ...context, __args: args }); + const page = { + evaluate, + waitForFunction: async (fn) => { + assert.equal(evaluate(fn), true); + }, + locator: (selector) => ({ + fill: async (value) => assert.equal(value, prompt), + click: async () => { + assert.equal(selector, ".home-input-send:not(.home-input-send--stop)"); + onChat({ runId: "old", sessionKey, state: "final", message: { content: "Old answer" } }); + onChat({ runId: "new", sessionKey, state: "status" }); + onTool({ + runId: "new", + sessionKey, + data: { phase: "start", name: "todo_add", toolCallId: "new-call" }, + }); + onChat({ runId: "new", sessionKey, state: "final", message: { content: "Created" } }); + }, + }), + }; + const result = await sendGoalPrompt(page, "main", prompt, async () => { + assert.equal(context.window.__harborGoalTurn.runId, "new"); + sent++; + }); + assert.equal(result.runId, "new"); + assert.equal(result.submittedPrompt, prompt); + assert.equal(sent, 1); +}); +test("Goals profiles need only model credentials and use explicit isolated agent rosters", async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "harbor-goals-test-")); + try { + const config = { + schema: 1, + appPath: path.join(root, "app.exe"), + model: { id: "synthetic", baseUrl: "https://example.invalid/v1", apiKey: "synthetic-only" }, + }; + for (const id of Object.keys(expectations)) { + assert.deepEqual(validateConfig(config, id), []); + assert.ok( + validateConfig({ ...config, uiOnly: true }, id).includes("model.inference-required"), + ); + const profile = path.join(root, id); + await createProfile(profile, config, {}, { task: getCase(id) }); + const saved = JSON.parse( + await fs.readFile(path.join(profile, "state/openclaw.json"), "utf8"), + ); + assert.equal(saved.agents.ownership, "explicit"); + assert.deepEqual(Object.keys(saved.agents.entries), expectations[id].agentIds); + assert.deepEqual(saved.tools.allow, expectations[id].allowedTools); + assert.equal(saved.plugins.entries["microclaw-todos"].enabled, true); + assert.equal(JSON.stringify(saved).includes("synthetic-only"), false); + await fs.mkdir(path.join(profile, "state/microclaw-todos")); + assert.deepEqual((await readTodoSnapshot(profile)).items, []); + await fs.writeFile( + path.join(profile, "state/microclaw-todos/todos.json"), + JSON.stringify({ version: 1, items: [a] }), + ); + assert.deepEqual((await readTodoSnapshot(profile)).items, [a]); + } + } finally { + assert.equal(path.dirname(root), os.tmpdir()); + await fs.rm(root, { recursive: true, force: true }); + } +}); +test("configuration rejects an old packaged build without Goals before starting it", async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "harbor-goals-build-")); + try { + const appPath = path.join(root, "app.exe"); + await fs.writeFile(appPath, "fixture"); + await fs.mkdir(path.join(root, "resources")); + await fs.writeFile(path.join(root, "resources/app.asar"), "microclaw.test-profile.v1"); + const configPath = path.join(root, "config.json"); + await fs.writeFile( + configPath, + JSON.stringify({ + schema: 1, + appPath, + model: { id: "fake", baseUrl: "http://127.0.0.1:9", apiKey: "fixture" }, + }), + ); + assert.ok( + (await readConfig(configPath, "goals-chat-lifecycle")).missing.includes( + "appPath.goals-support", + ), + ); + await fs.mkdir(path.join(root, "resources/microclaw-todos")); + await fs.writeFile( + path.join(root, "resources/microclaw-todos/openclaw.plugin.json"), + JSON.stringify({ + id: "microclaw-todos", + contracts: { tools: ["todo_list", "todo_add", "todo_update", "todo_delete"] }, + }), + ); + assert.ok( + (await readConfig(configPath, "goals-chat-lifecycle")).missing.includes( + "appPath.goals-support", + ), + ); + await fs.appendFile(path.join(root, "resources/app.asar"), " todos:list microclaw.todos."); + assert.deepEqual((await readConfig(configPath, "goals-chat-lifecycle")).missing, []); + } finally { + assert.equal(path.dirname(root), os.tmpdir()); + await fs.rm(root, { recursive: true, force: true }); + } +}); +test("Goal verifier writes the standard reward and result files", async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "harbor-goals-verifier-")); + try { + const evidence = path.join(root, "evidence.json"); + await fs.writeFile(evidence, JSON.stringify(golden("goals-chat-lifecycle"))); + const result = spawnSync( + process.execPath, + [fileURLToPath(new URL("../tasks/goals-chat-lifecycle/tests/verify.mjs", import.meta.url))], + { + env: { + ...process.env, + MICROCLAW_BENCH_EVIDENCE: evidence, + MICROCLAW_BENCH_REWARD: path.join(root, "verifier"), + MICROCLAW_BENCH_REPORT_DIR: "", + }, + encoding: "utf8", + timeout: 30000, + windowsHide: true, + }, + ); + assert.equal(result.status, 0, result.stderr); + assert.equal(await fs.readFile(path.join(root, "verifier/reward.txt"), "utf8"), "1"); + assert.equal( + JSON.parse(await fs.readFile(path.join(root, "verifier/result.json"))).status, + "PASS", + ); + } finally { + assert.equal(path.dirname(root), os.tmpdir()); + await fs.rm(root, { recursive: true, force: true }); + } +}); diff --git a/benchmarks/harbor/tests/model-credentials.test.mjs b/benchmarks/harbor/tests/model-credentials.test.mjs new file mode 100644 index 0000000..de3e831 --- /dev/null +++ b/benchmarks/harbor/tests/model-credentials.test.mjs @@ -0,0 +1,49 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { credentialPaths, protectConfig, resolveCredentials } from "../runtime/credentials.mjs"; + +const cipher = { + protect: async (bytes) => Buffer.from(`test-cipher:${bytes.toString("base64")}`), + unprotect: async (bytes) => Buffer.from(bytes.toString().slice("test-cipher:".length), "base64"), +}; +test("Goals accepts only model secrets and verifies protected configuration before replacing input", async () => { + assert.deepEqual(credentialPaths, ["model.apiKey"]); + const root = await fs.mkdtemp(path.join(os.tmpdir(), "goals-model-secret-")); + try { + const file = path.join(root, "goals.json"); + await fs.writeFile( + file, + JSON.stringify({ schema: 1, model: { apiKey: "synthetic-model-secret" } }), + ); + await protectConfig(file, cipher); + const text = await fs.readFile(file, "utf8"); + assert.equal(text.includes("synthetic-model-secret"), false); + const config = JSON.parse(text); + assert.deepEqual(config.model.apiKey, { $secretRef: "model.apiKey" }); + assert.equal( + (await resolveCredentials(config, file, cipher)).model.apiKey, + "synthetic-model-secret", + ); + } finally { + assert.equal(path.dirname(root), os.tmpdir()); + await fs.rm(root, { recursive: true, force: true }); + } +}); +test("a failed credential verification preserves the original input", async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "goals-model-secret-")); + try { + const file = path.join(root, "goals.json"), + original = JSON.stringify({ schema: 1, model: { apiKey: "synthetic" } }); + await fs.writeFile(file, original); + await assert.rejects( + protectConfig(file, { ...cipher, unprotect: async () => Buffer.from("wrong") }), + ); + assert.equal(await fs.readFile(file, "utf8"), original); + } finally { + assert.equal(path.dirname(root), os.tmpdir()); + await fs.rm(root, { recursive: true, force: true }); + } +}); diff --git a/benchmarks/harbor/tests/profile-hook.test.mjs b/benchmarks/harbor/tests/profile-hook.test.mjs new file mode 100644 index 0000000..b1fa4f1 --- /dev/null +++ b/benchmarks/harbor/tests/profile-hook.test.mjs @@ -0,0 +1,102 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { configureIsolatedTestProfile } from "../../../desktop/src/isolated-test-profile.ts"; + +function fixture() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "microclaw-profile-hook-")); + for (const name of [ + "home", + "appData", + "userData", + "sessionData", + "temp", + "localAppData", + "state", + ]) + fs.mkdirSync(path.join(root, name)); + const marker = path.join(root, "profile.json"); + fs.writeFileSync( + marker, + JSON.stringify({ + kind: "microclaw.test-profile.v1", + disposable: true, + token: "synthetic-marker", + }), + ); + return { + root, + marker, + env: { MICROCLAW_TEST_PROFILE: marker, MICROCLAW_TEST_PROFILE_TOKEN: "synthetic-marker" }, + }; +} +test("ordinary launches remain unchanged and test launches set every native path before use", () => { + const value = fixture(); + try { + const calls = []; + const app = { setPath: (...args) => calls.push(args) }; + assert.equal(configureIsolatedTestProfile(app, {}), false); + assert.equal(calls.length, 0); + assert.equal(configureIsolatedTestProfile(app, value.env), true); + assert.deepEqual( + calls.map((c) => c[0]), + ["home", "appData", "userData", "sessionData", "temp"], + ); + assert.equal(value.env.OPENCLAW_STATE_DIR, path.join(value.root, "state")); + assert.equal(value.env.USERPROFILE, path.join(value.root, "home")); + } finally { + fs.rmSync(value.root, { recursive: true, force: true }); + } +}); +test("invalid markers, conflicting modes, and missing directories never partially set paths", () => { + for (const change of [ + (v) => (v.env.MICROCLAW_TEST_PROFILE_TOKEN = "wrong"), + (v) => (v.env.MICROCLAW_TEST_PROFILE = "relative"), + (v) => (v.env.MICROCLAW_PERF_FIXTURE = "performance-mode"), + (v) => fs.rmdirSync(path.join(v.root, "state")), + (v) => + fs.writeFileSync( + v.marker, + JSON.stringify({ kind: "other", disposable: true, token: "synthetic-marker" }), + ), + ]) { + const value = fixture(); + try { + change(value); + const calls = []; + assert.throws(() => + configureIsolatedTestProfile({ setPath: (...args) => calls.push(args) }, value.env), + ); + assert.equal(calls.length, 0); + } finally { + fs.rmSync(value.root, { recursive: true, force: true }); + } + } +}); +test("a junction cannot redirect the native home path outside the disposable profile", () => { + const value = fixture(); + const outside = fs.mkdtempSync(path.join(os.tmpdir(), "microclaw-profile-outside-")); + try { + fs.rmdirSync(path.join(value.root, "home")); + fs.symlinkSync( + outside, + path.join(value.root, "home"), + process.platform === "win32" ? "junction" : "dir", + ); + assert.throws(() => + configureIsolatedTestProfile( + { + setPath() { + assert.fail("must validate first"); + }, + }, + value.env, + ), + ); + } finally { + fs.rmSync(value.root, { recursive: true, force: true }); + fs.rmSync(outside, { recursive: true, force: true }); + } +}); diff --git a/benchmarks/harbor/tests/test_environment.py b/benchmarks/harbor/tests/test_environment.py new file mode 100644 index 0000000..70ab06f --- /dev/null +++ b/benchmarks/harbor/tests/test_environment.py @@ -0,0 +1,118 @@ +import asyncio +import json +import os +import shutil +import tempfile +import unittest +from pathlib import Path + +from harbor.models.task.task import Task +from microclaw_harbor.environment import WindowsDesktop + +ROOT = Path(__file__).resolve().parents[1] + + +class ContractTests(unittest.TestCase): + def test_environment_folder_routes_to_its_reviewed_parent_task(self): + adapter = object.__new__(WindowsDesktop) + for name in ( + "goals-chat-lifecycle", + "goals-agent-isolation", + ): + adapter.environment_dir = ROOT / "tasks" / name / "environment" + self.assertEqual(adapter._task_name(), name) + adapter.environment_dir = ROOT / "tasks" / "unreviewed" / "environment" + with self.assertRaises(ValueError): + adapter._task_name() + + def test_task_uses_harbor_schema_and_windows_scripts(self): + for name in ( + "goals-chat-lifecycle", + "goals-agent-isolation", + ): + with self.subTest(task=name): + task = Task(ROOT / "tasks" / name) + self.assertEqual(task.config.environment.os.value, "windows") + self.assertTrue(task.paths.solve_path_for(task.config.environment.os).is_file()) + self.assertTrue(task.paths.test_path_for(task.config.environment.os).is_file()) + + def test_virtual_paths_cannot_address_the_host_or_escape_the_trial(self): + with tempfile.TemporaryDirectory() as root: + adapter = object.__new__(WindowsDesktop) + adapter.root = Path(root).resolve() + self.assertEqual( + adapter.local_path(r"C:\logs\verifier\reward.txt"), + adapter.root / "logs/verifier/reward.txt", + ) + for value in ( + r"C:\Users\someone", + r"C:\logs\..\..\outside", + r"D:\logs", + "relative", + "C:\\", + ): + with self.assertRaises(ValueError): + adapter.local_path(value) + + def test_failed_desktop_cleanup_retains_the_private_profile(self): + work = ROOT / ".work" + work.mkdir(exist_ok=True) + root = Path(tempfile.mkdtemp(prefix="trial-test-", dir=work)).resolve() + try: + (root / "workdir/profile").mkdir(parents=True) + (root / "logs/agent").mkdir(parents=True) + (root / "logs/agent/evidence.json").write_text( + json.dumps({"checkpoints": [{"name": "cleanup", "ok": False}]}), encoding="utf-8" + ) + adapter = object.__new__(WindowsDesktop) + adapter.root, adapter.process = root, None + with self.assertRaises(RuntimeError): + asyncio.run(adapter.stop()) + self.assertTrue(root.exists()) + finally: + if root.parent != work.resolve(): + raise ValueError("Invalid test cleanup path") + shutil.rmtree(root) + + def test_failed_verifier_retains_artifacts_after_graceful_cleanup(self): + work = ROOT / ".work" + work.mkdir(exist_ok=True) + root = Path(tempfile.mkdtemp(prefix="trial-test-", dir=work)).resolve() + try: + (root / "workdir/profile").mkdir(parents=True) + (root / "logs/agent").mkdir(parents=True) + (root / "logs/verifier").mkdir(parents=True) + (root / "logs/agent/evidence.json").write_text( + json.dumps( + { + "status": "COMPLETE", + "checkpoints": [{"name": "cleanup", "ok": True, "forced": False}], + } + ), + encoding="utf-8", + ) + (root / "logs/verifier/result.json").write_text( + json.dumps({"status": "FAIL"}), encoding="utf-8" + ) + adapter = object.__new__(WindowsDesktop) + adapter.root, adapter.process = root, None + asyncio.run(adapter.stop()) + self.assertTrue(root.exists()) + (root / "logs/verifier/result.json").write_text( + json.dumps({"status": "PASS"}), encoding="utf-8" + ) + deep = root / "workdir" / ("nested-" * 12) / ("package-" * 12) + native_deep = Path("\\\\?\\" + str(deep)) if os.name == "nt" else deep + native_deep.mkdir(parents=True) + (native_deep / "fixture.txt").write_text("synthetic", encoding="utf-8") + asyncio.run(adapter.stop()) + self.assertFalse(root.exists()) + finally: + if root.parent != work.resolve(): + raise ValueError("Invalid test cleanup path") + if root.exists(): + shutil.rmtree(root) + + +if __name__ == "__main__": + unittest.main() diff --git a/desktop/electron-builder.yml b/desktop/electron-builder.yml index 5ea8f55..dff0400 100644 --- a/desktop/electron-builder.yml +++ b/desktop/electron-builder.yml @@ -54,6 +54,13 @@ nsis: shortcutName: OpenClaw extraResources: + - from: ../plugins/microclaw-todos/ + to: microclaw-todos/ + filter: + - package.json + - openclaw.plugin.json + - index.mjs + - store.mjs - from: ../scripts/windows/npm-registry.ps1 to: npm-registry.ps1 - from: resources/npm-registry.json diff --git a/desktop/package.json b/desktop/package.json index c12113f..7d26a5a 100644 --- a/desktop/package.json +++ b/desktop/package.json @@ -17,7 +17,7 @@ "prepare-weixin-plugin-resource": "node scripts/prepare-weixin-plugin-resource.mjs", "prepare-windows-node-resources": "node scripts/prepare-windows-node-resources.mjs --arch=x64", "prepare-windows-node-resources:arm64": "node scripts/prepare-windows-node-resources.mjs --arch=arm64", - "test": "npm run test:weixin-runtime && npm run test:prepared-resources && vitest run", + "test": "npm run test:todos && npm run test:weixin-runtime && npm run test:prepared-resources && vitest run", "test:prepared-resources": "node --test scripts/npm-registry.test.mjs scripts/prepare-windows-node-resources.test.mjs scripts/publish-prepared-resource.test.mjs scripts/local-model-packaging.test.mjs scripts/openclaw-resource.test.mjs scripts/update-signed-windows-node-manifest.test.mjs", "test:weixin-runtime": "node --test scripts/stage-weixin-runtime.test.mjs", "test:watch": "vitest", @@ -26,7 +26,8 @@ "lint:weixin": "node scripts/lint-weixin.mjs", "lint:sarif": "eslint . --format @microsoft/eslint-formatter-sarif --output-file eslint-results.sarif", "prepare-resources": "node scripts/prepare-resources.mjs", - "postinstall": "install-electron && cd renderer && npm install" + "postinstall": "install-electron && cd renderer && npm install", + "test:todos": "node --test ../plugins/microclaw-todos/*.test.mjs" }, "devDependencies": { "@eslint/js": "^10.0.1", diff --git a/desktop/renderer/env.d.ts b/desktop/renderer/env.d.ts index 5255bf4..e75c1fc 100644 --- a/desktop/renderer/env.d.ts +++ b/desktop/renderer/env.d.ts @@ -192,6 +192,7 @@ type UpdateCheckResult = }; interface OpenClawAPI { + todos: import("../src/todos/types").TodoAPI; readonly features: { readonly githubCopilot: boolean; readonly performance?: boolean; @@ -273,7 +274,7 @@ interface OpenClawAPI { onSessionUpdate(callback: (payload: { sessionKey: string }) => void): () => void; isConnected(): Promise; sendMessage(sessionKey: string, message: string, attachments?: ChatAttachment[]): Promise; - loadHistory(sessionKey: string): Promise; + loadHistory(sessionKey: string, options?: { toolResultMaxChars?: number }): Promise; listSessionTitles(keys: string[]): Promise<{ titles: Record }>; generateSessionTitle(sessionKey: string): Promise; abort(sessionKey: string): Promise; diff --git a/desktop/renderer/src/browser-openclaw.ts b/desktop/renderer/src/browser-openclaw.ts index f165884..9f57583 100644 --- a/desktop/renderer/src/browser-openclaw.ts +++ b/desktop/renderer/src/browser-openclaw.ts @@ -21,6 +21,20 @@ export function createBrowserOpenClawMock(): OpenClawAPI { ]; return { + todos: { + list: async () => { + throw new Error("Todos require the desktop Gateway."); + }, + add: async () => { + throw new Error("Todos require the desktop Gateway."); + }, + update: async () => { + throw new Error("Todos require the desktop Gateway."); + }, + delete: async () => { + throw new Error("Todos require the desktop Gateway."); + }, + }, features: { githubCopilot: false }, gateway: { getStatus: async () => "running", diff --git a/desktop/renderer/src/components/SidePanel.vue b/desktop/renderer/src/components/SidePanel.vue index be1f221..f06773b 100644 --- a/desktop/renderer/src/components/SidePanel.vue +++ b/desktop/renderer/src/components/SidePanel.vue @@ -64,6 +64,25 @@ +
' }, +})); +const item: TodoItem = { + id: "task-1", + agentId: "main", + text: "Submit expenses", + done: false, + revision: 3, + createdAt: "2026-11-30T00:00:00Z", + updatedAt: "2026-11-30T00:00:00Z", + reminder: null, +}; +describe("TodosView", () => { + const list = vi.fn(); + const add = vi.fn(); + const update = vi.fn(); + const remove = vi.fn(); + beforeEach(() => { + setLocale("en-US"); + vi.clearAllMocks(); + context.goalDraft = { text: "" }; + context.chat.getDraft.mockReturnValue(context.goalDraft); + context.route = reactive({ params: { agentId: "main" } }); + context.agents = reactive({ + currentAgentId: "main", + agents: [ + { id: "main", name: "Assistant" }, + { id: "specialist", name: "Specialist" }, + ], + selectAgent: vi.fn(), + }); + list.mockResolvedValue({ items: [structuredClone(item)], now: "2026-11-30T00:00:00Z" }); + add.mockResolvedValue({ item }); + update.mockResolvedValue({ item }); + remove.mockResolvedValue({ deleted: item.id }); + window.openclaw = { + todos: { list, add, update, delete: remove }, + } as unknown as typeof window.openclaw; + }); + it.each([ + ["health", "Create a health goal"], + ["relationships", "Create a relationship goal"], + ["finance", "Create a finance goal"], + ["career", "Create a career goal"], + ["interests", "Create a personal interest goal"], + ["productivity", "Create a productivity goal"], + ["other", "Create a goal"], + ])("introduces the %s category before starting a conversation", async (category, title) => { + const wrapper = mount(TodosView); + await flushPromises(); + await wrapper.get(`[data-category="${category}"]`).trigger("click"); + const dialog = wrapper.get(".todo-create-dialog"); + expect(dialog.attributes("aria-label")).toBe(title); + expect(dialog.text()).toContain("First, we'll refine the goal together in chat."); + expect(dialog.find("textarea").exists()).toBe(false); + expect(context.chat.newSession).not.toHaveBeenCalled(); + expect(add).not.toHaveBeenCalled(); + await dialog.get(".todo-create-close").trigger("click"); + expect(wrapper.find(".todo-create-dialog").exists()).toBe(false); + expect(context.push).not.toHaveBeenCalled(); + wrapper.unmount(); + }); + it("starts a separate chat for the selected agent with a localized goal draft", async () => { + setLocale("zh-CN"); + context.route.params.agentId = "specialist"; + const wrapper = mount(TodosView); + await flushPromises(); + await wrapper.get('[data-category="health"]').trigger("click"); + expect(wrapper.get(".todo-create-header h2").text()).toBe("创建健康目标"); + expect(wrapper.get(".todo-create-start").text()).toBe("开始吧"); + await wrapper.get(".todo-create-start").trigger("click"); + expect(context.chat.newSession).toHaveBeenCalledExactlyOnceWith("specialist"); + expect(context.goalDraft.text).toContain("我想创建一个健康目标"); + expect(context.goalDraft.text).toContain("等我们确认后,再把目标添加到目标列表"); + expect(context.push).toHaveBeenCalledWith({ name: "chat", params: { agentId: "specialist" } }); + expect(wrapper.find(".todo-create-dialog").exists()).toBe(false); + expect(add).not.toHaveBeenCalled(); + wrapper.unmount(); + }); + it("keeps the other category open-ended and dismisses the intro on agent changes", async () => { + const wrapper = mount(TodosView); + await flushPromises(); + await wrapper.get('[data-category="health"]').trigger("click"); + context.route.params.agentId = "specialist"; + await flushPromises(); + expect(wrapper.find(".todo-create-dialog").exists()).toBe(false); + await wrapper.get('[data-category="other"]').trigger("click"); + await wrapper.get(".todo-create-start").trigger("click"); + expect(context.goalDraft.text).toContain("I'd like to create a goal."); + expect(context.goalDraft.text).not.toContain("health"); + wrapper.unmount(); + }); + it("keeps the empty message stable during background polling", async () => { + vi.useFakeTimers(); + const visible = vi.spyOn(document, "hidden", "get").mockReturnValue(false); + let finishRefresh!: (value: unknown) => void; + list.mockResolvedValueOnce({ items: [] }).mockReturnValueOnce( + new Promise((resolve) => { + finishRefresh = resolve; + }), + ); + const wrapper = mount(TodosView); + try { + await flushPromises(); + const message = wrapper.find(".todos-empty").element; + expect(message.textContent).toBe("No goals being tracked yet."); + await vi.advanceTimersByTimeAsync(5000); + expect(list).toHaveBeenCalledTimes(2); + expect(wrapper.find(".todos-empty").text()).toBe("No goals being tracked yet."); + expect(wrapper.find(".todos-empty").element).toBe(message); + finishRefresh({ items: [] }); + await flushPromises(); + expect(wrapper.find(".todos-empty").element).toBe(message); + } finally { + wrapper.unmount(); + visible.mockRestore(); + vi.useRealTimers(); + } + }); + it("records a todo without inventing a reminder and refreshes after the write", async () => { + const wrapper = mount(TodosView); + await flushPromises(); + expect(wrapper.find(".todo-compose").exists()).toBe(false); + await wrapper.find(".todo-create-manually").trigger("click"); + await wrapper.find(".todo-compose textarea").setValue("Buy paper"); + await wrapper.find(".todo-compose").trigger("submit"); + await flushPromises(); + expect(add).toHaveBeenCalledWith({ + agentId: "main", + requestId: expect.any(String), + text: "Buy paper", + remindAt: null, + }); + expect(list.mock.calls.length).toBeGreaterThanOrEqual(2); + expect(wrapper.find(".todo-compose").exists()).toBe(false); + wrapper.unmount(); + }); + it("completes the correct agent's todo with the observed revision", async () => { + const wrapper = mount(TodosView); + await flushPromises(); + await wrapper.find('.todo-row input[type="checkbox"]').setValue(true); + await flushPromises(); + expect(update).toHaveBeenCalledWith({ + agentId: "main", + requestId: expect.any(String), + id: "task-1", + revision: 3, + done: true, + }); + wrapper.unmount(); + }); + it("reuses the add request identity after an uncertain response", async () => { + add.mockRejectedValueOnce(new Error("Response lost")).mockResolvedValueOnce({ item }); + const wrapper = mount(TodosView); + await flushPromises(); + await wrapper.find(".todo-create-manually").trigger("click"); + await wrapper.find(".todo-compose textarea").setValue("Do not duplicate"); + await wrapper.find(".todo-compose").trigger("submit"); + await flushPromises(); + await wrapper.find(".todo-compose").trigger("submit"); + await flushPromises(); + expect(add.mock.calls[0][0].requestId).toBe(add.mock.calls[1][0].requestId); + wrapper.unmount(); + }); + it("does not move or rearm an existing phone reminder when only editing text", async () => { + list.mockResolvedValue({ + items: [ + { + ...item, + reminder: { + id: "reminder", + at: "2026-01-01T09:00:00Z", + status: "sent", + route: { channel: "openclaw-weixin", accountId: "a", to: "owner" }, + }, + }, + ], + }); + const wrapper = mount(TodosView); + await flushPromises(); + await wrapper.find(".todo-content").trigger("click"); + expect(wrapper.find('[role="dialog"]').text()).toContain("WeChat"); + await wrapper.find(".todo-edit textarea").setValue("Updated text"); + await wrapper.find(".todo-edit").trigger("submit"); + await flushPromises(); + expect(update).toHaveBeenCalledWith({ + agentId: "main", + requestId: expect.any(String), + id: "task-1", + revision: 3, + text: "Updated text", + }); + wrapper.unmount(); + }); + it("ignores a delayed response after switching to another agent", async () => { + let resolve!: (value: unknown) => void; + list + .mockReturnValueOnce( + new Promise((r) => { + resolve = r; + }), + ) + .mockResolvedValue({ + items: [{ ...item, id: "other", agentId: "specialist", text: "Specialist todo" }], + }); + const wrapper = mount(TodosView); + context.route.params.agentId = "specialist"; + await flushPromises(); + resolve({ items: [item] }); + await flushPromises(); + expect(wrapper.text()).toContain("Specialist todo"); + expect(wrapper.text()).not.toContain("Submit expenses"); + wrapper.unmount(); + }); + it("preserves a rejected add's draft and does not claim completion on stale-write errors", async () => { + add.mockRejectedValue(new Error("Gateway disconnected")); + update.mockRejectedValue(new Error("Todo changed. List again.")); + const wrapper = mount(TodosView); + await flushPromises(); + await wrapper.find(".todo-create-manually").trigger("click"); + await wrapper.find(".todo-compose textarea").setValue("Keep this draft"); + await wrapper.find(".todo-compose").trigger("submit"); + await flushPromises(); + expect((wrapper.find(".todo-compose textarea").element as HTMLTextAreaElement).value).toBe( + "Keep this draft", + ); + await wrapper.find(".todo-editor-actions button").trigger("click"); + await wrapper.find('.todo-row input[type="checkbox"]').setValue(true); + await flushPromises(); + expect(wrapper.find('[role="alert"]').text()).toContain("Todo changed"); + expect(wrapper.find(".todo-label").classes()).not.toContain("done"); + expect( + (wrapper.find('.todo-row input[type="checkbox"]').element as HTMLInputElement).checked, + ).toBe(false); + wrapper.unmount(); + }); +}); diff --git a/desktop/renderer/src/views/TodosView.vue b/desktop/renderer/src/views/TodosView.vue new file mode 100644 index 0000000..8ff2e59 --- /dev/null +++ b/desktop/renderer/src/views/TodosView.vue @@ -0,0 +1,907 @@ +