diff --git a/.github/scripts/binary-build-order.test.cjs b/.github/scripts/binary-build-order.test.cjs index c40103f675..ead32bfbe8 100644 --- a/.github/scripts/binary-build-order.test.cjs +++ b/.github/scripts/binary-build-order.test.cjs @@ -3,6 +3,17 @@ const fs = require("node:fs") const path = require("node:path") const test = require("node:test") const yaml = require("yaml") +const { spawnSync } = require("node:child_process") + +function python(code, args = []) { + const result = spawnSync(process.platform === "win32" ? "python" : "python3", ["-B", "-c", code, ...args], { + encoding: "utf8", windowsHide: true, timeout: 120000, + }) + assert.ifError(result.error) + assert.equal(result.signal, null, result.stderr) + assert.equal(result.status, 0, result.stdout + result.stderr) + return result.stdout +} const workflow = (name) => yaml.parse(fs.readFileSync(path.join(__dirname, "../workflows", name), "utf8")) @@ -45,3 +56,261 @@ test("npm server publication installs the locked optional dependencies once befo const build = steps.findIndex(step => step.run === 'node "$PINNED_NPM_CLI" run build --workspace packages/server') assert.ok(build > steps.indexOf(installs[0]), "build follows the frozen installation") }) + +test("native ARM smoke consumes only the successful Intel producer's immutable artifact", () => { + const { jobs } = workflow("build-and-upload.yml") + const producer = jobs["build-macos"] + const job = jobs["smoke-electron-macos-arm64"] + assert.equal(producer["runs-on"], "macos-15-intel") + assert.deepEqual(producer.outputs, { + "artifact-id": "${{ steps.electron-artifact.outputs.artifact-id }}", + "artifact-digest": "${{ steps.electron-artifact.outputs.artifact-digest }}", + "source-sha": "${{ steps.source.outputs.sha }}", + "run-id": "${{ steps.source.outputs.run-id }}", + "run-attempt": "${{ steps.source.outputs.run-attempt }}", + started: "${{ steps.source.outputs.started }}", + }) + const uploads = Object.values(jobs).flatMap(j => j.steps ?? []).filter(s => s.name?.startsWith("Upload Actions artifacts (")) + assert.equal(uploads.length, 7, "same seven desktop Actions artifacts") + const upload = producer.steps.find(s => s.id === "electron-artifact") + assert.equal(upload.name, "Upload Actions artifacts (Electron macOS)") + assert.equal(upload.if, "${{ inputs.upload_actions_artifacts }}") + assert.deepEqual(upload.with, { + name: "${{ inputs.actions_artifacts_name_prefix }}electron-macos", + path: "packages/electron-app/release/*.zip", + "retention-days": "${{ inputs.actions_artifacts_retention_days }}", + "if-no-files-found": "error", + }) + assert.match(producer.steps.find(s => s.id === "source").run, /git rev-parse HEAD/) + assert.equal(producer.steps.find(s => s.name === "Build macOS binaries (Electron)").run, + "npm run build:mac --workspace @neuralnomads/codenomad-electron-app") + assert.match(producer.steps.find(s => s.name === "Verify bundled npm resource (Electron macOS)").run, + /mac\/CodeNomad.app\/Contents\/Resources@darwin-x64 .*mac-arm64\/CodeNomad.app\/Contents\/Resources@darwin-arm64$/) + assert.ok(producer.steps.some(s => s.name === "Validate Electron macOS codesign (unzipped)")) + assert.equal(job.needs, "build-macos") + assert.equal(job.if, "${{ inputs.upload_actions_artifacts && needs.build-macos.result == 'success' }}") + assert.equal(workflow("pr-build.yml").jobs.build.with.upload_actions_artifacts, true) + assert.equal(job["runs-on"], "macos-26") + assert.equal(job["timeout-minutes"], 15) + assert.deepEqual(job.permissions, { contents: "read", actions: "read" }) + assert.equal(job["continue-on-error"], undefined) + assert.equal(job.environment, undefined) + assert.equal(job.secrets, undefined) + assert.equal(job.env, undefined) + const [checkout, node, identity, download, smoke] = job.steps + assert.equal(job.steps.length, 5) + assert.deepEqual(checkout.with, { ref: "${{ needs.build-macos.outputs.source-sha }}", "persist-credentials": false }) + assert.equal(checkout.uses, "actions/checkout@v7.0.1") + assert.equal(node.uses, "actions/setup-node@v7.1.0") + assert.deepEqual(node.with, { "node-version-file": ".node-version" }) + assert.equal(identity.env.ARTIFACT_ID, producer.outputs["artifact-id"].replace("steps.electron-artifact", "needs.build-macos")) + assert.equal(identity.env.ARTIFACT_DIGEST, "${{ needs.build-macos.outputs.artifact-digest }}") + assert.equal(identity.env.ARTIFACT_NAME, upload.with.name) + assert.equal(identity.env.PR_HEAD, "${{ github.event.pull_request.head.sha }}") + assert.equal(identity.env.GITHUB_TOKEN, "${{ github.token }}") + assert.equal(download.uses, "actions/download-artifact@v8.0.2") + assert.deepEqual(download.with, { + "artifact-ids": "${{ needs.build-macos.outputs.artifact-id }}", + path: "${{ steps.identity.outputs.download }}", + "digest-mismatch": "error", "skip-decompress": true, + }) + assert.deepEqual(smoke.env, { DOWNLOAD: "${{ steps.identity.outputs.download }}" }) + assert.match(smoke.run, /python3 \.github\/scripts\/electron-macos-archive.py "\$DOWNLOAD" "\$GITHUB_WORKSPACE" "\$\(command -v node\)"/) + for (const step of job.steps) { + assert.equal(step.if, undefined) + assert.equal(step["continue-on-error"], undefined) + assert.doesNotMatch(step.run ?? "", /\$\{\{|npm (?:ci|install)|npx|always\(|codesign.*--sign/) + if (step !== identity) assert.doesNotMatch(JSON.stringify(step), /GITHUB_TOKEN|GH_TOKEN|secrets\.|github.token/) + } +}) + +test("artifact identity rejects missing/mismatched provenance before download (API double, no network)", () => { + const script = workflow("build-and-upload.yml").jobs["smoke-electron-macos-arm64"].steps[2].run.split("<<'PY'\n")[1].split("\nPY")[0] + python(String.raw` +import contextlib, datetime, io, json, os, subprocess, sys, tempfile, urllib.request +from unittest.mock import patch, Mock +script = sys.argv[1] +source, workflow_sha, checksum = 'a' * 40, 'b' * 40, 'c' * 64 +now = datetime.datetime.now(datetime.timezone.utc) +artifact = dict(id=123, name='pr-1-' + source + '-electron-macos', expired=False, + workflow_run=dict(id=42, head_sha=source), digest='sha256:' + checksum, size_in_bytes=10, + created_at=now.isoformat(), expires_at=(now + datetime.timedelta(days=1)).isoformat()) +with tempfile.TemporaryDirectory() as tmp: + env = dict(PRODUCER_SHA=source, PRODUCER_RUN='42', PRODUCER_ATTEMPT='2', PRODUCER_STARTED=str(int(now.timestamp())-1), + GITHUB_RUN_ID='42', GITHUB_RUN_ATTEMPT='2', PR_HEAD=source, WORKFLOW_SHA=workflow_sha, + ARTIFACT_ID='123', ARTIFACT_DIGEST=checksum, ARTIFACT_NAME=artifact['name'], GITHUB_TOKEN='test-only', + GITHUB_API_URL='https://api.github.com', GITHUB_REPOSITORY='owner/repo', RUNNER_TEMP=tmp, + GITHUB_OUTPUT=tmp+'/output', GITHUB_STEP_SUMMARY=tmp+'/summary') + def execute(value, changes=None, head=source, error=False): + with patch.dict(os.environ, env | (changes or {}), clear=True), \ + patch.object(subprocess, 'check_output', return_value=head+'\n'), \ + patch.object(urllib.request, 'build_opener', return_value=Mock(open=Mock(return_value=io.BytesIO(json.dumps(value).encode())))) as opener, \ + contextlib.redirect_stdout(io.StringIO()): + try: + exec(script, {}) + except (ValueError, KeyError, TypeError): + assert error, 'unexpected rejection' + else: + assert not error, 'accepted invalid metadata' + get = opener.return_value.open + assert get.call_count <= 1 + if get.call_count: + assert opener.call_args.args[0].redirect_request(None, None, None, None, None, None) is None + request = get.call_args.args[0] + assert request.full_url == 'https://api.github.com/repos/owner/repo/actions/artifacts/123' + execute(artifact) + for changes in ({'PRODUCER_SHA':''}, {'ARTIFACT_ID':''}, {'ARTIFACT_ID':'123,456'}, {'ARTIFACT_DIGEST':''}, + {'PRODUCER_RUN':'43'}, {'PRODUCER_ATTEMPT':'1'}, {'PR_HEAD':'d'*40}): + execute(artifact, changes, error=True) + execute(artifact, head='d'*40, error=True) + for field, value in [('id',124), ('name','other'), ('expired',True), ('digest','d'*64), + ('size_in_bytes',0), ('expires_at',(now-datetime.timedelta(days=1)).isoformat()), + ('created_at',(now-datetime.timedelta(days=1)).isoformat()), + ('workflow_run',dict(id=43,head_sha=source)), ('workflow_run',dict(id=42,head_sha='d'*40))]: + execute(artifact | {field:value}, error=True) + execute({}, error=True) +print('metadata: positive and 18 fail-closed cases; no network') +`, [script]) +}) + +test("macOS ZIP validation and packaged smoke subprocess handling", () => { + python(String.raw` +import contextlib, importlib.util, io, os, pathlib, stat, struct, subprocess, sys, tempfile, warnings, zipfile +from unittest.mock import patch +spec = importlib.util.spec_from_file_location('archive', sys.argv[1]) +m = importlib.util.module_from_spec(spec) +spec.loader.exec_module(m) +warnings.simplefilter('ignore', UserWarning) +with tempfile.TemporaryDirectory() as tmp: + root = pathlib.Path(tmp) + sequence = 0 + def zip_path(entries): + global sequence + sequence += 1 + p = root / (str(sequence)+'.zip') + with zipfile.ZipFile(p, 'w') as z: + for name, kind, content in entries: + i = zipfile.ZipInfo(name) + i.filename = name # Keep deliberately hostile raw names on Windows too. + i.create_system = 3 + i.external_attr = ((kind | 0o755) << 16) + z.writestr(i, content) + return p + F, D, L = stat.S_IFREG, stat.S_IFDIR, stat.S_IFLNK + base = [('CodeNomad.app/',D,b''), ('CodeNomad.app/Contents/',D,b'')] + def rejected(p, outer=False, reason=None): + try: + m.validate(p, outer) + except (ValueError, zipfile.BadZipFile, UnicodeError) as error: + if reason is not None: + assert str(error) == reason, (p, str(error)) + return + raise AssertionError('accepted unsafe ZIP: '+str(p)) + framework = base + [ + ('CodeNomad.app/Contents/F.framework/Versions/A/bin',F,b'binary'), + ('CodeNomad.app/Contents/F.framework/Versions/Current',L,b'A'), + ('CodeNomad.app/Contents/F.framework/bin',L,b'Versions/Current/bin')] + m.validate(zip_path(framework)) + m.validate(zip_path(base+[('__MACOSX/._CodeNomad.app',F,b'appledouble')])) + # Clear UTF-8 bit in BOTH local and central records; bytes stay UTF-8, as ditto writes them. + def unflag(p): + raw = bytearray(p.read_bytes()) + for signature, flag_offset in ((b'PK\x03\x04',6),(b'PK\x01\x02',8)): + start = 0 + while (start := raw.find(signature,start)) >= 0: + flags = struct.unpack_from('1 and str(command[1]).endswith('smoke-packaged-resources.cjs') + if is_smoke: + assert command[-1] == str(exe) and command[-3] == 'darwin-arm64' + assert command[3] == str(resources) + output = markers + if bad == program: output = 'x64' + if is_smoke and bad == 'skip': output += 'skipping executable smoke' + if is_smoke and bad == 'marker': output = 'no markers' + return subprocess.CompletedProcess(command, 17 if is_smoke and bad=='exit' else 0, output) + with patch.object(m.subprocess,'run',side_effect=fake), patch.dict(os.environ,{'GITHUB_TOKEN':'do-not-inherit','NODE_OPTIONS':'hostile'}), contextlib.redirect_stdout(io.StringIO()): + try: m.smoke(app,root,pathlib.Path('/control/node'),private,arch) + except (ValueError,subprocess.CalledProcessError): + assert arch!='ARM64' or bad + else: assert arch=='ARM64' and not bad + return calls + trial() + assert not trial(arch='X64') + for bad in ('uname','node','sysctl','lipo','CodeNomad','skip','marker','exit'): + trial(bad=bad) + aliases = [ + [('CodeNomad.app/A',L,b'.'), ('CodeNomad.app/link',L,b'a/../inside')], + [('CodeNomad.app/É',L,b'.'), ('CodeNomad.app/link',L,'E\u0301/../inside'.encode())], + [('CodeNomad.app/A',L,b'.'), ('CodeNomad.app/bridge',L,b'a/../inside'), ('CodeNomad.app/link',L,b'bridge')], + [('CodeNomad.app/A',L,b'a/../inside')], + [('CodeNomad.app/Dir/',D,b''), ('CodeNomad.app/Dir/A',L,b'.'), ('CodeNomad.app/link',L,b'Dir/a/../../inside')], + [('CodeNomad.app/Dir/file',F,b'x'), ('CodeNomad.app/link',L,b'dir/../inside')], + ] + for entries in aliases: + rejected(zip_path(base+[('CodeNomad.app/inside',F,b'benign')]+entries), reason='macOS link prefix alias') +`, [path.join(__dirname, "electron-macos-archive.py")]) +}) diff --git a/.github/scripts/download-cache.cjs b/.github/scripts/download-cache.cjs index cef657896b..64d0954bdd 100644 --- a/.github/scripts/download-cache.cjs +++ b/.github/scripts/download-cache.cjs @@ -20,12 +20,39 @@ const APPIMAGE_PLUGIN_FILE = "linuxdeploy-plugin-appimage.AppImage" const sha256 = (data) => crypto.createHash("sha256").update(data).digest("hex") const read = (file) => fs.readFileSync(path.join(root, file), "utf8") -function lockedVersion(lock, name) { - const version = lock.packages?.[`node_modules/${name}`]?.version - if (!version) throw new Error(`package-lock.json does not lock ${name} at the root`) +function lockedVersion(lock, name, workspace) { + const key = `node_modules/${name}` + const local = workspace && lock.packages?.[`${workspace}/${key}`] + const version = (local || lock.packages?.[key])?.version + if (!version) throw new Error(`package-lock.json does not lock ${name} for ${workspace ?? "the root"}`) return version } +function appBuilderVersion(lock) { + let selected + for (const owner of ["packages/electron-app/node_modules/app-builder-bin", "node_modules/app-builder-bin"]) { + if (!Object.hasOwn(lock.packages ?? {}, owner)) continue + const entry = lock.packages[owner] + let url + try { if (typeof entry?.resolved === "string") url = new URL(entry.resolved) } catch {} + if (!entry || typeof entry !== "object" || Array.isArray(entry) + || typeof entry.version !== "string" || entry.version !== entry.version.trim() + || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.test(entry.version) + || !url || !entry.resolved.startsWith("https://") || /\s/.test(entry.resolved) + || url.protocol !== "https:" || !url.hostname || url.username || url.password + || typeof entry.integrity !== "string" || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(entry.integrity) + || Buffer.from(entry.integrity.slice(7), "base64").toString("base64") !== entry.integrity.slice(7)) { + throw new Error(`package-lock.json has an invalid app-builder-bin identity at ${owner}`) + } + if (selected && ["version", "resolved", "integrity"].some((field) => selected[field] !== entry[field])) { + throw new Error("package-lock.json has conflicting app-builder-bin identities") + } + selected = entry + } + if (!selected) throw new Error("package-lock.json does not lock app-builder-bin for packages/electron-app") + return selected.version +} + // Defaults shared by @electron/get (env-paths), app-builder (GetCacheDirectory) // and tauri-bundler (dirs::cache_dir). function cacheHome({ env, platform, home }) { @@ -60,7 +87,8 @@ function spec(kind, host, inputs) { const paths = [electronDir(host)] // electron-builder's own downloads: fpm (deb) and winCodeSign (rcedit). if (platform !== "darwin") paths.push(path.join(cacheHome(host), "electron-builder", platform === "win32" ? "Cache" : "")) - const key = `electron-${id}-${lockedVersion(lock, "electron")}-app-builder-bin-${lockedVersion(lock, "app-builder-bin")}` + const workspace = "packages/electron-app" + const key = `electron-${id}-${lockedVersion(lock, "electron", workspace)}-app-builder-bin-${appBuilderVersion(lock)}` return { key, paths } } if (kind === "cargo") { diff --git a/.github/scripts/download-cache.test.cjs b/.github/scripts/download-cache.test.cjs index 083fbc4466..87b554eb66 100644 --- a/.github/scripts/download-cache.test.cjs +++ b/.github/scripts/download-cache.test.cjs @@ -12,7 +12,10 @@ const sha256 = (data) => crypto.createHash("sha256").update(data).digest("hex") const workflow = (name) => yaml.parse(fs.readFileSync(path.join(__dirname, "../workflows", name), "utf8"), { strict: true, uniqueKeys: true }) const packageLock = JSON.stringify({ packages: { "node_modules/electron": { version: "45.2.3" }, - "node_modules/app-builder-bin": { version: "4.0.0" }, + "node_modules/app-builder-bin": { + version: "4.0.0", resolved: "https://registry.npmjs.org/app-builder-bin/-/app-builder-bin-4.0.0.tgz", + integrity: `sha512-${Buffer.alloc(64).toString("base64")}`, + }, "node_modules/@tauri-apps/cli": { version: "2.12.4" }, } }) const crate = (name, version, checksum, source = "registry+https://github.com/rust-lang/crates.io-index") => @@ -39,6 +42,72 @@ test("Electron caches are keyed by the locked Electron and app-builder versions assert.deepEqual(electronTargets(windows), ["win32-x64"]) }) +test("Electron cache resolves the real workspace lock", () => { + const realPackageLock = fs.readFileSync(path.join(__dirname, "../../package-lock.json"), "utf8") + const { packages } = JSON.parse(realPackageLock) + const bin = packages["packages/electron-app/node_modules/app-builder-bin"] + assert.equal(spec("electron", linux, { packageLock: realPackageLock }).key.split("-app-builder-bin-").at(-1), bin.version) +}) + +test("Electron cache refuses absent or unrelated app-builder-bin owners", () => { + for (const unrelated of [null, "packages/other/node_modules/app-builder-bin", "packages/electron-app/other/node_modules/app-builder-bin"]) { + const lock = JSON.parse(packageLock) + const bin = lock.packages["node_modules/app-builder-bin"] + delete lock.packages["node_modules/app-builder-bin"] + if (unrelated) lock.packages[unrelated] = bin + assert.throws(() => spec("electron", linux, { packageLock: JSON.stringify(lock) }), /app-builder-bin/) + } +}) + +test("Electron cache validates every present app-builder-bin identity", () => { + const valid = JSON.parse(packageLock).packages["node_modules/app-builder-bin"] + const malformed = [null, false, 4, "4.0.0", [], + ...[undefined, "", 4, "^4.0.0", "4.0", "04.0.0", "4.0.0\n", "4.0.0-01"].map(version => ({ ...valid, version })), + ...[undefined, "", 4, "not a URL", "http://example.com/bin.tgz", "https:example.com/bin.tgz", "https://", "https://example.com/a b"].map(resolved => ({ ...valid, resolved })), + ...[undefined, "", 4, "sha256-abc", "sha512-abc", `sha512-${"A".repeat(85)}B==`].map(integrity => ({ ...valid, integrity })), + ] + for (const owner of ["node_modules/app-builder-bin", "packages/electron-app/node_modules/app-builder-bin"]) { + for (const entry of malformed) { + for (const withValidOther of [false, true]) { + const lock = JSON.parse(packageLock) + delete lock.packages["node_modules/app-builder-bin"] + if (withValidOther) lock.packages[owner === "node_modules/app-builder-bin" ? "packages/electron-app/node_modules/app-builder-bin" : "node_modules/app-builder-bin"] = valid + lock.packages[owner] = entry + assert.throws(() => spec("electron", linux, { packageLock: JSON.stringify(lock) }), /app-builder-bin/, JSON.stringify({ owner, entry, withValidOther })) + } + } + } +}) + +test("Electron cache refuses conflicts in each app-builder-bin identity field", () => { + for (const patch of [ + { version: "4.2.0" }, + { resolved: "https://example.com/app-builder-bin.tgz" }, + { integrity: `sha512-${Buffer.alloc(64, 1).toString("base64")}` }, + ]) { + const lock = JSON.parse(packageLock) + lock.packages["packages/electron-app/node_modules/app-builder-bin"] = { ...lock.packages["node_modules/app-builder-bin"], ...patch } + assert.throws(() => spec("electron", linux, { packageLock: JSON.stringify(lock) }), /app-builder-bin/) + } +}) + +test("Electron cache accepts identical app-builder-bin copies independently of key order", () => { + const lock = JSON.parse(packageLock) + lock.packages["packages/electron-app/node_modules/app-builder-bin"] = { ...lock.packages["node_modules/app-builder-bin"] } + for (const packages of [lock.packages, Object.fromEntries(Object.entries(lock.packages).reverse())]) { + for (const host of [linux, windows, mac]) { + assert.deepEqual(spec("electron", host, { packageLock: JSON.stringify({ packages }) }), spec("electron", host, { packageLock })) + } + } +}) + +test("Electron cache keys use the app workspace's Electron version before the hoisted version", () => { + const lock = JSON.parse(packageLock) + lock.packages["packages/electron-app/node_modules/electron"] = { version: "45.2.4" } + assert.equal(spec("electron", linux, { packageLock: JSON.stringify(lock) }).key, + "electron-linux-x64-45.2.4-app-builder-bin-4.0.0") +}) + test("Cargo caches only download directories, keyed by the lockfile whatever its line endings", () => { const lock = crate("serde", "1.0.0", "aa") const result = spec("cargo", linux, { cargoLock: lock }) diff --git a/.github/scripts/electron-macos-archive.py b/.github/scripts/electron-macos-archive.py new file mode 100644 index 0000000000..33b559089c --- /dev/null +++ b/.github/scripts/electron-macos-archive.py @@ -0,0 +1,265 @@ +"""Private CI gate for the macOS Electron artifact; Python standard library only.""" +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import stat +import struct +import subprocess +import sys +import tempfile +import unicodedata +import zipfile + + +ARM_ZIP = re.compile(r"CodeNomad-Electron-macos-arm64-[A-Za-z0-9.+_-]+\.zip") +MAX_ARCHIVE = 1024 ** 3 + + +def require(ok, message): + if not ok: + raise ValueError(message) + + +def key(name): + return unicodedata.normalize("NFD", name).casefold() + + +def parts(name): + require(name and "\x00" not in name and "\\" not in name, "invalid ZIP name") + require(not name.endswith("//"), "ambiguous directory suffix") + require(not name.startswith("/") and not re.match(r"^[A-Za-z]:", name), "absolute ZIP name") + result = name.rstrip("/").split("/") + require(all(p not in ("", ".", "..") and ":" not in p for p in result), "unsafe ZIP path") + return result + + +def digest(path): + with open(path, "rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() + + +def check_extra(extra): + offset = 0 + while offset < len(extra): + require(offset + 4 <= len(extra), "malformed ZIP extra") + tag, size = struct.unpack_from("= 0 and len(tail) >= end + 22, "missing ZIP end") + require(end + 22 + struct.unpack_from("> 16 + kind = stat.S_IFMT(mode) + require(kind in (0, stat.S_IFREG, stat.S_IFDIR, stat.S_IFLNK), "special ZIP entry") + directory = info.is_dir() + require(not directory or kind in (0, stat.S_IFDIR), "ZIP directory type") + require(kind != stat.S_IFDIR or directory, "ZIP directory suffix") + require(not info.external_attr & 0x10 or directory, "DOS directory suffix") + require(not info.flag_bits & 1 and info.compress_type in (0, 8), "encrypted/unsupported ZIP") + require(info.file_size <= MAX_ARCHIVE and info.file_size <= max(1, info.compress_size) * 1000, + "ZIP expansion bound") + check_extra(info.extra) + with path.open("rb") as raw: + raw.seek(info.header_offset) + header = raw.read(30) + require(len(header) == 30 and header[:4] == b"PK\x03\x04", "bad local ZIP header") + flags, method = struct.unpack_from(" 1, "escaping link") + resolved.pop() + continue + resolved.append(bit) + current = "/".join(resolved) + require(resolved[0] == "CodeNomad.app", "link outside app") + require(aliases.get(key(current), current) == current, "macOS link prefix alias") + if current in links: + require(current not in seen, "link cycle") + seen.add(current) + pending = links[current].split("/") + pending + resolved.pop() + destination = "/".join(resolved) + require(destination in entries or any(n.startswith(destination + "/") for n in entries), + "dangling link") + if outer: + candidates = [i for n, (i, _) in entries.items() if ARM_ZIP.fullmatch(n)] + require(len(candidates) == 1, "expected exactly one ARM ZIP") + return candidates[0].filename + require("CodeNomad.app" not in entries or entries["CodeNomad.app"][1] == "dir", "app root type") + return digest(path) + + +def run(command, env, cwd): + result = subprocess.run([str(c) for c in command], env=env, cwd=cwd, text=True, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=240) + print(result.stdout, end="", flush=True) + result.check_returncode() + return result.stdout.strip() + + +def smoke(app, source, node, private, runner_arch): + """All native commands, including the packaged process, get a positive environment.""" + env = {"PATH": f"{node.parent}:/usr/bin:/bin:/usr/sbin:/sbin", "LANG": "en_US.UTF-8", + "HOME": str(private / "home"), "TMPDIR": str(private / "tmp"), + "XDG_CONFIG_HOME": str(private / "config"), "XDG_CACHE_HOME": str(private / "cache"), + "XDG_DATA_HOME": str(private / "data"), "CLI_CONFIG": str(private / "config/config.yaml"), + "CODENOMAD_PROFILE": "ci-arm-smoke", "CLI_UI_NO_UPDATE": "1", + "ELECTRON_RUN_AS_NODE": "1", "ELECTRON_NO_ASAR": "1", + "npm_config_offline": "true", "npm_config_update_notifier": "false", + "npm_config_audit": "false", "npm_config_fund": "false", + "npm_config_userconfig": str(private / "config/npmrc"), + "npm_config_cache": str(private / "cache/npm")} + for name in ("home", "tmp", "config", "cache", "data"): + (private / name).mkdir() + require(runner_arch == "ARM64", "RUNNER_ARCH must be ARM64") + require(run(["/usr/bin/uname", "-m"], env, private) == "arm64", "non-ARM kernel") + require(run([node, "-p", "process.platform + '/' + process.arch"], env, private) == "darwin/arm64", + "non-ARM host Node") + # -i returns empty for the absent proc_translated key on native ARM. + translated = run(["/usr/sbin/sysctl", "-in", "sysctl.proc_translated"], env, private) + require(translated in ("", "0"), "Rosetta process") + exe, resources = app / "Contents/MacOS/CodeNomad", app / "Contents/Resources" + require(exe.is_file() and os.access(exe, os.X_OK) and resources.is_dir(), "missing bundle runtime") + require((resources / "app.asar").is_file(), "missing bundle resource: app.asar") + require((resources / "server/dist/bin.js").is_file() + and (resources / "node/darwin-arm64/npm/bin/npm-cli.js").is_file(), + "missing bundle runtime files") + run(["/usr/bin/codesign", "--verify", "--deep", "--strict", app], env, private) + require(run(["/usr/bin/lipo", "-archs", exe], env, private) == "arm64", "non-ARM executable slice") + require(run([exe, "-p", "process.platform + '/' + process.arch"], env, private) == "darwin/arm64", + "non-ARM packaged process") + script = source / "scripts/smoke-packaged-resources.cjs" + output = run([node, script, "--resources", resources, "--target", "darwin-arm64", "--electron", exe], + env, private) + require("skipping executable smoke" not in output, "executable smoke skipped") + for marker in ("packaged server static checks ok for darwin-arm64", "Electron's integrated Node version ok:", + "bundled npm ", " engine ok:", "packaged dependency imports ok"): + require(marker in output, "missing smoke success marker: " + marker) + + +def qualify(download, source, node): + os.umask(0o077) + runner_temp = Path(os.environ["RUNNER_TEMP"]).resolve(strict=True) + require(download.is_relative_to(runner_temp) and download.is_dir() and not download.is_symlink(), + "download outside RUNNER_TEMP") + files = list(download.iterdir()) + require(len(files) == 1 and files[0].is_file() and not files[0].is_symlink(), "expected one outer ZIP") + with tempfile.TemporaryDirectory(prefix="electron-arm-", dir=runner_temp) as directory: + private = Path(directory) + outer = private / "artifact.zip" + require(files[0].stat().st_size <= MAX_ARCHIVE, "outer archive too large") + shutil.copyfile(files[0], outer) + outer.chmod(0o400) + selected = validate(outer, outer=True) + payload = private / "payload.zip" + with zipfile.ZipFile(outer, metadata_encoding="utf-8") as archive: + with archive.open(selected) as src, payload.open("xb") as dst: + shutil.copyfileobj(src, dst) + payload.chmod(0o400) + sha = validate(payload) + print(json.dumps({"payload_name": selected, "payload_sha256": sha, + "outer_sha256": digest(outer)}), flush=True) + extracted = private / "extracted" + extracted.mkdir() + subprocess.run(["/usr/bin/ditto", "-x", "-k", str(payload), str(extracted)], + env={"PATH": "/usr/bin:/bin", "HOME": str(private), "LANG": "en_US.UTF-8"}, + check=True, timeout=240) + require(digest(payload) == sha, "payload changed during extraction") + require({p.name for p in extracted.iterdir()} == {"CodeNomad.app"}, "unexpected extracted root") + app = extracted / "CodeNomad.app" + require(app.is_dir() and not app.is_symlink(), "invalid extracted app") + for root, dirs, files in os.walk(app, followlinks=False): + for name in dirs + files: + path = Path(root) / name + require(path.resolve(strict=True).is_relative_to(app), "extracted path escaped app") + require(stat.S_IFMT(path.lstat().st_mode) in (stat.S_IFDIR, stat.S_IFREG, stat.S_IFLNK), + "extracted special entry") + smoke(app, source, node, private, os.environ.get("RUNNER_ARCH")) + print("Native ARM packaged smoke passed (exit 0)", flush=True) + + +if __name__ == "__main__": + try: + qualify(Path(sys.argv[1]).absolute(), Path(sys.argv[2]).resolve(strict=True), + Path(sys.argv[3]).resolve(strict=True)) + except Exception as error: + print(f"Electron ARM qualification failed: {error}", file=sys.stderr) + sys.exit(1) diff --git a/.github/workflows/build-and-upload.yml b/.github/workflows/build-and-upload.yml index 757ed77aab..ca4cf9599a 100644 --- a/.github/workflows/build-and-upload.yml +++ b/.github/workflows/build-and-upload.yml @@ -62,6 +62,13 @@ jobs: build-macos: needs: build-tauri-windows runs-on: macos-15-intel + outputs: + artifact-id: ${{ steps.electron-artifact.outputs.artifact-id }} + artifact-digest: ${{ steps.electron-artifact.outputs.artifact-digest }} + source-sha: ${{ steps.source.outputs.sha }} + run-id: ${{ steps.source.outputs.run-id }} + run-attempt: ${{ steps.source.outputs.run-attempt }} + started: ${{ steps.source.outputs.started }} env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} VERSION: ${{ inputs.version }} @@ -72,6 +79,16 @@ jobs: with: ref: ${{ inputs.ref || github.ref }} + - name: Record Electron producer source + id: source + shell: bash + run: | + set -euo pipefail + echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + echo "run-id=$GITHUB_RUN_ID" >> "$GITHUB_OUTPUT" + echo "run-attempt=$GITHUB_RUN_ATTEMPT" >> "$GITHUB_OUTPUT" + echo "started=$(date +%s)" >> "$GITHUB_OUTPUT" + - name: Setup Node uses: actions/setup-node@v7.1.0 with: @@ -236,6 +253,7 @@ jobs: done - name: Upload Actions artifacts (Electron macOS) + id: electron-artifact if: ${{ inputs.upload_actions_artifacts }} uses: actions/upload-artifact@v7.0.2 with: @@ -244,6 +262,103 @@ jobs: retention-days: ${{ inputs.actions_artifacts_retention_days }} if-no-files-found: error + smoke-electron-macos-arm64: + needs: build-macos + if: ${{ inputs.upload_actions_artifacts && needs.build-macos.result == 'success' }} + runs-on: macos-26 + timeout-minutes: 15 + permissions: + contents: read + actions: read + steps: + - name: Checkout producer source + uses: actions/checkout@v7.0.1 + with: + ref: ${{ needs.build-macos.outputs.source-sha }} + persist-credentials: false + + - name: Setup host Node + uses: actions/setup-node@v7.1.0 + with: + node-version-file: .node-version + + - name: Verify producer and artifact identity + id: identity + shell: bash + env: + GITHUB_TOKEN: ${{ github.token }} + PRODUCER_SHA: ${{ needs.build-macos.outputs.source-sha }} + PRODUCER_RUN: ${{ needs.build-macos.outputs.run-id }} + PRODUCER_ATTEMPT: ${{ needs.build-macos.outputs.run-attempt }} + PRODUCER_STARTED: ${{ needs.build-macos.outputs.started }} + ARTIFACT_ID: ${{ needs.build-macos.outputs.artifact-id }} + ARTIFACT_DIGEST: ${{ needs.build-macos.outputs.artifact-digest }} + ARTIFACT_NAME: ${{ inputs.actions_artifacts_name_prefix }}electron-macos + PR_HEAD: ${{ github.event.pull_request.head.sha }} + WORKFLOW_SHA: ${{ github.sha }} + run: | + set -euo pipefail + python3 - <<'PY' + import datetime, json, os, re, subprocess, tempfile, urllib.request + e = os.environ + def require(ok, message): + if not ok: + raise ValueError(message) + def sha(value): + require(re.fullmatch(r'[0-9a-f]{40}', value), 'malformed source SHA') + return value + def digest(value): + value = value.removeprefix('sha256:') + require(re.fullmatch(r'[0-9a-f]{64}', value), 'malformed artifact digest') + return value + source = sha(e['PRODUCER_SHA']) + require(subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip() == source, 'checkout mismatch') + if e['PR_HEAD']: + require(source == sha(e['PR_HEAD']), 'PR head mismatch') + require(e['PRODUCER_RUN'] == e['GITHUB_RUN_ID'] and e['PRODUCER_ATTEMPT'] == e['GITHUB_RUN_ATTEMPT'], 'producer run/attempt mismatch') + require(re.fullmatch(r'[1-9][0-9]*', e['ARTIFACT_ID']), 'malformed artifact ID') + expected = digest(e['ARTIFACT_DIGEST']) + require(re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', e['GITHUB_REPOSITORY']), 'malformed repository') + request = urllib.request.Request(e['GITHUB_API_URL'] + '/repos/' + e['GITHUB_REPOSITORY'] + '/actions/artifacts/' + e['ARTIFACT_ID'], headers={ + 'Authorization': 'Bearer ' + e['GITHUB_TOKEN'], 'Accept': 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28'}) + redirect = urllib.request.HTTPRedirectHandler() + redirect.redirect_request = lambda *args, **kwargs: None + with urllib.request.build_opener(redirect).open(request, timeout=30) as response: + raw = response.read(1024 * 1024 + 1) + require(len(raw) <= 1024 * 1024, 'oversized artifact metadata') + artifact = json.loads(raw) + require(type(artifact['id']) is int and str(artifact['id']) == e['ARTIFACT_ID'], 'artifact ID mismatch') + require(artifact['name'] == e['ARTIFACT_NAME'] and artifact['expired'] is False, 'artifact name/expiration mismatch') + require(artifact['workflow_run']['id'] == int(e['GITHUB_RUN_ID']), 'artifact run mismatch') + require(artifact['workflow_run']['head_sha'] == sha(e['PR_HEAD'] or e['WORKFLOW_SHA']), 'artifact workflow head mismatch') + require(digest(artifact['digest']) == expected, 'producer digest mismatch') + now = datetime.datetime.now(datetime.timezone.utc) + require(datetime.datetime.fromisoformat(artifact['expires_at'].replace('Z', '+00:00')) > now, 'artifact expired') + require(datetime.datetime.fromisoformat(artifact['created_at'].replace('Z', '+00:00')).timestamp() >= int(e['PRODUCER_STARTED']), 'artifact predates producer attempt') + require(type(artifact['size_in_bytes']) is int and 0 < artifact['size_in_bytes'] <= 1024 ** 3, 'artifact size bound') + os.umask(0o077) + download = tempfile.mkdtemp(prefix='electron-arm-download-', dir=e['RUNNER_TEMP']) + with open(e['GITHUB_OUTPUT'], 'a') as output: + output.write('download=' + download + '\n') + PY + + - name: Download exact producer artifact without extraction + uses: actions/download-artifact@v8.0.2 + with: + artifact-ids: ${{ needs.build-macos.outputs.artifact-id }} + path: ${{ steps.identity.outputs.download }} + digest-mismatch: error + skip-decompress: true + + - name: Validate archives and execute packaged ARM smoke + shell: bash + env: + DOWNLOAD: ${{ steps.identity.outputs.download }} + run: | + set -euo pipefail + umask 077 + python3 .github/scripts/electron-macos-archive.py "$DOWNLOAD" "$GITHUB_WORKSPACE" "$(command -v node)" + build-windows: needs: build-tauri-windows runs-on: windows-2025 @@ -1134,6 +1249,8 @@ jobs: libgtk-3-dev \ libglib2.0-dev \ libwebkit2gtk-4.1-dev \ + libgstreamer-plugins-base1.0-dev \ + gstreamer1.0-plugins-good \ libsoup-3.0-dev \ libayatana-appindicator3-dev \ librsvg2-dev @@ -1394,6 +1511,8 @@ jobs: libgtk-3-dev:arm64 \ libglib2.0-dev:arm64 \ libwebkit2gtk-4.1-dev:arm64 \ + libgstreamer-plugins-base1.0-dev:arm64 \ + gstreamer1.0-plugins-good:arm64 \ libsoup-3.0-dev:arm64 \ libayatana-appindicator3-dev:arm64 \ librsvg2-dev:arm64 @@ -1412,6 +1531,8 @@ jobs: CODENOMAD_NODE_TARGET: linux-arm64 TAURI_BUILD_TARGET: aarch64-unknown-linux-gnu PKG_CONFIG_PATH: /usr/lib/aarch64-linux-gnu/pkgconfig + GSTREAMER_PLUGINS_DIR: /usr/lib/aarch64-linux-gnu/gstreamer-1.0 + GSTREAMER_HELPERS_DIR: /usr/lib/aarch64-linux-gnu/gstreamer1.0/gstreamer-1.0 CC_aarch64_unknown_linux_gnu: aarch64-linux-gnu-gcc CXX_aarch64_unknown_linux_gnu: aarch64-linux-gnu-g++ AR_aarch64_unknown_linux_gnu: aarch64-linux-gnu-ar diff --git a/.github/workflows/pr-build.yml b/.github/workflows/pr-build.yml index 8733b9d1f0..88aaf9bcab 100644 --- a/.github/workflows/pr-build.yml +++ b/.github/workflows/pr-build.yml @@ -70,6 +70,62 @@ jobs: actions_artifacts_name_prefix: pr-${{ github.event.pull_request.number }}-${{ github.event.pull_request.head.sha }}- set_versions: false + performance-guard: + name: Renderer performance guard + needs: authorize + if: ${{ needs.authorize.outputs.allowed == 'true' && !github.event.pull_request.draft }} + runs-on: ubuntu-latest + timeout-minutes: 25 + permissions: + contents: read + steps: + - uses: actions/checkout@v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + - uses: actions/checkout@v7.0.1 + with: + ref: ${{ github.event.pull_request.base.sha }} + path: .perf-base + persist-credentials: false + sparse-checkout: scripts/perf/perf-budgets.json + sparse-checkout-cone-mode: false + - uses: actions/setup-node@v7.1.0 + with: + node-version-file: .node-version + cache: npm + - run: npm ci --ignore-scripts --no-audit --no-fund + - run: node --test scripts/perf/budget-report.test.mjs scripts/perf/seed.test.mjs + - run: npm run build --workspace @neuralnomads/codenomad + - name: Install Chromium and the pinned benchmark tools + run: | + npx --workspace @codenomad/ui playwright install --with-deps chromium + npm install --prefix scripts/perf/tools --ignore-scripts --no-audit --no-fund \ + @lydell/node-pty@1.2.0-beta.18 @xterm/headless@6.0.0 @opencode/cli-linux-x64@2.4.2 + - run: node --test scripts/perf/page-probe.test.mjs + - name: Measure renderer work and latency against the TUI + run: | + node scripts/perf/bench.mjs "$PWD/scripts/perf/tools/node_modules/@opencode/cli-linux-x64/bin/opencode" + - name: Check budgets + run: | + results=(scripts/perf/run/perf-*/results) + test "${#results[@]}" = 1 + node scripts/perf/perf-check.mjs "${results[0]}" --calibrate > "${results[0]}/budget-candidate.json" + base=.perf-base/scripts/perf/perf-budgets.json + args=() + if test -f "$base"; then args=(--base "$base"); fi + node scripts/perf/perf-check.mjs "${results[0]}" --summary "$GITHUB_STEP_SUMMARY" "${args[@]}" + - name: Upload performance evidence + if: always() + uses: actions/upload-artifact@v7.0.2 + with: + name: renderer-performance + path: | + scripts/perf/run/perf-*/results/*.json + scripts/perf/run/perf-*/**/*.log + if-no-files-found: ignore + retention-days: 7 + tests-session-pruning-native: needs: authorize if: ${{ needs.authorize.outputs.allowed == 'true' && !github.event.pull_request.draft }} @@ -218,7 +274,7 @@ jobs: if ($LASTEXITCODE) { exit $LASTEXITCODE } } # Shipped Missions bundle: loading, model-visible tools through the - # ordinary prompt loop, journal RPC and recurrence capability. + # ordinary prompt loop and journal RPC. node scripts/test-missions-native-contract.mjs $cli if ($LASTEXITCODE) { exit $LASTEXITCODE } node scripts/test-missions-native-family-control.mjs $cli @@ -230,14 +286,6 @@ jobs: # Parallel siblings, a recursive grandchild and coordinator readout. node scripts/test-missions-native-trajectory.mjs $cli if ($LASTEXITCODE) { exit $LASTEXITCODE } - # Context IDs must resolve native schedule metadata; the retained product - # bundle must admit cold scheduled passages with the backend closed. - node scripts/test-native-schedule-context.mjs $cli - if ($LASTEXITCODE) { exit $LASTEXITCODE } - $scheduleParent = node -p "require('node:path').join(require('node:os').tmpdir(), 'opencode')" - $scheduleScratch = Join-Path $scheduleParent "schedule-wakes-$([guid]::NewGuid().ToString('N'))" - node --import tsx scripts/test-native-mission-schedule-product.mjs $cli $scheduleScratch --parent-ready --kinds=at,in - if ($LASTEXITCODE) { exit $LASTEXITCODE } if ('${{ matrix.runtime }}' -eq 'latest') { # Missions Preferences' Location subagent-depth editor against the # native config schema and production JSONC document admission. @@ -282,12 +330,6 @@ jobs: if ($LASTEXITCODE) { exit $LASTEXITCODE } node --conditions=browser --import tsx scripts/test-blank-session-cleanup-native.mjs $cli if ($LASTEXITCODE) { exit $LASTEXITCODE } - # Recurring schedule journeys (~6.5 min) qualify the latest stable - # only; the contract fixture qualifies the recurrence graph on both. - if ('${{ matrix.runtime }}' -eq 'latest') { - node scripts/test-recurring-simple-native.mjs $cli ABCD - if ($LASTEXITCODE) { exit $LASTEXITCODE } - } - name: Upload isolated schedule product failure diagnostics if: ${{ failure() && env.NATIVE_SCHEDULE_PRODUCT_FIXTURE != '' }} @@ -300,17 +342,6 @@ jobs: ${{ env.NATIVE_SCHEDULE_PRODUCT_FIXTURE }}/**/failure-sql.json if-no-files-found: ignore retention-days: 7 - - name: Upload isolated schedule foundation failure diagnostics - if: ${{ failure() && env.NATIVE_SCHEDULE_FOUNDATION_FIXTURE != '' }} - uses: actions/upload-artifact@v7.0.2 - with: - name: schedule-foundation-failure-${{ matrix.runtime }} - path: | - ${{ env.NATIVE_SCHEDULE_FOUNDATION_FIXTURE }}/receipt.json - ${{ env.NATIVE_SCHEDULE_FOUNDATION_FIXTURE }}/failure-diagnostic.json - if-no-files-found: ignore - retention-days: 7 - - name: Upload isolated runtime contract failure diagnostics if: ${{ failure() && env.RUNTIME_CONTRACT_FIXTURES != '' }} uses: actions/upload-artifact@v7.0.2 @@ -359,6 +390,7 @@ jobs: libgtk-3-dev \ libglib2.0-dev \ libwebkit2gtk-4.1-dev \ + libgstreamer-plugins-base1.0-dev \ libsoup-3.0-dev \ libayatana-appindicator3-dev \ librsvg2-dev @@ -393,7 +425,7 @@ jobs: run: npm run build:memory --workspace @neuralnomads/codenomad - name: Test desktop packaging invariants - run: node --test scripts/desktop-server-resources.test.cjs scripts/prepare-node-runtime.test.cjs packages/tauri-app/scripts/configure-updater.test.mjs packages/tauri-app/scripts/updater-artifacts.test.mjs packages/tauri-app/scripts/patch-bundle-type.test.mjs packages/tauri-app/scripts/vendored-patches.test.mjs + run: node --test scripts/desktop-server-resources.test.cjs scripts/precompress-ui.test.mjs scripts/prepare-node-runtime.test.cjs packages/tauri-app/scripts/configure-updater.test.mjs packages/tauri-app/scripts/updater-artifacts.test.mjs packages/tauri-app/scripts/patch-bundle-type.test.mjs packages/tauri-app/scripts/vendored-patches.test.mjs - name: Test CI fixture diagnostics and artifact announcements run: node --test scripts/native-fixture-diagnostics.test.mjs scripts/native-pruning-ready.test.mjs .github/scripts/comment-pr-artifacts.test.cjs .github/scripts/runtime-maintenance.test.cjs .github/scripts/dependabot-policy.test.cjs .github/scripts/binary-build-order.test.cjs .github/scripts/windows-signing.test.cjs .github/scripts/zip-entry.test.cjs .github/scripts/release-pr-notes.test.cjs .github/scripts/download-cache.test.cjs @@ -413,6 +445,7 @@ jobs: run: >- node --import tsx --test --test-force-exit packages/ui/src/components/browser-frame-security.test.ts + packages/ui/src/lib/remote-preview-address.test.ts packages/ui/src/components/panel-extensions/work-items-channel.test.ts packages/ui/src/components/message-history-pagination.test.ts packages/ui/src/components/message-timeline-v2.test.ts @@ -445,6 +478,14 @@ jobs: packages/ui/src/lib/height-delta.test.ts packages/ui/src/lib/scroll-gesture-routing.test.ts packages/ui/src/lib/client-identity.test.ts + packages/ui/src/lib/backend-identity.test.ts + packages/ui/src/lib/backend-client.test.ts + packages/ui/src/lib/backend-meta-contract.test.ts + packages/ui/src/lib/passive-image.test.ts + packages/ui/src/lib/backend-usage-routing.test.ts + packages/ui/src/lib/backend-transport.test.ts + packages/ui/src/lib/backend-route-joining.test.ts + packages/ui/src/lib/local-route-joining.test.ts packages/ui/src/lib/filesystem-events.test.ts packages/ui/src/lib/global-cache.test.ts packages/ui/src/lib/monaco/model-cache.test.ts @@ -481,7 +522,9 @@ jobs: packages/ui/src/stores/restore-workspace-commit-gates.test.ts packages/ui/src/stores/client-state-codec.test.ts packages/ui/src/stores/client-state-partitions.test.ts + packages/ui/src/stores/client-state-delta.test.ts packages/ui/src/stores/client-state.test.ts + packages/ui/src/stores/session-catalog-persistence.test.ts packages/ui/src/stores/compaction-notice.test.ts packages/ui/src/stores/form-settlements.test.ts packages/ui/src/stores/instance-invalidation.test.ts @@ -489,10 +532,12 @@ jobs: packages/ui/src/stores/plugin-controls-demand.test.ts packages/ui/src/stores/plugin-controls-events.test.ts packages/ui/src/stores/plugin-sources.test.ts + packages/ui/src/lib/backend-plugin-routing.test.ts packages/ui/src/stores/integrations-store.test.ts packages/ui/src/stores/integration-bindings-store.test.ts packages/ui/src/lib/integration-rows.test.ts packages/ui/src/lib/integrations-api.test.ts + packages/ui/src/lib/backend-integration-routing.test.ts packages/ui/src/stores/message-prompt-display.test.ts packages/ui/src/stores/message-v2/instance-store.test.ts packages/ui/src/stores/message-v2/message-hydration-authority.test.ts @@ -515,6 +560,7 @@ jobs: packages/ui/src/stores/session-deletion-reconciliation.test.ts packages/ui/src/components/instance/shell/right-panel/useGitChanges.test.ts packages/ui/src/stores/tab-view-state.test.ts + packages/ui/src/stores/tab-view-state-local.test.ts packages/ui/src/stores/mission-view-state-migration.test.ts packages/ui/src/lib/browser-history.test.ts packages/ui/src/lib/keyboard-offset.test.ts @@ -525,6 +571,11 @@ jobs: - name: Test Missions UI units run: >- node --conditions=browser --import tsx --test --test-force-exit + packages/ui/src/lib/backend-missions-routing.test.ts + packages/ui/src/lib/mission-coordinator-routing.test.ts + packages/ui/src/components/mission-backend-consumers.test.ts + packages/ui/src/stores/mission-backend-routing.test.ts + packages/ui/src/stores/mission-store-ownership.test.ts packages/ui/src/components/mission-attention.test.ts packages/ui/src/stores/mission-store.test.ts packages/ui/src/stores/mission-task-pages.test.ts @@ -540,6 +591,7 @@ jobs: packages/ui/src/components/mission-native-execution.test.ts packages/ui/src/components/mission-picker-model.test.ts packages/ui/src/components/mission-profile-controls-data.test.ts + packages/ui/src/components/catalog-refresh.test.ts packages/ui/src/components/mission-profile-summary-data.test.ts packages/ui/src/components/mission-progress-model.test.ts packages/ui/src/components/mission-reader-locales.test.ts @@ -550,13 +602,13 @@ jobs: packages/ui/src/lib/mission-cleanup.test.ts packages/ui/src/lib/mission-defaults.test.ts packages/ui/src/lib/mission-display.test.ts + packages/ui/src/lib/mission-held-reread.test.ts packages/ui/src/lib/mission-lifecycle-request.test.ts packages/ui/src/lib/mission-markdown-pages.test.ts packages/ui/src/lib/mission-model-library.test.ts packages/ui/src/lib/mission-mutation-locales.test.ts packages/ui/src/lib/mission-mutation.test.ts packages/ui/src/lib/mission-preferences-document.test.ts - packages/ui/src/lib/mission-recurrence-control.test.ts packages/ui/src/lib/mission-view-fence.test.ts packages/ui/src/lib/native-mission-preferences.test.ts packages/ui/src/lib/storage-owner-read-fence.test.ts @@ -571,6 +623,13 @@ jobs: - name: Test restore ownership integration run: >- node --conditions=browser --import tsx --test --test-force-exit + packages/ui/src/stores/backend-preview-routing.test.ts + packages/ui/src/stores/backend-preferences.test.ts + packages/ui/src/stores/recent-projects.test.ts + packages/ui/src/stores/backend-registry.test.ts + packages/ui/tests/backend-relay-authority.test.ts + packages/ui/src/stores/preferences-multi-backend.test.ts + packages/ui/src/components/panel-extensions/api4-notes-channel.test.ts packages/ui/src/components/form-request-tool-target.test.ts packages/ui/src/components/form-request.test.ts packages/ui/src/components/instance/shell/useSessionCache.test.ts @@ -585,6 +644,7 @@ jobs: packages/ui/src/components/tool-call/renderers/execute-data.test.ts packages/ui/src/components/tool-call/renderers/bash-data.test.ts packages/ui/src/components/prompt-input/usePromptState.test.ts + packages/ui/src/components/prompt-input/backend-history.test.ts packages/ui/src/components/session/provider-usage-panel.test.ts packages/ui/src/lib/hooks/use-active-session-message-load.test.ts packages/ui/src/lib/assistant-meta.test.ts @@ -595,10 +655,35 @@ jobs: packages/ui/src/stores/instance-startup-priority.test.ts packages/ui/src/stores/session-list-startup.test.ts packages/ui/src/stores/app-tabs.test.ts + packages/ui/src/stores/backend-instance-identity.test.ts + packages/ui/src/lib/backend-events.test.ts + packages/ui/src/lib/backend-session-routing.test.ts + packages/ui/src/lib/backend-files-routing.test.ts + packages/ui/src/lib/backend-event-lifecycle.test.ts + packages/ui/src/lib/backend-event-authority.test.ts + packages/ui/src/lib/backend-consumer-lifetime.test.ts + packages/ui/src/lib/backend-async-inventory.test.ts + packages/ui/src/stores/backend-demand-lifetime.test.ts + packages/ui/src/stores/backend-action-lifetime.test.ts + packages/ui/src/stores/backend-runtime-lifetime.test.ts + packages/ui/src/stores/backend-session-flags.test.ts + packages/ui/src/stores/backend-session-read-flags.test.ts + packages/ui/src/stores/backend-store-indicators.test.ts + packages/ui/src/components/backend-view-indicators.test.ts + packages/ui/src/lib/backend-panel-deadline.test.ts + packages/ui/src/lib/backend-panel-extensions-routing.test.ts packages/ui/src/stores/app-session-workspace-hydration.test.ts + packages/ui/src/components/backend-view-lifetime.test.ts + packages/ui/src/lib/backend-view-io.test.ts + packages/ui/src/components/panel-extensions/extension-manager-lifetime.test.ts + packages/ui/src/stores/backend-workspace-list-refresh.test.ts packages/ui/src/stores/forms.test.ts packages/ui/src/stores/preferences-favorites-mode.test.ts packages/ui/src/stores/instances-restore-ownership.test.ts + packages/ui/src/stores/instances-cancellation-flight.test.ts + packages/ui/src/stores/workspace-creation-cancellation-admission.test.ts + packages/ui/src/stores/workspace-creation-cancellation-order.test.ts + packages/ui/src/stores/instances-backend-lifecycle.test.ts packages/ui/src/stores/instances-pending-compaction.test.ts packages/ui/src/stores/instances-pending-requests.test.ts packages/ui/src/stores/pending-recovery-cause.test.ts @@ -618,7 +703,6 @@ jobs: packages/ui/src/stores/session-child-transcript-watch.test.ts packages/ui/src/stores/opencode-inbox-rebinding.test.ts packages/ui/src/stores/opencode-transcript-replay.test.ts - packages/ui/src/stores/opencode-compaction.test.ts packages/ui/src/lib/message-part-grouping.test.ts packages/ui/src/lib/settings/behavior-registry.test.ts packages/ui/src/components/instance/shell/right-panel/core-plugin.test.ts @@ -640,6 +724,10 @@ jobs: packages/ui/src/stores/session-native-events.test.ts packages/ui/src/stores/interruption-scope.test.ts packages/ui/src/stores/session-workspace-scope.test.ts + packages/ui/src/stores/session-projection-cost.test.ts + packages/ui/src/stores/session-projection.test.ts + packages/ui/src/lib/deadline-memo.test.ts + packages/ui/src/lib/server-events-lifecycle.test.ts packages/ui/src/stores/session-outline.test.ts packages/ui/src/stores/runtime-contract.test.ts packages/ui/src/stores/session-lifecycle-signals.test.ts @@ -648,11 +736,11 @@ jobs: packages/ui/src/stores/session-request-authority.test.ts packages/ui/src/stores/session-default-agent.test.ts packages/ui/src/stores/session-default-model.test.ts - packages/ui/src/stores/session-create-pending.test.ts packages/ui/src/stores/history-search-sessions.test.ts packages/ui/src/stores/session-git-degraded.test.ts packages/ui/src/stores/session-send-lifecycle.test.ts packages/ui/src/stores/blank-session-cleanup.test.ts + packages/ui/src/stores/instance-reconnect-reconciliation.test.ts packages/ui/src/stores/session-status.test.ts packages/ui/src/stores/session-subsession-activity.test.ts packages/ui/src/stores/worktree-ready.test.ts @@ -661,6 +749,10 @@ jobs: packages/ui/src/stores/temporary-instances.test.ts packages/ui/src/stores/closed-workspace-drafts.test.ts + - name: Test compaction and verify natural exit + timeout-minutes: 1 + run: node --conditions=browser --import tsx --test packages/ui/src/stores/opencode-compaction.test.ts + - name: Test server run: node --import tsx --test "packages/server/src/**/*.test.ts" @@ -817,6 +909,9 @@ jobs: - name: Install dependencies run: npm ci + - name: Test concurrent server identity and crash recovery + run: node --import tsx --test packages/server/src/settings/server-identity.test.ts + - name: Restore the Electron download if: ${{ hashFiles('.github/actions/download-cache/action.yml') != '' }} uses: ./.github/actions/download-cache @@ -970,7 +1065,8 @@ jobs: run: | sudo apt-get update sudo apt-get install -y build-essential pkg-config zsh libgtk-3-dev \ - libglib2.0-dev libwebkit2gtk-4.1-dev libsoup-3.0-dev \ + libglib2.0-dev libwebkit2gtk-4.1-dev libgstreamer-plugins-base1.0-dev \ + gstreamer1.0-plugins-good libsoup-3.0-dev \ libayatana-appindicator3-dev librsvg2-dev - run: npm ci --workspaces --include=optional - name: Test WebKit qualification workflow contract diff --git a/.npm-version b/.npm-version index 3592725d8b..9446bf2bec 100644 --- a/.npm-version +++ b/.npm-version @@ -1 +1 @@ -12.2.2 +12.2.3 diff --git a/.opencode/skills/codenomad-architecture-guide/SKILL.md b/.opencode/skills/codenomad-architecture-guide/SKILL.md index 407a8e50ba..ebe6adc9c9 100644 --- a/.opencode/skills/codenomad-architecture-guide/SKILL.md +++ b/.opencode/skills/codenomad-architecture-guide/SKILL.md @@ -1,7 +1,7 @@ --- name: codenomad-architecture-guide description: | - Architecture and native OpenCode V2 navigation guide for CodeNomad. Use for cross-package changes, OpenCode client calls, server routes, events, workspaces, Git, Yolo, UI, or desktop integration. + Architecture and native OpenCode V2 navigation guide for CodeNomad. Use for cross-package changes, OpenCode client calls, server routes, events, workspaces, Git, permissions, UI, or desktop integration. --- # CodeNomad Architecture Guide @@ -17,15 +17,15 @@ description: | ## Native OpenCode V2 Baseline -- Runtime requirements live in `opencode/runtime-support.ts`: OpenCode 2.3.0 is the minimum and the recommendation, required by the background subagent report contract (every subagent call returns at once and the child reports through synthetic `` messages) and by the `experimental_image_generate` image tool contract (upstream #60258) that the Images gallery, Design agent and Images settings consume; it also provides Code Mode's JavaScript job ordering (`scripts/test-codemode-jobs-native.mjs`) and the `native`/`metadata.keepID` replay contract consumed by the pinned client reducer. Each blocking requirement needs demonstrated API/behavior evidence; distinguish technically incompatible, recommended/tested and unverified versions. Shared-daemon restart is explicit and uses the native-parent launch bridge. See `dev-docs/OPENCODE_COMPATIBILITY.md` for the version boundaries and `dev-docs/OPENCODE_RUNTIME_SETUP.md` for setup, installation and admission. +- Runtime requirements live in `opencode/runtime-support.ts`; consumed contracts and qualification live in `dev-docs/OPENCODE_COMPATIBILITY.md`. Each blocking requirement needs demonstrated API/behavior evidence. Shared-daemon restart is explicit and uses the native-parent launch bridge; see `dev-docs/OPENCODE_RUNTIME_SETUP.md`. -- Server and UI pin the official `@opencode/client@2.3.0` together; native plugins pin `@opencode/plugin@2.3.0` for authoring and use `packages/server/scripts/native-plugin-build.mjs` to keep Effect/public SDK modules external. The daemon supplies their runtime instances. The canonical server-info client is `server.info()`, adapted to the authenticated discovered route. Review official V2 docs, installed declarations, generated wire paths and native integration tests when upgrading. Never infer a minimum from the latest publication or dependency pin alone. Update `dev-docs/OPENCODE_COMPATIBILITY.md` in place and retain detailed evidence in PR/CI logs. The runtime CLI is managed independently. +- Server and UI pin the official `@opencode/client` together; native plugins pin `@opencode/plugin` for authoring and use `packages/server/scripts/native-plugin-build.mjs` to keep Effect/public SDK modules external. The daemon supplies their runtime instances. The canonical server-info client is `server.info()`, adapted to the authenticated discovered route. Review official V2 docs, installed declarations, generated wire paths and native integration tests when upgrading. Never infer a minimum from a dependency pin. Keep qualification evidence in PR/CI logs. - Do not use `@opencode-ai/sdk`, `@opencode-ai/sdk/v2/client`, or `createOpencodeClient()`; follow installed `@opencode/client` declarations. - Never add general plugin extension points. The narrow native integrations are the bundled `codenomad.automation` plugin, project-local native session coordination (`codenomad.missions`) and the bundled session-pruning RPC; see `dev-docs/BROWSER_AUTOMATION.md`, `dev-docs/MISSIONS.md` and `dev-docs/SESSION_PRUNING_RPC.md`. All automation tools follow backend presence, sharing the authenticated native transport and execution-time session/window fences. - The server uses the selected host or WSL CLI's official `service status`, `service start`, and `service get password` lifecycle to connect to one externally owned global OpenCode daemon. It owns no private port/database/registration/PID and never stops the daemon on backend shutdown. WSL requires Windows localhost forwarding and uses no cross-namespace PID operations. - The UI uses generated Promise clients from `OpenCode.make()` through the CodeNomad proxy. - OpenCode owns session APIs, native Forms, session Shell (`client.session.shell`), session instructions (`client.session.instructions.entry`), location-scoped shells, and interactive PTYs. Forms list through `client.form.list({ location })` and settle through `client.session.form.reply/cancel`; global Forms use the encoded directory header. The Status panel joins native background-job shell IDs to the Location's `client.shell.list` records through the owned background-shells route, refreshing on Shell events, tool completion and reconnect while visible. Output/removal use the ownership-checking Shell proxy; a tool shell is authorized by its originating session. Interactive `client.pty.*` terminals remain separate. -- CodeNomad owns logical project records, directory authorization, Git status/diff/stage/unstage/commit, Yolo persistence/auto-replies, and `/api/events`. Closing a project tab deletes that occurrence's backend record; native sessions continue. CodeNomad never evicts native Locations. Whole-window close, quit and reload preserve restoration behavior. +- CodeNomad owns logical project records, directory authorization, Git status/diff/stage/unstage/commit, session permission block ownership, and `/api/events`. Closing a project tab deletes that occurrence's backend record; native sessions continue. CodeNomad never evicts native Locations. Whole-window close, quit and reload preserve restoration behavior. - OpenCode owns the global daemon's standard state and database. Configured environment variables are passed to `service start` for a missing daemon; an existing daemon is unchanged. Before each session prompt/command/shell send, the authorized proxy also applies the profile's complete execution-host environment via `session.environment`. `OPENCODE_DB`/`XDG_STATE_HOME` ownership settings are ignored. See `dev-docs/SESSION_ENVIRONMENT.md` for scope and limitations. - Native desktop identity is data profile plus config identity (`dev-docs/DESKTOP_DATA_PROFILES.md`): one singleton process/backend per scope and multiple UUID windows. A second launch opens another window by default; Advanced settings can restore MRU focus, while `--new-window` always requests another window. Each scope isolates native state; OpenCode sessions/messages are shared while tabs/drafts/views are per-window. - Client-state V3 is a per-window envelope over the V2 content-addressed partition graph with atomic publication/migration, ownership-fenced writes, and conservative post-commit GC. Iframe preview fallbacks are sandboxed without same-origin access; native browser guests share one preview profile kept separate from the application renderer and get no application capabilities (frame policy in `dev-docs/architecture.md`). @@ -37,7 +37,7 @@ External right-panel UI addons use `packages/server/src/panel-extensions/` and They are sandboxed UI packages with their own consent and loading path. Never import author code into the primary renderer, expose generic RPC or grant native commands. -- `packages/server/`: Fastify control API, shared OpenCode service, locations, auth, filesystem, Git, Yolo, speech. +- `packages/server/`: Fastify control API, shared OpenCode service, locations, auth, filesystem, Git, permissions, speech. - `packages/ui/`: SolidJS application, generated client adapters, stores, components, i18n. - `packages/electron-app/`: Electron host. - `packages/tauri-app/`: Tauri host. @@ -53,7 +53,7 @@ author code into the primary renderer, expose generic RPC or grant native comman - Root client authority: `packages/ui/src/stores/opencode-client.ts` - Native session calls: `packages/ui/src/stores/session-api.ts`, `session-actions.ts` - Git mutations: `packages/server/src/workspaces/git-mutations.ts` -- Yolo: `packages/server/src/permissions/`, `packages/server/src/server/routes/yolo.ts` +- Conversation permissions: `packages/server/src/permissions/`, `packages/server/src/server/routes/session-permission-mode.ts` - Desktop hosts: `packages/electron-app/electron/main/`, `packages/electron-app/electron/preload/index.cjs`, `packages/tauri-app/src-tauri/src/` - Desktop automation: `packages/server/src/opencode/automation-plugin.ts`, `packages/server/src/opencode/automation/desktop-plugin.ts`, `packages/server/src/server/routes/automation-plugin.ts`, `packages/server/src/developer-cdp.ts`, `packages/server/src/automation/page/` @@ -64,7 +64,7 @@ author code into the primary renderer, expose generic RPC or grant native comman - Send CodeNomad operations through `/api/*`; send OpenCode operations through `/workspaces/:id/instance/api/*`. - Consume the multiplexed CodeNomad SSE stream at `/api/events`; do not create one OpenCode process or event stream per workspace. Native events are volatile, so reconnect must reconcile authoritative state. - Treat the instance proxy allowlist as an integration boundary. Upstream routes are exposed only after review. -- Keep Git mutations and Yolo in CodeNomad: they are its policy/security boundaries. +- Keep Git mutations and permission mode ownership in CodeNomad; OpenCode owns permission evaluation and settlement. - Check `packages/server/src/api-types.ts` and UI consumers together when changing CodeNomad events or responses. - Desktop behavior must remain at strict Electron/Tauri parity in the same change; use the shared native abstraction and test both hosts. diff --git a/.opencode/skills/codenomad-architecture-guide/references/architecture-overview.md b/.opencode/skills/codenomad-architecture-guide/references/architecture-overview.md index 1a39fefc3e..96deb7ec13 100644 --- a/.opencode/skills/codenomad-architecture-guide/references/architecture-overview.md +++ b/.opencode/skills/codenomad-architecture-guide/references/architecture-overview.md @@ -20,8 +20,8 @@ Client-state V3 is a per-window envelope over the V2 content-addressed partition | Owner | Responsibilities | Main paths | |---|---|---| -| OpenCode V2 | Sessions, messages, permissions, Forms, files, session Shell/instructions, background Shells, interactive PTYs | pinned `@opencode/client@2.3.0` contract across server and UI; host-owned native plugin runtime | -| CodeNomad server | Shared service lifecycle, locations, proxy authorization, Git mutations, Yolo, auth, storage, speech, SSE multiplexing, desktop automation bridge | `packages/server/src/` | +| OpenCode V2 | Sessions, messages, permissions, Forms, files, session Shell/instructions, background Shells, interactive PTYs | pinned `@opencode/client` contract across server and UI; host-owned native plugin runtime | +| CodeNomad server | Shared service lifecycle, locations, proxy authorization, Git mutations, permission mode ownership, auth, storage, speech, SSE multiplexing, desktop automation bridge | `packages/server/src/` | | CodeNomad UI | Generated Promise clients, state reconciliation, interaction and rendering | `packages/ui/src/` | | Desktop hosts | Start CodeNomad and provide native OS integration | `packages/electron-app/`, `packages/tauri-app/` | @@ -33,14 +33,14 @@ Native Forms are the interruption API; never add a separate Question queue. - CodeNomad control endpoints live under `/api/*`, including `/api/workspaces`, Git routes and `/api/events`. - OpenCode requests use `/workspaces/:id/instance/api/*`. The explicit method/path allowlist injects service auth, validates supplied paths and `location`/`directory` values, checks session ownership, and defaults safe requests to the workspace directory. New upstream routes are exposed only after review. -- Yolo state endpoints use `/workspaces/:id/yolo/sessions/:sessionId`; state changes and auto-accept confirmations travel over `/api/events`. +- Conversation permission mode uses `/api/workspaces/:id/sessions/:sessionId/permission-mode`; native `session.permissions` invalidates display state. - `InstanceEventBridge` subscribes once to the volatile shared OpenCode event stream and publishes typed `instance.event` records on CodeNomad's event bus. Reconnect must refetch authoritative state because missed events are lost. ## Persistence `packages/server/src/config/location.ts` resolves CodeNomad data under `~/.config/codenomad/`: canonical `config.yaml`, `state.yaml`, and `instances/`, with `config.json` retained only as migration input. -OpenCode location/workspace identity is upstream state. CodeNomad persists only its own preferences and policy metadata, including Yolo state. +OpenCode location/workspace identity is upstream state. CodeNomad persists its own preferences and the exact permission blocks it owns. OpenCode owns the global daemon's standard state and database. Allowed configured environment variables apply only when CodeNomad starts a missing daemon; an existing daemon is unchanged, and `OPENCODE_DB`/`XDG_STATE_HOME` ownership variables are ignored. diff --git a/.opencode/skills/codenomad-architecture-guide/references/feature-traces.md b/.opencode/skills/codenomad-architecture-guide/references/feature-traces.md index 288cb4dca9..d6cccbdf1d 100644 --- a/.opencode/skills/codenomad-architecture-guide/references/feature-traces.md +++ b/.opencode/skills/codenomad-architecture-guide/references/feature-traces.md @@ -20,14 +20,12 @@ 7. The proxy checks directory/session ownership, applies the profile's session environment before prompt/command/shell sends (`workspaces/session-environment.ts`) and forwards to the shared service's `/api/*` route. 8. One upstream event subscription feeds `InstanceEventBridge`, then CodeNomad `/api/events`, then UI stores. -## Permission And Yolo +## Conversation Permissions 1. OpenCode emits a location-scoped permission event. 2. `InstanceEventBridge` publishes it as `instance.event`. -3. `AutoAcceptManager` checks CodeNomad-owned Yolo state. -4. If enabled, `createOpencodePermissionReplier` calls native `client.permission.reply` and emits `yolo.autoAccepted`. -5. Otherwise the UI queues the permission and replies with the native client. -6. Yolo toggle/persistence remains in CodeNomad; `/api/events` distributes `yolo.stateChanged`. +3. The UI queues permission questions and sends the explicit decision through the native client. +4. `session.permissions` triggers a mode read; the backend checks the current rules against its private ownership record. ## Git Changes @@ -40,7 +38,7 @@ Never replace mutation routes with OpenCode file/status calls; CodeNomad owns th ## Events - OpenCode events: shared `client.event.subscribe()` -> `InstanceEventBridge` -> `EventBus`. -- CodeNomad events: workspace/Git-adjacent policy/Yolo producers -> `EventBus`. +- CodeNomad events: workspace, filesystem and storage producers -> `EventBus`. - Browser transport: `GET /api/events` with heartbeat/pong via `/api/client-connections/pong`. - The native stream is volatile. On reconnect, refetch authoritative session/pending-request/file/config state. - Invalidations use `filesystem.changed` and `config.updated`; session lifecycle/output uses `session.created`, `session.renamed`, `session.moved`, `session.execution.*` (OpenCode never publishes the declared `session.status`/`session.idle`), `session.compaction.*`, `session.text.*`, `session.reasoning.*`, and `session.tool.*`. diff --git a/.opencode/skills/codenomad-architecture-guide/references/sdk-api-reference.md b/.opencode/skills/codenomad-architecture-guide/references/sdk-api-reference.md index 47f55c8e3a..7d52aab9eb 100644 --- a/.opencode/skills/codenomad-architecture-guide/references/sdk-api-reference.md +++ b/.opencode/skills/codenomad-architecture-guide/references/sdk-api-reference.md @@ -2,9 +2,9 @@ ## Package -CodeNomad server and UI pin `@opencode/client@2.3.0`. The runtime CLI is managed independently; startup validates authenticated loopback `/api/info`, then (only to identify an outdated daemon) `/api/status`, then `/api/health`, advancing only on HTTP 404 with the same endpoint, credentials and deadline. Each response has its own validated schema and a 64 KiB bound. The shared transport forwards canonical `server.info()` unchanged. Review official V2 docs, installed declarations, generated routes and native regression tests together when upgrading. +CodeNomad server and UI pin the same `@opencode/client`. The runtime CLI is managed independently; startup validates authenticated loopback `/api/info`, then (only to identify an outdated daemon) `/api/status`, then `/api/health`, advancing only on HTTP 404 with the same endpoint, credentials and deadline. Each response has its own validated schema and a 64 KiB bound. The shared transport forwards canonical `server.info()` unchanged. Review official V2 docs, installed declarations, generated routes and native regression tests together when upgrading. -Runtime requirements live in `packages/server/src/opencode/runtime-support.ts`: minimum 2.3.0 (the background subagent report contract, the `experimental_image_generate` image tool contract, Code Mode JavaScript job ordering and the `native`/`metadata.keepID` replay contract), with the recommendation (also 2.3.0) tracked separately. Native builds share the daemon's Effect/public SDK instead of bundling a second runtime. The shared connection binds authenticated runtime identity, the canonical client and forwarding transport. Admission precedes functional requests/plugin provisioning; unlisted custom/prerelease/future labels require authenticated bounded API recognition. Never add operation-specific retry fallbacks. See `dev-docs/OPENCODE_COMPATIBILITY.md` for the version boundaries and `dev-docs/OPENCODE_RUNTIME_SETUP.md` for admission. +The minimum and recommendation live in `packages/server/src/opencode/runtime-support.ts`. Native builds share the daemon's Effect/public SDK. The shared connection binds authenticated runtime identity, the canonical client and forwarding transport. Admission precedes functional requests/plugin provisioning; unlisted custom/prerelease/future labels require authenticated bounded API recognition. Never add operation-specific retry fallbacks. See `dev-docs/OPENCODE_COMPATIBILITY.md` for the consumed contracts and `dev-docs/OPENCODE_RUNTIME_SETUP.md` for admission. The Promise client preserves the full `baseUrl` path prefix. Forward its generated URL unchanged through `createInstanceFetch`; remove the proxy prefix only when classifying reads for scheduling. Declared API errors are `Error` instances retaining their native `_tag`/data fields. Client errors retain structured `reason`/`cause`, and their `message` may add status, content type or cause detail: classify by structured fields, never exact message text. @@ -25,7 +25,7 @@ Do not replace the shared network service with `@opencode-ai/sdk` unless CodeNom | Sessions | `list/get/create/fork/remove/update/prompt/command/shell/interrupt` | UI session stores | | Session environment | `client.session.environment({ sessionID, variables })` replaces a complete snapshot before prompt/command/shell admission | guarded server proxy; `workspaces/session-environment.ts` builds host/WSL values | | Instructions | `client.session.instructions.entry.put/remove` | conversation-mode prompt setup | -| Permissions | `permission.request.list`, `permission.reply` | UI and server Yolo replier | +| Permissions | `permission.request.list`, `permission.reply`, session `permissions` on create/get/update | UI, guarded permission mode and receipts routes | | Forms | `client.form.list`, `client.session.form.reply`, `client.session.form.cancel` | `packages/ui/src/stores/instances.ts`, `forms.ts` | Native methods return decoded Promise values. Follow the installed declarations and existing callers; never wrap calls in response-unwrapping helpers. @@ -50,7 +50,7 @@ Do not look for these in the OpenCode client: - Workspace create/delete and worktree workflow routes (native OpenCode owns worktree discovery/create/remove; CodeNomad supplies directory/branch policy and verified session-family moves) - Git status/diff/stage/unstage/commit -- Yolo toggle, persistence and auto-accept policy +- Conversation permission mode and ownership of appended session rules - Authentication, storage, speech, sidecars and previews - Multiplexed browser SSE at `/api/events` diff --git a/.opencode/skills/codenomad-architecture-guide/references/sdk-critical-behaviors.md b/.opencode/skills/codenomad-architecture-guide/references/sdk-critical-behaviors.md index 24fee3cdd2..5143a416e3 100644 --- a/.opencode/skills/codenomad-architecture-guide/references/sdk-critical-behaviors.md +++ b/.opencode/skills/codenomad-architecture-guide/references/sdk-critical-behaviors.md @@ -2,12 +2,12 @@ ## Contract -- Server and UI pin `@opencode/client@2.3.0`. Manage the runtime CLI independently: startup checks authenticated loopback `/api/info`, then (only to identify an outdated daemon) `/api/status`, then `/api/health`, advancing only on HTTP 404. All probes share the endpoint, credentials, 64 KiB response bound and absolute deadline; authentication, transport and malformed response failures end discovery without fallback. The shared transport forwards canonical `server.info()` unchanged. Review documentation, installed declarations and proxy/API parity whenever the client contract changes. +- Server and UI pin the same `@opencode/client`. Manage the runtime CLI independently: startup checks authenticated loopback `/api/info`, then (only to identify an outdated daemon) `/api/status`, then `/api/health`, advancing only on HTTP 404. All probes share the endpoint, credentials, 64 KiB response bound and absolute deadline; authentication, transport and malformed response failures end discovery without fallback. The shared transport forwards canonical `server.info()` unchanged. Review documentation, installed declarations and proxy/API parity whenever the client contract changes. - The package root is the generated zero-Effect Promise client. Use installed declarations; never follow `@opencode-ai/sdk` examples. - Native routes are `/api/*`; CodeNomad exposes them only through the authorized `/workspaces/:id/instance` proxy. - That proxy is an explicit method/path allowlist: expose each new upstream API only after review. - Proxy authorization and forwarding share one acquired connection. A stale generation must be rejected at actual HTTP dispatch, including after asynchronous body preparation; late streams cannot invalidate a replacement connection. -- The technical minimum is 2.3.0 for the background subagent report contract (calls return at once; children report through synthetic `` messages) and the `experimental_image_generate` image tool contract (upstream #60258: tool, permission action, job type and notice `metadata.source` share that name; on unless `experimental.image_generate` is `false`), alongside Code Mode's JavaScript job ordering and the `native` replay and `metadata.keepID` compaction shapes consumed by the pinned client reducer; the recommendation, also 2.3.0, is a separate constant. Plugins use host-owned Effect/public SDK modules through the shared native build settings. Unknown version labels, prereleases and future majors undergo bounded authenticated API recognition, including session environment support. Native `session.inbox.enqueued` has its own shape: its timestamp lives in event metadata, unlike an HTTP inbox record. +- See `dev-docs/OPENCODE_COMPATIBILITY.md` for the runtime requirements. Plugins use host-owned Effect/public SDK modules. Unknown version labels, prereleases and future majors undergo bounded authenticated API recognition, including session environment support. Native `session.inbox.enqueued` has its own shape: its timestamp lives in event metadata, unlike an HTTP inbox record. - Never retry a write using another contract after a 400/404/transport failure. Keep the setup/recovery path distinct from functional transport and never replay prompts. ## Location Is Authority @@ -36,7 +36,7 @@ | Service status/start/password | CodeNomad adapter using the selected host or WSL CLI; only the explicit setup restart may stop/start the shared daemon | | Workspace and directory authorization | CodeNomad | | Git status/diff and mutations | CodeNomad | -| Yolo policy/persistence/auto-reply | CodeNomad | +| Conversation permission block ownership | CodeNomad | | Browser event multiplexing | CodeNomad `/api/events` | Background Shell output uses native cursor pagination; interactive PTYs remain separate. Never use `@opencode-ai/sdk`, per-workspace processes or server plugin/background-process tools. diff --git a/.opencode/skills/codenomad-architecture-guide/references/sdk-integration-patterns.md b/.opencode/skills/codenomad-architecture-guide/references/sdk-integration-patterns.md index 61bf29c105..1e8a83f93d 100644 --- a/.opencode/skills/codenomad-architecture-guide/references/sdk-integration-patterns.md +++ b/.opencode/skills/codenomad-architecture-guide/references/sdk-integration-patterns.md @@ -35,7 +35,7 @@ Use `getRootClient(instanceId)` from `packages/ui/src/stores/opencode-client.ts` 1. The server subscribes once with `client.event.subscribe()`. 2. `InstanceEventBridge` maps location-scoped OpenCode events to CodeNomad `instance.event` records. -3. `EventBus` also carries CodeNomad events such as workspace and Yolo changes. +3. `EventBus` also carries CodeNomad events such as workspace and storage changes. 4. `/api/events` multiplexes those records to the UI; `packages/ui/src/lib/sse-manager.ts` reconnects and dispatches them. The native stream is volatile. Reconnect must refetch authoritative sessions and pending requests; file/config consumers must also refresh after gaps. Invalidations are `filesystem.changed` and `config.updated`, alongside native `session.*` lifecycle/output events. @@ -43,5 +43,5 @@ The native stream is volatile. Reconnect must refetch authoritative sessions and ## CodeNomad Policy Boundaries - Git mutations run validated `git` commands in `packages/server/src/workspaces/git-mutations.ts` through `/api/workspaces/:id/worktrees/:slug/git-*`. -- Yolo is server-owned. `AutoAcceptManager` persists CodeNomad metadata and replies through the shared native client, then emits `yolo.stateChanged`/`yolo.autoAccepted`. +- `SessionPermissionModes` owns its exact native rule block and confirms changes by a fresh read. Native `session.permissions` invalidates displayed mode. - Never move these operations into a browser-only client or an OpenCode plugin. diff --git a/.opencode/skills/codenomad-architecture-guide/references/server-conventions.md b/.opencode/skills/codenomad-architecture-guide/references/server-conventions.md index 6a5cce263e..53cbf2b750 100644 --- a/.opencode/skills/codenomad-architecture-guide/references/server-conventions.md +++ b/.opencode/skills/codenomad-architecture-guide/references/server-conventions.md @@ -23,7 +23,7 @@ - Keep the OpenCode proxy method/path allowlist explicit; add upstream routes only after review. - Resolve worktree slugs server-side before filesystem or Git operations. - Keep Git path traversal checks and commit validation in CodeNomad. -- Keep Yolo persistence and automatic permission replies server-side. +- Keep ownership of CodeNomad's appended permission block in private backend state. ## Configuration @@ -44,5 +44,5 @@ - Instance proxy: `packages/server/src/server/http-server.ts` - CodeNomad SSE: `packages/server/src/server/routes/events.ts` - Git reads/mutations: `packages/server/src/workspaces/git-status.ts`, `git-mutations.ts` -- Yolo: `packages/server/src/permissions/`, `packages/server/src/server/routes/yolo.ts` +- Conversation permissions: `packages/server/src/permissions/`, `packages/server/src/server/routes/session-permission-mode.ts` - Desktop automation: `packages/server/src/opencode/automation-plugin.ts`, `packages/server/src/opencode/automation/desktop-plugin.ts`, `packages/server/src/server/routes/automation-plugin.ts`, `packages/server/src/developer-cdp.ts`, `packages/server/src/automation/page/` diff --git a/.opencode/skills/codenomad-automation/SKILL.md b/.opencode/skills/codenomad-automation/SKILL.md index dd76239350..a68e839f3f 100644 --- a/.opencode/skills/codenomad-automation/SKILL.md +++ b/.opencode/skills/codenomad-automation/SKILL.md @@ -8,9 +8,9 @@ description: Inspect, modify, rebuild, relaunch, and verify CodeNomad desktop bu 1. Call `codenomad.inspect` before editing. It identifies the local CodeNomad window and returns an indented accessibility outline with refs, plus runtime diagnostics. Large parts collapse with `(+N hidden)`/`(+N more)`: pass `ref` to expand one, or `query` to find elements by text or role. 2. Use refs from the latest inspections with `codenomad.act`: `click` (a real pointer click, refused when the element is covered), `type` (replaces the field's text; `clear: false` appends), `select` (native ``. `styles/components/native-select.css` styles every native select globally: the closed control matches selector triggers (control surface, chevron) and, where `appearance: base-select` and content-box clipping are supported (Electron, WebView2), the open list matches the shared menus and long values stay on one line, clipped before a background-drawn chevron; elsewhere the native select remains. Customizable selects size to the shown value, so auto-width selects need a stable feature width (container units, not percentages of shrink-to-fit parents). Do not style individual selects as fields. - The `.icon-toggle` active state (`aria-pressed`/`aria-expanded`/`data-active`) is one shared rule in `styles/utilities.css` for every palette; never add per-button or per-palette active overrides (exact tint, exception and contrast test in `dev-docs/UI_CONVENTIONS.md`). @@ -27,8 +27,8 @@ Before changing code in an area listed under [Area conventions](#area-convention ## Area conventions Paths are under `packages/ui/src/` or `packages/server/src/` unless stated. -- **Missions** (`missions/`, `opencode/missions-plugin.ts`, `server/routes/mission-*`, `host-lifetime/`; UI `components/mission-*`, `components/settings/missions-settings-section.tsx`, `stores/mission-*`, `styles/panels/mission-*`): `dev-docs/MISSIONS.md`; recurring schedules and Wayfinder human gates (its "Wayfinder human decision mark" section) `dev-docs/MISSIONS_RECURRING.md`. -- **Questions, permissions and pending-request recovery** (interruption dock, permission receipts, `question-data.ts`, `server/routes/pending-requests.ts`, `workspaces/pending-discovery.ts`, `stores/pending-recovery-*`): `dev-docs/NATIVE_INTERRUPTION_UX.md`. +- **Missions** (`missions/`, `opencode/missions-plugin.ts`, `server/routes/mission-*`, `host-lifetime/`; UI `components/mission-*`, `components/settings/missions-settings-section.tsx`, `stores/mission-*`, `styles/panels/mission-*`): `dev-docs/MISSIONS.md`; launch criteria, documents and Wayfinder human gates (its "Wayfinder human decision mark" section) `dev-docs/MISSIONS_RECURRING.md`. +- **Questions, permissions and pending-request recovery** (interruption dock, conversation permission modes and receipts, `question-data.ts`, `permissions/`, `server/routes/session-permission-mode.ts`, `server/routes/pending-requests.ts`, `workspaces/pending-discovery.ts`, `stores/pending-recovery-*`): `dev-docs/NATIVE_INTERRUPTION_UX.md`. - **Composer** (`components/prompt-input*`, `prompt-input/`, `PromptContextControls`, `/btw`): `dev-docs/COMPOSER.md`. - **Transcript** (message rendering, Message content and presets, token lines, tool renderers, `stores/message-v2/`, `stores/opencode-data.ts`, `lib/native-execution-events.ts`): `dev-docs/TRANSCRIPT.md`; long-text bounds `dev-docs/TEXT_DISPLAY_BOUNDS.md`. - **Timeline, transcript scrolling and history search** (`virtual-follow-list.tsx`, `timeline-*`, `stores/timeline-previews.ts`, history search): `dev-docs/SESSION_HISTORY_NAVIGATION.md`, `dev-docs/SESSION_HISTORY_QUERIES.md`. diff --git a/BUILD.md b/BUILD.md index 42979a0240..931b575a2e 100644 --- a/BUILD.md +++ b/BUILD.md @@ -86,6 +86,9 @@ bun run build:win-arm64 ### Linux +Tauri source builds require `libgstreamer-plugins-base1.0-dev` on Debian/Ubuntu. +Linux remote dictation uses the GStreamer Good plugins and PulseAudio (or PipeWire's PulseAudio service). + ```bash # Electron Debian package (x64) npm run build:linux --workspace @neuralnomads/codenomad-electron-app diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 267eaf43cc..a3a3939629 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -114,7 +114,7 @@ Then open a pull request on GitHub targeting the `dev` branch. ### OpenCode V2 Boundaries -- Server and UI pin `@opencode/client@2.3.0`; native plugins pin `@opencode/plugin@2.3.0` for authoring but resolve Effect and the public SDK from the daemon at runtime. Upgrade pins together with the lockfile and isolated native validation. The runtime CLI is managed independently; its demonstrated minimum and recommended/tested versions remain separate constants in `packages/server/src/opencode/runtime-support.ts` (minimum 2.3.0 for the background subagent report contract and the `experimental_image_generate` image tool contract of upstream #60258, consumed by the subagent cards, Missions, the Images gallery, Design agent and Images settings; recommended 2.3.0). A build pin alone is never a runtime requirement, and unfamiliar newer/custom labels retain authenticated contract recognition. Review current OpenCode documentation, installed declarations, and proxy/API parity whenever the client contract changes. +- Server and UI pin `@opencode/client@2.4.2`; native plugins pin `@opencode/plugin@2.4.2` for authoring but resolve Effect and the public SDK from the daemon at runtime. Upgrade pins together with the lockfile and isolated native validation. The independently managed runtime CLI's minimum and recommendation live in `packages/server/src/opencode/runtime-support.ts`. Unfamiliar newer/custom labels retain authenticated contract recognition. Review current OpenCode documentation, installed declarations, and proxy/API parity whenever the client contract changes. - Upgrade references: [OpenCode V2 changelog](https://opencode.ai/changelog) (GitHub Releases list V1), the exact release tags (`vX.Y.Z`) or published npm packages for source/declaration deltas, [OpenCode V2 documentation](https://opencode.ai/v2/docs/), and `node_modules/@opencode/client/dist/promise/`. - `packages/server/src/workspaces/opencode-service.ts` uses the selected host or WSL CLI's official `service status`, `service start`, and `service get password` lifecycle to connect to one externally owned global daemon. CodeNomad owns no private port, database, registration, or daemon PID and never stops the daemon on backend shutdown. - WSL requires Windows localhost forwarding and runs the Linux CLI lifecycle inside the distribution; never inspect or signal Linux PIDs from Windows. @@ -125,7 +125,7 @@ Then open a pull request on GitHub targeting the `dev` branch. - Shell mode (`client.session.shell`) and prompt instructions (`client.session.instructions.entry`) remain separate from background shells and interactive PTYs. - Location-scoped background shells use `client.shell.*` and are listed in the Status panel. The UI refreshes them on Shell events and reconnect, displays native metadata, and supports ownership-checked removal. `client.pty.*` remains reserved for interactive terminals. `packages/opencode-plugin` and the server plugin/background-process paths remain deleted and must not be restored. - Native events are volatile. Reconnect handlers must refetch authoritative state instead of assuming missed events will replay. -- Git mutations and Yolo policy remain CodeNomad-owned server boundaries. +- Git mutations and ownership records for conversation permission modes remain CodeNomad server responsibilities. - Native desktop identity is channel plus config profile: one singleton process/backend per profile and multiple UUID windows. A second launch opens another window by default; Advanced settings can restore MRU focus, while `--new-window` always requests another window. Stable, dev, and non-default profiles isolate native/browser/client state; OpenCode sessions/messages stay shared while tabs, drafts, and views are per-window. - Desktop restore uses a V3 per-window envelope over the V2 content-addressed partition graph. Preserve atomic publication/migration, ownership write fencing, and post-commit conservative garbage collection in both Electron and Tauri. - Browser preview iframes are sandboxed without same-origin access, so DOM comment inspection is web-only. SideCar iframes are same-origin by design: SideCars are trusted extensions of the application (see `dev-docs/architecture.md`). diff --git a/README.md b/README.md index 6b9cf7d23d..0998e4faab 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ npx @neuralnomads/codenomad-dev --password "your-password" --launch ## OpenCode V2 and upgrading from 0.19.x -CodeNomad **requires OpenCode V2 2.3.0 or later** (also the recommended version); it provides the background subagent reports shown in subagent cards and used by Missions, and the image generation tool used by the Images settings and the Design extension. OpenCode V1 and the former V2 beta protocol are not supported. The current requirements are maintained in [`runtime-support.ts`](packages/server/src/opencode/runtime-support.ts). +This branch **requires OpenCode V2 2.4.2 or later** for Mission Automations, the browser tools, Code Mode image generation and family session moves. See [`runtime-support.ts`](packages/server/src/opencode/runtime-support.ts) and the [OpenCode setup guide](https://neuralnomadsai.github.io/CodeNomad/en/opencode.html) for release requirements. - **One shared OpenCode service** owns sessions and messages. Closing a CodeNomad tab, window, or backend leaves that service running. Desktop tabs, drafts, and layout are restored separately for each window. - **Use an existing CLI or install from CodeNomad.** Executables on `PATH` are preferred; the setup screen also supports a selected executable and a shared user npm installation. The former private CodeNomad OpenCode installation is no longer used. @@ -166,7 +166,7 @@ Add SideCar as: ## Requirements -- **[OpenCode V2](https://opencode.ai/v2/docs/)** — 2.3.0 minimum and recommended. Install/select it through desktop setup or provide a compatible CLI on the server host. +- **[OpenCode V2](https://opencode.ai/v2/docs/)** — 2.4.2 minimum and recommended. Install/select it through desktop setup or provide a compatible CLI on the server host. - **[Git](https://git-scm.com/downloads)** — a prerequisite for full functionality (repository identity, Git operations and worktrees). Git must be executable in the CodeNomad backend's `PATH`; it is not bundled with the desktop installers. - **Node.js and npm** — required for the standalone npm server and source builds; desktop releases include their own (Electron's integrated Node or Tauri's bundled Node, with npm). Use **Node.js 24 LTS**; development and release builds use the version in [`.node-version`](.node-version). diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 21f48bb7f0..f85b59e3df 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -56,3 +56,31 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +## OpenCode + +The browser console and network diagnostics (`packages/server/src/opencode/native-browser/diagnostics.ts`, +`diagnostics-machine.ts`) are ported from OpenCode's desktop browser, v2.4.1: +https://github.com/anomalyco/opencode + +MIT License + +Copyright (c) 2025 opencode + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dev-docs/AGENT_MEMORY.md b/dev-docs/AGENT_MEMORY.md index 62fa960230..9192de57b2 100644 --- a/dev-docs/AGENT_MEMORY.md +++ b/dev-docs/AGENT_MEMORY.md @@ -195,6 +195,24 @@ filesystem targets. ## Authorized HTTP operations +Remote browsers use the authenticated UI admission matrix in +[Remote Control](REMOTE_CONTROL.md#saved-profile-relay). With the strict host-owned +`multiBackend` flag enabled (the default), paired Remote Control devices, verified HTTPS clients +and declared LAN HTTP sessions can use the exact memory routes on the host and +through saved-profile relays. PWA requests follow their current URL's channel. +Relayed memory retains the current backend proof, destination schemas and +project-directory ownership. The selected Preferences project owns review, +editing and Tidy up on that backend. + +The common pre-body hook captures the request principal. Its signal fences +project-identity follow-ups, repository-lock waits, read/writability checks, +locked mutation decisions and response publication. Each lock waiter owns its +cancellation. After writing, syncing and closing the temporary journal, the +original signal is checked immediately before its atomic rename. That publication +admits a durable transaction; accepted transactions and their Git recovery finish +while revoked callers lose their acknowledgements. Individual host filesystem/Git reads retain their bounded +native lifetime, with the original signal checked before subsequent work. + `memory/api.ts` validates the shared UI/tool operation contract from `memory/contract.ts`. `POST /api/memory` takes `{ operation, context? }`; operations are `list`, `read` with `query` (exact ID first, then title), `save` with `content`, @@ -323,6 +341,15 @@ the main window's active project and selected session Location on General demand native Preferences keeps its explicit resolved context. Without an authorized project only About you can be selected. Titles/types/text have localized labels in all ten UI languages, and supplementary copy uses `SettingsInfoTip`. +Qualified remote projects select `agentMemoryFor(instanceId)`: scopes, enablement, +reads, edits and cleanup checks retain that backend's attachment and relay transport. +HTTP context carries its raw workspace ID. Draft and badge frontiers include the +backend identity; unavailable Preferences projects keep the card inactive and +retain unsent drafts for the same project owner. +Local calls retain `localHttp`. The UI relay requires a current relay proof +for exact POST `/api/memory` and GET/PUT `/api/memory/settings`. The destination +admits these methods over its authenticated direct server-device transport; +Remote Control browser admission follows the host flag and principal contract above. The cleanup action and its info tip wrap as one group. Editable title/text fields derive direction from their contents, and list titles use bidirectional isolation. @@ -378,6 +405,9 @@ in the project's session inventory and shows the localized cleanup failure. intent. Electron and Tauri accept it only from the trusted Preferences main frame, compare it to the host's current Preferences project, and forward to that window's exact local opener. Missing openers fail explicitly. The main renderer +also checks the remote intent's `serverId` against its admitted backend before +any preflight or session creation; both native hosts compare it to their current request. +The main renderer claims each Tauri event hint through the native host, which returns the pending intent only to its targeted local window and only once. The main renderer alone owns session creation, tab/session activation and the initial send through @@ -447,6 +477,9 @@ for cross-process contention. The five committed entries, fresh locked decisions Windows sharing failures and crash-recovery history remain asserted. Readiness and lock-candidate publication coordinate handoffs; test polling deadlines bound missing signals independently of the unchanged product lock deadline. +`memory/cancellation.integration.ts` checks independently cancelled lock/read/write +waiters, revocation during temporary-journal fsync, pre-rename refusal and +post-journal durability with real Git/filesystem IO. ```text node --import tsx --test packages/ui/tests/contracts/agent-memory-types.test.ts diff --git a/dev-docs/BROWSER_AUTOMATION.md b/dev-docs/BROWSER_AUTOMATION.md index c209b01e8b..cda72b0687 100644 --- a/dev-docs/BROWSER_AUTOMATION.md +++ b/dev-docs/BROWSER_AUTOMATION.md @@ -1,20 +1,19 @@ # Browser Automation -CodeNomad exposes `codenomad.browser` for controlling the visible web preview attached to the current OpenCode session. It supports `open`, `navigate`, `snapshot`, `screenshot` and the same page actions as `codenomad.act`: `click`, `type`, `select`, `hover`, `drag`, `scroll`, `press` and `wait`. +CodeNomad serves OpenCode's native browser tools (`tools.browser.*` and the built-in `browser` skill from `opencode.browser`, OpenCode 2.4+) directly from the visible web preview attached to each session. ## Integration and shared bridge Browser previews are an ordinary desktop feature and must work in user projects outside the CodeNomad source checkout. -- One bundled V2 plugin, `codenomad.automation`, is provisioned through native OpenCode plugin discovery in the selected host/WSL daemon namespace. Its definitions follow backend presence; browsers start and actions run only on tool calls. +- While a local desktop view with browser automation capability shows a session (`packages/ui/src/lib/native-browser-hold.ts`), it holds that session on the local backend (`PUT/DELETE /api/native-browser/holds/:holdId`, local UI requests only: `localUiRequest` also refuses clients behind a loopback proxy). +- `NativeBrowserAttachments` (`packages/server/src/opencode/native-browser/attachments.ts`) keeps one attachment per session, whichever workspaces' views hold it. It attaches through a holding workspace that owns the session's location (`ownsLocation`), retrying while none does, and checks ownership again when each command's turn in the preview queue comes: `open` targets only verified owners, and a lost owner fails the command without reading the preview or publishing its inventory, then attaches again. Admission reads the session's current location, so a session moved elsewhere refuses its queued commands. Inventory publications run one at a time and each reads the tab at its turn, since OpenCode replaces its inventory with every one it receives; a queued command's publication is acknowledged before the next command runs. Each web open, and each preview replaced by another registration, gives the tab a new ID. Previews browse over the desktop's network, as the person's own preview does, so OpenCode's server-network tunnel (`tunnel.*`, its `/proxy` entrypoint) is not used: a WSL daemon's `localhost` reaches the desktop, which WSL2's default localhost forwarding connects to WSL servers. A refused inventory publication still sends the command's result, and a command that cannot be read is settled as failed. Probes, opens and loads report the preview registration, and an open or load that ends in another preview fails. Probes name the verified owners, so only a preview registered in one of their project tabs serves the session. It attaches to OpenCode's `experimental.browser` RPC (version 4) with a long-lived `headersTimeout: 0` dispatcher. Internal `rpc.experimental.browser.control` events are consumed on the server bus and omitted from UI SSE streams (`/api/events`); the relay can deliver one event per owning workspace, so each request ID runs once. Cancellation and the end of an attachment abort its commands; a native request already sent is not recalled. +- `PreviewTab` (`packages/server/src/opencode/native-browser/commands.ts`) exposes the session's visible preview as a single tab whose generation advances with the document witness. Commands run one at a time and each keeps the target it started on; the tab reports the document's title and history (`Page.getNavigationHistory`; WebKit previews report none). Supported operations are `tabs.list`, `tabs.open`, `tabs.focus`, `navigate`, `back`, `forward`, `reload`, `snapshot`, `find`, `click`, `hover`, `drag`, `fill`, `fill_form`, `select`, `check`, `press`, `scroll`, `wait`, `screenshot`, `console`, `network.list` and `network.get`. Options an operation cannot honor (frames, interactive or depth-limited snapshots, cache-bypassing reload, background `tabs.open`, middle, right or double clicks, element or full-page screenshots) are refused, never ignored. `select` matches option values exactly (`select-values`); `check` reads the state attributes after the ref and confirms the state after clicking; `press` refuses clipboard and context-menu shortcuts like OpenCode's own browser; screenshots above OpenCode's 5 MiB file limit fail, and a result OpenCode refuses still settles its request as a failure; agent clicks refuse file inputs and their labels, and Electron and WebView2 also intercept native file pickers (`Page.setInterceptFileChooserDialog`) for the length of each agent page lease, lifted again when the lease ends or fails, Linux WebKitGTK cancels `run-file-chooser` while one of the preview's page leases is held, and on macOS the vendored Wry's `set_file_panels_refused` cancels the page's file panels for each agent page lease; `wait` for load follows the native probe's `loading` state, which the tab also reports; a `click` or `press` the page received before its document changed (a followed link, a submitted form) succeeds and returns the tab on the document it led to. WebKit previews (macOS and Linux Tauri) answer `back`, `forward` and `reload` as unsupported. Refs follow OpenCode's `e` format via a `BrowserPage` ref prefix. Unsupported operations (including `evaluate`) fail explicitly with `code: "unsupported"`. +- Console and network diagnostics follow OpenCode's desktop browser. Electron and WebView2 enable the `Runtime`, `Log` and `Network` domains on the preview's own protocol attachment, auto-attach out-of-process frames and dedicated workers paused at start (frames get the same domains in their sessions before they run; workers run and are left; every child is resumed even when its domains fail), and keep the listed raw events of the current document (`automation/page/diagnostic-events.ts`, generated `diagnostic-events.generated.json` for Rust) in a bounded buffer, each frame event tagged with its session. The buffer restarts its epoch when a main-frame navigation starts (WebView2: a new navigation ID, so redirects keep it) or `document.open()` replaces the document. Network events (with frame detaches) and the others have separate budgets, so a console flood never evicts a request's lifecycle; reads name, bounded like the buffer, the requests whose ending event (`loadingFinished`, `loadingFailed`, `webSocketClosed`, a WebSocket's handshake response or frame error) or frame detach was evicted unread, which the readout ends as failed instead of leaving pending; other lost events only count as drops. A readout whose tab or document changes while it is read fails with `document_changed`, and a web open reads the host's buffer before it navigates, so the new tab's readouts start with the open, its new page's startup included. WebView2 keeps one buffer per registration generation, so a candidate's setup or an older generation's removal leaves the published preview's. A new tab (a web open or another preview) starts with empty readouts; an event too large to keep whole keeps its console text cut past OpenCode's 2,000-character entry limit. The buffer also keeps the live execution contexts, which outlast epochs and evictions; only a frame's default context counts as the page's, as in OpenCode. The `diagnostics` page operation reads the events after a sequence number with the epoch, the live contexts and the epoch's console entries and requests evicted before any read; `response-body` reads one retained body in its frame's session. A body read fenced by a document change answers `document_changed`. `PreviewDiagnostics` (`opencode/native-browser/diagnostics.ts`, with the request machine ported from OpenCode in `diagnostics-machine.ts`) builds OpenCode's readouts: page-world console entries, Chromium log entries and uncaught errors (500 kept), requests with redirects and wire status (500 kept), `cookie`, `set-cookie`, `authorization` and `proxy-authorization` values redacted, and text bodies up to 20,000 characters. Electron starts capture when the guest is created, before its first load; WebView2 when the preview's webview is set up. WebKit previews answer diagnostics as unsupported. +- One bundled V2 plugin, `codenomad.automation`, is provisioned through native OpenCode plugin discovery in the selected host/WSL daemon namespace. Its definitions follow backend presence and expose `inspect`, `act`, and `screenshot` for CodeNomad's own desktop UI. - Provisioning follows the `config.get` discovery-root, sibling `.codenomad//` lease and WSL rules in `OPENCODE_COMPATIBILITY.md`. A lease mtime update beneath the watched root would reload every loaded location; only the new directory receives heartbeats; missing discovery information is reported, never guessed. -- The plugin exposes `browser`, `inspect`, `act`, and `screenshot` while a desktop backend is present. Tool availability is separate from plugin loading. -- Browser and developer calls share the backend's loopback registration and private native transport. Native instrumentation is prepared at normal startup and every tool is available. Execution still verifies the selected backend, supported native capabilities and invoking session. -- Developer inspection targets the native window, independently of its selected project/conversation (including empty views). The invoking session still identifies an owning backend; it need not be visible. Actions retain the inspected window/run and document-scoped accessibility references, so agents can navigate back themselves. Window automation stays valid across session/project selection; navigation, replaced pages, changed native targets or windows and restarts require fresh inspection. Browser-preview tools retain their separate per-session attachment rules. -- `packages/server/src/server/routes/automation-plugin.ts` serves the `/api/opencode-plugin/automation` endpoint with the per-process token. -- `browser-claim` verifies exactly one browser-capable backend owning the session before an `open` action asks the UI to select a project-tab occurrence under the targeting rule below. -- `browser-probe` requires exactly one visible native preview registered to that session. -- `browser-execute` validates the browser action and forwards `browser.probe` or `browser.execute` over the fenced native-parent request channel. +- Developer inspection targets a local native window (including empty views). The invoking session identifies an owning backend and helps choose the first window; it need not be visible. `inspect({targets:true})` lists eligible windows and invocation-scoped session presence; `inspect({target})` selects an exact returned identifier. A plain inspection keeps its selected window. Actions retain the inspected window/run and document, independently of focus and project/conversation selection. Document changes require a fresh inspection; a lost window requires a new selection. +- `packages/server/src/server/routes/automation-plugin.ts` serves the `/api/opencode-plugin/automation` endpoint with the per-process token for developer inspection, Mission dispatch (`browser-claim` with Mission `purpose`, `mission-input`), and memory bridge calls. An active backend publishes an ephemeral registration with a per-process 256-bit token and removes it on graceful shutdown. All bridge discovery checks the @@ -24,9 +23,9 @@ conservatively. Best-effort pruning removes recognized local registrations whose filename or parsed PID establishes absence. A file removed between enumeration and open is absent. Windows PIDs belong to their host namespace, so WSL discovery uses endpoint evidence for Windows registrations and leaves their files in place. -Windows path lookup is asynchronous, shares an in-flight lookup for the effective -distro/PATH, and ordinary discovery retains its cached result. Missions' strict -ownership and retry rules are in the [creation recovery contract](MISSIONS.md#mission-profile-selection-and-creation-recovery). +Windows path lookup reads `LOCALAPPDATA` as UTF-16LE from `cmd.exe /U`. It shares an in-flight lookup for the effective +distro/PATH, and ordinary discovery retains its cached result. +Missions' strict ownership and retry rules are in the [creation recovery contract](MISSIONS.md#mission-profile-selection-and-creation-recovery). ## Desktop instrumentation @@ -43,6 +42,7 @@ Windows Tauri (`packages/tauri-app/src-tauri/src/developer_mode.rs`): - Uses a persistent local `developer-mode` WebView2 directory inside the data profile, leaving isolated remote-window profiles untouched. - Gives only local WebViews `--remote-debugging-port=0`, then reads and verifies their `EBWebView/DevToolsActivePort` endpoint. - Enables Rust backtraces and Node source-map stack traces for the managed backend. +- Retains the latest 32 contextual preview errors in memory for the lifetime of the native process (2,048 characters per log entry). `developer.status` includes them in its native snapshot `logs`; `codenomad.inspect` exposes them as runtime diagnostics. The error dialog keeps the complete native message, including its HRESULT, after the localized heading. Copy that detail or the inspection diagnostics when reporting a preview failure. Packaged Electron main/preload/renderer, UI and server builds emit source maps. Local hosts sanitize inherited debugging flags; isolated remote-window profiles run without local instrumentation. Windows WebView2 is the supported Tauri CDP host. `packages/server/src/developer-cdp.ts` (`DeveloperCdp`) is the shared CDP controller and `opencode/automation-plugin.ts` the OpenCode adapter. `.opencode/skills/codenomad-automation/SKILL.md` holds the inspect, edit, build, relaunch, reconnect and evidence workflow. @@ -52,26 +52,34 @@ Windows registry-path discovery in WSL uses asynchronous interop with bounded co Memory admission cancellation reaches both discovery commands and registry scans; only a qualified path is retained across calls. -`codenomad.act({ action: "restart" })` asks the host pinned by the latest successful inspection to relaunch gracefully, ignores the old registration, waits for the same native identity with a new run, re-inspects it for the invoking session and returns that inspection. It never switches to another worktree build. +`codenomad.act({ action: "restart" })` relaunches the inspected desktop scope (data profile, original config source, executable and Electron app artifact) through the native graceful shutdown. The bridge verifies the current inspection pin and sends its window UUID, incarnation, native scope and run ID with a fresh restart ID to `developer.restartScope`. The host rechecks the exact window before shutdown. The relaunch uses ordinary window restoration and preserves the profile manager's next choice. + +Electron's scope binds the physical main module as well as the package root. Direct CLI launches relaunch the resolved script; directory launches keep the package root and require a fresh Electron-compatible entry resolution before admission. The filesystem can still change between admission and the native loader opening the entry; the next CodeNomad run checks the resulting identity before restoring the scope. + +`developer-reconnect` checks a new registration for the one-shot restart handoff in a new run of the same scope. It reports a missing UUID, waits for a loading window, or issues a fresh inspection pin for the original UUID's new incarnation. Reconnection uses the same renderer identity and session-ownership checks as ordinary inspection. Transport uncertainty permits read-only reconnection; never resend the restart. Mixed versions refuse restart. + +A restart acknowledgement or uncertain delivery retires the run's inspection pins, refs and pending CDP reads. If the profile stays open, a fresh inspection of an exact ready window can issue a new pin. - The HTTP bridge and CDP endpoint use IPv4 loopback only. The bridge requires its random token. Raw CDP has no authentication and can execute code in authenticated renderer pages, so it trusts local processes; the bridge keeps its token and session/window selection checks. -- The host targets the focused local window, or the most recent local window when CodeNomad is not focused. Preferences and remote windows are never targets. -- Operations for one native run are serialized. Click and type revalidate context immediately before input; inspection and screenshot revalidate after capture. -- Actions and screenshots require a successful inspection and stay pinned to that registration until another inspection or a verified restart replaces it. +- Initial discovery prefers a window visibly showing the invoking session, then a window with that session selected in an inactive tab, then a ready window. Focus and local recency break ties within a profile; equally ranked profiles require an explicit selection. Preferences and remote windows are never targets. `developer.targets` supplies the ready local inventory; `developer.status {runId,windowId,windowInstance}` validates the pinned incarnation, including when another window reuses the saved window ID. +- Operations for one native window incarnation are serialized. Immediately before native dispatch, the marked document root checks the current window, the active tab for new input, and the live viewport hit or keyboard focus, including the exact element for ref actions. An ambiguous closed-shadow destination is refused. Inspection and screenshot revalidate after capture. +- Actions, ref expansions, screenshots and restart require the exact receipt from a successful inspection in the invoking session. The OpenCode adapter retains it privately for the inspected window. Without a receipt, another inspection of the selected window sends its exact identifier and verifies the returned window before presenting the outline. +- A newer selection takes precedence over a pending reconnect; the bridge checks before reading CDP and before publishing the restored window's pin. - Registration files, bridge responses, target probes, diagnostics, accessibility snapshots, screenshots, request bodies and reconnect time are bounded. ## Page engine -`codenomad.inspect` / `codenomad.act` (the CodeNomad window) and `codenomad.browser` (the session preview) run on the same page engine in `packages/server/src/automation/page/`. `protocol.ts` defines the semantic `PageDriver`: normalized tree, stable node/handle resolution, predefined function calls with JSON arguments, geometry, viewport, hit testing, native input, handle release and checkpoints. `cdp-driver.ts` adapts that contract to DevTools; `native-driver.ts` uses the fenced parent channel. `snapshot.ts` retains the outline renderer and budgets, `actions.ts`/`input.ts` retain action orchestration, `keys.ts` maps chords, and `refs.ts` owns document-scoped references. The app uses `DeveloperCdp`; previews use `automation/browser-page.ts`. The preview's `snapshot({ ref, query })` has the same outline and scoping as the app's `inspect`. +`codenomad.inspect` / `codenomad.act` (the CodeNomad window) and OpenCode's native `tools.browser.*` (the session preview) run on the same page engine in `packages/server/src/automation/page/`. `protocol.ts` defines the semantic `PageDriver`: normalized tree, stable node/handle resolution, predefined function calls with JSON arguments, geometry, viewport, hit testing, native input, handle release and checkpoints. `cdp-driver.ts` adapts that contract to DevTools; `native-driver.ts` uses the fenced parent channel. `snapshot.ts` retains the outline renderer and budgets, `actions.ts`/`input.ts` retain action orchestration, `keys.ts` maps chords, and `refs.ts` owns document-scoped references. The app uses `DeveloperCdp`; previews use `automation/browser-page.ts`. The preview's `snapshot({ ref })` and `find({ text })` have the same outline and scoping as the app's `inspect` with `ref` and `query`. - Inspection is an indented outline with refs, read as plain text. Wrappers, unnamed images and text repeating its parent's name are dropped; fields show their value instead of their inner nodes; native selects list their options with `selected`/`disabled`. A character budget (32 000 by default) is shared among siblings: small parts stay whole while large ones collapse in place with `(+N hidden)` or `(+N more)`, keeping their first and last items, so nothing is cut silently. `ref` expands one subtree and `query` keeps elements whose name, value or description contains it, or whose role is exactly it, with their contents and ancestors. - A ref names one node within one target, run and navigation epoch. It keeps its name and stays usable for the life of that page generation, whatever is inspected later; a node that left the page fails its action explicitly. - `type` focuses the field and refuses one that cannot take focus (hidden, disabled, behind a modal dialog), because native text insertion goes to the focused element. It then replaces the field's text by default (select, then native insertion, so framework input handlers fire); `clear: false` appends. Date, time, range and color inputs are validated before anything changes, then set with `input`/`change`, keeping the browser's normalization; email and number inputs append as a value. `select` picks native ` options by label or value, hover, drag onto another ref, scroll (a ref or the page), press a key or chord (optionally after focusing a ref), or wait for text to appear or disappear. restart gracefully relaunches CodeNomad and waits for reconnection.", + description: "Act on refs from the latest codenomad.inspect like a user: click (real pointer at the element's visible centre, refused when covered), type into a field (replacing its text unless clear is false), select native Download fixtureDialog idle +
Below idle Follow link ", "forms": "
\n \n \n
Old rich
\n \n \n \n
", "edges": "
\n \n
More
\n
\n \n \n \n \n \n \n
one
two
\n

Mission

\n \n
", - "inputs": "
\n
\n idle\n \n
tall
\n
\n
\n
\n
\n
\n
\n

\n
" + "inputs": "
\n
\n idle\n \n
tall
\n
\n
\n
\n
\n
\n
\n

\n
" } diff --git a/packages/tauri-app/tests/private-preview-url-cases.json b/packages/tauri-app/tests/private-preview-url-cases.json new file mode 100644 index 0000000000..7cd6159653 --- /dev/null +++ b/packages/tauri-app/tests/private-preview-url-cases.json @@ -0,0 +1,17 @@ +[ + { "url": "http://cap.preview.localhost:9999/start", "private": true }, + { "url": "https://CAP.PREVIEW.LOCALHOST/start", "private": true }, + { "url": "blob:http://cap.preview.localhost:9999/document", "private": true }, + { "url": "http://127.0.0.1:9999/start", "private": false }, + { "url": "http://localhost:9999/start", "private": false }, + { "url": "https://example.com/.preview.localhost/start", "private": false }, + { "url": "https://example.com/?next=http://cap.preview.localhost/start", "private": false }, + { "url": "https://example.com/#http://cap.preview.localhost/start", "private": false }, + { "url": "https://x.preview.localhost.evil.test/start", "private": false }, + { "url": "https://notpreview.localhost/start", "private": false }, + { "url": "https://preview.localhost/start", "private": false }, + { "url": "blob:https://example.com/.preview.localhost/document", "private": false }, + { "url": "data:text/plain,http://cap.preview.localhost/start", "private": false }, + { "url": "file://cap.preview.localhost/start", "private": false }, + { "url": "not a URL .preview.localhost/start", "private": false } +] diff --git a/packages/tauri-app/tests/webkit-live-audio.c b/packages/tauri-app/tests/webkit-live-audio.c new file mode 100644 index 0000000000..67ce6b0550 --- /dev/null +++ b/packages/tauri-app/tests/webkit-live-audio.c @@ -0,0 +1,100 @@ +/* cc webkit-live-audio.c $(pkg-config --cflags --libs webkit2gtk-4.1) -o webkit-live-audio + * From packages/ui/src/lib, serve the worklet with python3 -m http.server --bind 127.0.0.1 8000. + * GDK_BACKEND=x11 xvfb-run -a ./webkit-live-audio http://127.0.0.1:8000/ + */ +#include + +static int result = 1; + +static void evaluated(WebKitWebView *view, GAsyncResult *reply, gpointer data) { + GError *error = NULL; + JSCValue *value = webkit_web_view_call_async_javascript_function_finish(view, reply, &error); + result = !(value && jsc_value_is_boolean(value) && jsc_value_to_boolean(value)); + g_print("WebKitGTK synthetic live audio: %s\n", result ? (error ? error->message : "failed") : "ok"); + g_clear_error(&error); + g_clear_object(&value); + gtk_main_quit(); +} + +static void loaded(WebKitWebView *view, WebKitLoadEvent event, gpointer data) { + if (event != WEBKIT_LOAD_FINISHED) + return; + + const char *test = + "const ctx = new AudioContext();" + "const resume = ctx.resume();" + "const frame = document.body.appendChild(document.createElement('iframe'));" + "frame.hidden = true;" + "const stream = await frame.contentWindow.navigator.mediaDevices.getUserMedia({audio: true});" + "try {" + " await ctx.audioWorklet.addModule('./live-voice-worklet.js');" + " const recorder = new AudioWorkletNode(ctx, 'codenomad-live-capture', {" + " outputChannelCount: [1], processorOptions: {inputRate: 16000}" + " });" + " const player = new AudioWorkletNode(ctx, 'codenomad-live-playback', {" + " numberOfInputs: 0, outputChannelCount: [1], processorOptions: {outputRate: 24000, capacity: 24000}" + " });" + " ctx.createMediaStreamSource(stream).connect(recorder).connect(ctx.destination);" + " player.connect(ctx.destination);" + " const captured = new Promise((resolve, reject) => recorder.port.onmessage = ({data}) => {" + " if (!(data instanceof ArrayBuffer) || data.byteLength !== 640) { reject(new Error('invalid capture chunk')); return; }" + " recorder.port.postMessage(null);" + " if (new Uint8Array(data).some(n => n)) resolve(true);" + " });" + " const cleared = new Promise(resolve => player.port.onmessage = ({data}) => {" + " if (data.flush) resolve(data.rendered);" + " else if (data.rendered > 1200) player.port.postMessage(true);" + " });" + " player.port.postMessage(new ArrayBuffer(48000));" + " const [pcm, rendered] = await Promise.race([Promise.all([captured, cleared, resume]), new Promise((_, reject) => {" + " recorder.onprocessorerror = () => reject(new Error('capture processor error'));" + " player.onprocessorerror = () => reject(new Error('playback processor error'));" + " setTimeout(() => reject(new Error(`audio graph stalled: ${ctx.state} at ${ctx.currentTime}s`)), 3000);" + " })]);" + " if (!pcm || rendered <= 1200 || rendered >= 24000) throw new Error(`bad interruption: ${rendered} frames`);" + " return true;" + "} finally { stream.getTracks().forEach(track => track.stop()); frame.remove(); void ctx.close(); }"; + + webkit_web_view_call_async_javascript_function(view, test, -1, NULL, NULL, + NULL, NULL, (GAsyncReadyCallback)evaluated, NULL); +} + +static gboolean expired(gpointer data) { + g_printerr("WebKitGTK synthetic live audio timed out\n"); + gtk_main_quit(); + return G_SOURCE_REMOVE; +} + +static gboolean permission(WebKitWebView *view, WebKitPermissionRequest *request, gpointer data) { + if (!WEBKIT_IS_USER_MEDIA_PERMISSION_REQUEST(request)) + return FALSE; + WebKitUserMediaPermissionRequest *media = WEBKIT_USER_MEDIA_PERMISSION_REQUEST(request); + WebKitSettings *settings = webkit_web_view_get_settings(view); + if (webkit_settings_get_enable_mock_capture_devices(settings) + && webkit_user_media_permission_is_for_audio_device(media) + && !webkit_user_media_permission_is_for_video_device(media)) + webkit_permission_request_allow(request); + else + webkit_permission_request_deny(request); + return TRUE; +} + +int main(int argc, char **argv) { + if (argc != 2) + return 2; + gtk_init(&argc, &argv); + GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL); + WebKitWebView *view = WEBKIT_WEB_VIEW(webkit_web_view_new()); + WebKitSettings *settings = webkit_web_view_get_settings(view); + webkit_settings_set_media_playback_requires_user_gesture(settings, FALSE); + webkit_settings_set_enable_media_stream(settings, TRUE); + webkit_settings_set_enable_mock_capture_devices(settings, TRUE); + g_signal_connect(view, "permission-request", G_CALLBACK(permission), NULL); + g_signal_connect(view, "load-changed", G_CALLBACK(loaded), NULL); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + gtk_widget_show_all(window); + webkit_web_view_load_uri(view, argv[1]); + g_timeout_add_seconds(12, expired, NULL); + gtk_main(); + return result; +} diff --git a/packages/tauri-app/tests/webkit-microphone.c b/packages/tauri-app/tests/webkit-microphone.c new file mode 100644 index 0000000000..50323d5a2a --- /dev/null +++ b/packages/tauri-app/tests/webkit-microphone.c @@ -0,0 +1,149 @@ +/* Build with cc webkit-microphone.c $(pkg-config --cflags --libs webkit2gtk-4.1) -o webkit-microphone + * Run with GDK_BACKEND=x11 xvfb-run -a ./webkit-microphone + */ +#include + +static gboolean permit; +static unsigned grants, denials, phase; +static int result = 1; + +static gboolean permission(WebKitWebView *view, WebKitPermissionRequest *request, gpointer data) { + if (!WEBKIT_IS_USER_MEDIA_PERMISSION_REQUEST(request)) + return FALSE; + WebKitUserMediaPermissionRequest *media = WEBKIT_USER_MEDIA_PERMISSION_REQUEST(request); + if (permit && webkit_user_media_permission_is_for_audio_device(media) + && !webkit_user_media_permission_is_for_video_device(media)) { + permit = FALSE; + ++grants; + webkit_permission_request_allow(request); + } else { + ++denials; + webkit_permission_request_deny(request); + } + return TRUE; +} + +/* Exercise the engine's permission cache with a real capture device replacement. + * Rust tests separately exercise CodeNomad's ownership and IPC permit rules. */ +static const struct { + gboolean permit; + const char *body; +} cases[] = { + { FALSE, "try { await navigator.mediaDevices.getUserMedia({audio:true}); return false; }" + "catch (error) { return error.name === 'NotAllowedError'; }" }, + { TRUE, "const preview = document.createElement('iframe');" + "preview.setAttribute('allow', \"microphone 'none'; camera 'none'\");" + "document.body.append(preview);" + "try { await preview.contentWindow.navigator.mediaDevices.getUserMedia({audio:true}); return false; }" + "catch (error) { return error.name === 'NotAllowedError'; } finally { preview.remove(); }" }, + { TRUE, "window.frame = document.body.appendChild(document.createElement('iframe'));" + "frame.hidden = true;" + "const audio = await frame.contentWindow.navigator.mediaDevices.getUserMedia({audio:true});" + "const context = new AudioContext();" + "const worklet = `registerProcessor('mock', class extends AudioWorkletProcessor {" + " process(inputs) { if (inputs[0]?.[0]?.length) this.port.postMessage(inputs[0][0].length); return true; }" + "});`;" + "const url = URL.createObjectURL(new Blob([worklet], { type:'text/javascript' }));" + "await context.audioWorklet.addModule(url); URL.revokeObjectURL(url);" + "const node = new AudioWorkletNode(context, 'mock');" + "const count = new Promise(resolve => node.port.onmessage = event => resolve(event.data));" + "context.createMediaStreamSource(audio).connect(node).connect(context.destination);" + "await context.resume(); if (await count <= 0) return false;" + "audio.getTracks().forEach(track => track.stop()); frame.remove(); await context.close();" + "return audio.getAudioTracks()[0].readyState === 'ended';" }, + { FALSE, "try { await navigator.mediaDevices.getUserMedia({audio:true}); return false; }" + "catch (error) { return error.name === 'NotAllowedError'; }" }, + { TRUE, "window.frame = document.body.appendChild(document.createElement('iframe'));" + "frame.hidden = true;" + "window.audio = await frame.contentWindow.navigator.mediaDevices.getUserMedia({audio:{channelCount:1}});" + "const context = new AudioContext();" + "const source = context.createMediaStreamSource(audio);" + "source.connect(context.createAnalyser());" + "await context.resume(); await context.close();" + "return audio.getAudioTracks()[0].readyState === 'live';" }, + { FALSE, "frame.remove(); return audio.getAudioTracks()[0].readyState === 'ended';" }, + { FALSE, "try { await navigator.mediaDevices.getUserMedia({audio:true}); return false; }" + "catch (error) { return error.name === 'NotAllowedError'; }" }, + { TRUE, "window.frame = document.body.appendChild(document.createElement('iframe'));" + "window.audio = await frame.contentWindow.navigator.mediaDevices.getUserMedia({audio:true});" + "return audio.getAudioTracks()[0].readyState === 'live';" }, + { FALSE, "const track = audio.getAudioTracks()[0];" + "if (track.readyState !== 'ended') await new Promise(resolve => track.addEventListener('ended', resolve, {once:true}));" + "try { await frame.contentWindow.navigator.mediaDevices.getUserMedia({audio:true}); return false; }" + "catch (error) { return error.name === 'NotAllowedError'; } finally { frame.remove(); }" }, + { FALSE, "try { await navigator.mediaDevices.getUserMedia({audio:true}); return false; }" + "catch (error) { return error.name === 'NotAllowedError'; }" }, +}; + +static void next(WebKitWebView *view); + +static void evaluated(WebKitWebView *view, GAsyncResult *reply, gpointer data) { + GError *error = NULL; + JSCValue *value = webkit_web_view_call_async_javascript_function_finish(view, reply, &error); + gboolean passed = value && jsc_value_is_boolean(value) && jsc_value_to_boolean(value); + g_print("capture check %u: %s\n", phase + 1, passed ? "ok" : error ? error->message : "failed"); + g_clear_error(&error); + g_clear_object(&value); + if (!passed) { + gtk_main_quit(); + } else if (++phase == G_N_ELEMENTS(cases)) { + result = grants != 3 || denials != 5; + g_print("decisions: %u allowed, %u denied\n", grants, denials); + gtk_main_quit(); + } else if (phase + 1 == G_N_ELEMENTS(cases)) { + webkit_web_view_load_html(view, "Reload", "http://127.0.0.1/"); + } else { + if (phase == G_N_ELEMENTS(cases) - 2) + webkit_web_view_set_microphone_capture_state(view, WEBKIT_MEDIA_CAPTURE_STATE_NONE); + next(view); + } +} + +static void next(WebKitWebView *view) { + permit = cases[phase].permit; + webkit_web_view_call_async_javascript_function(view, cases[phase].body, -1, NULL, NULL, + NULL, NULL, (GAsyncReadyCallback)evaluated, NULL); +} + +static void loaded(WebKitWebView *view, WebKitLoadEvent event, gpointer data) { + if (event == WEBKIT_LOAD_FINISHED) + next(view); +} + +static gboolean expired(gpointer data) { + g_printerr("Timed out during check %u\n", phase + 1); + gtk_main_quit(); + return G_SOURCE_REMOVE; +} + +int main(int argc, char **argv) { + gtk_init(&argc, &argv); + GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL); + WebKitWebView *view = WEBKIT_WEB_VIEW(webkit_web_view_new()); + WebKitSettings *settings = webkit_web_view_get_settings(view); + webkit_settings_set_enable_media_stream(settings, TRUE); + webkit_settings_set_enable_mock_capture_devices(settings, TRUE); + gboolean mock_prompt = FALSE; + WebKitFeatureList *features = webkit_settings_get_all_features(); + for (gsize i = 0; i < webkit_feature_list_get_length(features); ++i) { + WebKitFeature *feature = webkit_feature_list_get(features, i); + if (g_str_equal(webkit_feature_get_identifier(feature), "MockCaptureDevicesPrompt")) { + webkit_settings_set_feature_enabled(settings, feature, TRUE); + mock_prompt = TRUE; + break; + } + } + webkit_feature_list_unref(features); + if (!mock_prompt) { + g_printerr("WebKitGTK does not expose mock capture prompts; no capture attempted\n"); + return 77; + } + g_signal_connect(view, "permission-request", G_CALLBACK(permission), NULL); + g_signal_connect(view, "load-changed", G_CALLBACK(loaded), NULL); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + gtk_widget_show_all(window); + webkit_web_view_load_html(view, "Mock microphone", "http://127.0.0.1/"); + g_timeout_add_seconds(15, expired, NULL); + gtk_main(); + return result; +} diff --git a/packages/tauri-app/vendor/README.md b/packages/tauri-app/vendor/README.md index 0a0f180d19..cc835ff12b 100644 --- a/packages/tauri-app/vendor/README.md +++ b/packages/tauri-app/vendor/README.md @@ -12,8 +12,12 @@ MIT/Apache-2.0 crates, including licenses, selected through `[patch.crates-io]`. - Local changes: `patches/tauri-runtime-wry-gtk.patch` and `patches/wry-gtk.patch`, then `patches/wry-webkit-capabilities.patch`, `patches/wry-browser-isolation.patch`, `patches/runtime-browser-isolation.patch` - `patches/wry-browser-print.patch` and `patches/wry-browser-download.patch`; + `patches/wry-browser-print.patch`, `patches/wry-browser-download.patch`, + `patches/wry-browser-private-preview.patch`, `patches/runtime-browser-private-preview.patch` + `patches/runtime-cookie-dispatch.patch` and `patches/wry-agent-file-panels.patch`; native trials ship beside the runtime examples. +- Cookie installation releases the runtime's webview window-ID lock before + dispatch: WebKitGTK may handle a new window IPC while its cookie write completes. - GTK: the runtime lazily installs a window-owned `GtkOverlay` inside Tao's content box, below its menu bar. Primary content stays boxed, including a window's own webview in Tauri's multi-webview mode (it requests no bounds), so a @@ -48,11 +52,23 @@ MIT/Apache-2.0 crates, including licenses, selected through `[patch.crates-io]`. stay owned by the engine. Preview navigation gestures use Wry's native setting. WebView2 popup script closure disposes the top-level popup instead of only its child container; embedded roots remain host-owned. + The runtime installs only the fixed privilege-free remote-preview protection + program in browser guests; application scripts, IPC and resource protocols keep + their existing fence. - WKWebView preview printing and beforeunload use the native delegate selectors in WebKit's `WKUIDelegatePrivate.h`: both printFrame variants and the initiating-frame beforeunload completion. Printing uses the public `printOperationWithPrintInfo:` operation and system panel. Qualify these - selectors on supported macOS/WebKit updates with the native fixture. + selectors on supported macOS/WebKit updates with the native fixture. + Private preview origins refuse native printing and beforeunload confirmations; + the latter cancel navigation and retain the current page. + Native menus use an expression-valued nullable `method_id` return for objc2. + `src/preview_origin.rs` parses HTTP(S) and blob content origins and checks the + isolated host suffix; Tauri shares that predicate. Paths, queries and foreign + host suffixes retain ordinary browser actions. The shared cases in + `../tests/private-preview-url-cases.json` qualify native and preload predicates. +- `set_file_panels_refused` marks a WKWebView whose page-opened file panels are cancelled unseen; Tauri sets it + for the length of each agent page lease, as WebView2 intercepts file choosers. - WKWebView's `_webView:contextMenuDidCreateDownload:` callback, declared by `WKNavigationDelegatePrivate.h`, attaches the same download delegate as native navigation downloads. Both paths use the preview's Downloads-folder policy. diff --git a/packages/tauri-app/vendor/patches/runtime-browser-private-preview.patch b/packages/tauri-app/vendor/patches/runtime-browser-private-preview.patch new file mode 100644 index 0000000000..ab8d272faa --- /dev/null +++ b/packages/tauri-app/vendor/patches/runtime-browser-private-preview.patch @@ -0,0 +1,8 @@ +--- a/src/lib.rs ++++ b/src/lib.rs +@@ -5125,0 +5126,5 @@ ++ if browser_guest { ++ webview_builder = webview_builder.with_initialization_script_for_main_only( ++ include_str!("../../../../ui/src/lib/native/remote-preview-guards.cjs"), false); ++ } ++ diff --git a/packages/tauri-app/vendor/patches/runtime-cookie-dispatch.patch b/packages/tauri-app/vendor/patches/runtime-cookie-dispatch.patch new file mode 100644 index 0000000000..34e4624a32 --- /dev/null +++ b/packages/tauri-app/vendor/patches/runtime-cookie-dispatch.patch @@ -0,0 +1,12 @@ +diff --git a/src/lib.rs b/src/lib.rs +index 933e42ac6..42896c5be 100644 +--- a/src/lib.rs ++++ b/src/lib.rs +@@ -1706,4 +1706,6 @@ impl WebviewDispatch for WryWebviewDispatcher { + fn set_cookie(&self, cookie: Cookie<'_>) -> Result<()> { ++ // GTK may dispatch another IPC while waiting for the cookie store. ++ let window_id = *self.window_id.lock().unwrap(); + self.context.send_user_message(Message::Webview( +- *self.window_id.lock().unwrap(), ++ window_id, + self.webview_id, diff --git a/packages/tauri-app/vendor/patches/wry-agent-file-panels.patch b/packages/tauri-app/vendor/patches/wry-agent-file-panels.patch new file mode 100644 index 0000000000..5a949170db --- /dev/null +++ b/packages/tauri-app/vendor/patches/wry-agent-file-panels.patch @@ -0,0 +1,79 @@ +diff --git a/src/lib.rs b/src/lib.rs +index acc88af8d..2127c128e 100644 +--- a/src/lib.rs ++++ b/src/lib.rs +@@ -389,6 +389,8 @@ mod preview_origin; + use wkwebview::*; + #[cfg(any(target_os = "macos", target_os = "ios"))] + pub use wkwebview::{PrintMargin, PrintOptions, WryWebView}; ++#[cfg(target_os = "macos")] ++pub use wkwebview::file_panels::set_file_panels_refused; + + #[cfg(target_os = "windows")] + pub(crate) mod webview2; +diff --git a/src/wkwebview/class/wry_web_view_ui_delegate.rs b/src/wkwebview/class/wry_web_view_ui_delegate.rs +index 7392352d9..7a361072f 100644 +--- a/src/wkwebview/class/wry_web_view_ui_delegate.rs ++++ b/src/wkwebview/class/wry_web_view_ui_delegate.rs +@@ -250,6 +250,13 @@ define_class!( + handler: &block2::Block)>, + ) { + unsafe { ++ // CodeNomad: a panel the page opens during an agent's page action is cancelled unseen. ++ if crate::wkwebview::file_panels::file_panels_refused( ++ _webview as *const WryWebView as *const std::ffi::c_void, ++ ) { ++ (*handler).call((null_mut(),)); ++ return; ++ } + if let Some(mtm) = MainThreadMarker::new() { + let open_panel = NSOpenPanel::openPanel(mtm); + open_panel.setCanChooseFiles(true); +diff --git a/src/wkwebview/file_panels.rs b/src/wkwebview/file_panels.rs +new file mode 100644 +index 000000000..c52b536fb +--- /dev/null ++++ b/src/wkwebview/file_panels.rs +@@ -0,0 +1,28 @@ ++// CodeNomad: an agent's page actions cancel the file panels a page opens (see the vendor README). ++use std::{ ++ collections::HashSet, ++ ffi::c_void, ++ sync::{Mutex, OnceLock}, ++}; ++ ++fn refused() -> &'static Mutex> { ++ static REFUSED: OnceLock>> = OnceLock::new(); ++ REFUSED.get_or_init(Default::default) ++} ++ ++/// While set for a WKWebView, a file panel its page opens is cancelled without being shown. ++pub fn set_file_panels_refused(webview: *mut c_void, refused_now: bool) { ++ if let Ok(mut set) = refused().lock() { ++ if refused_now { ++ set.insert(webview as usize); ++ } else { ++ set.remove(&(webview as usize)); ++ } ++ } ++} ++ ++pub(crate) fn file_panels_refused(webview: *const c_void) -> bool { ++ refused() ++ .lock() ++ .is_ok_and(|set| set.contains(&(webview as usize))) ++} +\ No newline at end of file +diff --git a/src/wkwebview/mod.rs b/src/wkwebview/mod.rs +index 9b1db532b..00cd68eac 100644 +--- a/src/wkwebview/mod.rs ++++ b/src/wkwebview/mod.rs +@@ -4,6 +4,8 @@ + + mod download; + #[cfg(target_os = "macos")] ++pub(crate) mod file_panels; ++#[cfg(target_os = "macos")] + mod drag_drop; + mod navigation; + #[cfg(feature = "mac-proxy")] diff --git a/packages/tauri-app/vendor/patches/wry-browser-private-preview.patch b/packages/tauri-app/vendor/patches/wry-browser-private-preview.patch new file mode 100644 index 0000000000..9123deee9c --- /dev/null +++ b/packages/tauri-app/vendor/patches/wry-browser-private-preview.patch @@ -0,0 +1,50 @@ +--- a/src/wkwebview/class/wry_web_view_ui_delegate.rs ++++ b/src/wkwebview/class/wry_web_view_ui_delegate.rs +@@ -119,0 +120,4 @@ ++ if crate::preview_origin::private_preview_host(&unsafe { frame.securityOrigin().host() }.to_string()) { ++ completion.call((false.into(),)); ++ return; ++ } +@@ -466,0 +471,3 @@ ++ if webview.URL().and_then(|url| url.absoluteString()).is_some_and(|url| crate::preview_origin::private_preview_url(&url.to_string())) { ++ return; ++ } +--- a/src/wkwebview/class/wry_web_view.rs ++++ b/src/wkwebview/class/wry_web_view.rs +@@ -57,0 +58,12 @@ ++ #[cfg(target_os = "macos")] ++ #[unsafe(method_id(menuForEvent:))] ++ fn menu_for_event(&self, event: &NSEvent) -> Option> { ++ unsafe { ++ if self.URL().and_then(|url| url.absoluteString()).is_some_and(|url| crate::preview_origin::private_preview_url(&url.to_string())) { ++ None ++ } else { ++ objc2::msg_send![super(self), menuForEvent: event] ++ } ++ } ++ } ++ +--- a/src/lib.rs ++++ b/src/lib.rs +@@ -385,0 +386,2 @@ ++#[cfg(any(target_os = "macos", target_os = "ios"))] ++mod preview_origin; +--- /dev/null ++++ b/src/preview_origin.rs +@@ -0,0 +1,16 @@ ++pub(crate) fn private_preview_host(host: &str) -> bool { ++ host.ends_with(".preview.localhost") ++} ++ ++pub(crate) fn private_preview_url(raw: &str) -> bool { ++ let Ok(parsed) = url::Url::parse(raw) else { return false }; ++ let content = if parsed.scheme() == "blob" { ++ url::Url::parse(parsed.path()).ok() ++ } else { ++ Some(parsed) ++ }; ++ content.is_some_and(|url| { ++ matches!(url.scheme(), "http" | "https") ++ && url.host_str().is_some_and(private_preview_host) ++ }) ++} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/lib.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/lib.rs index adbdef5aca..42896c5be2 100644 --- a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/lib.rs +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/lib.rs @@ -1704,8 +1704,10 @@ impl WebviewDispatch for WryWebviewDispatcher { } fn set_cookie(&self, cookie: Cookie<'_>) -> Result<()> { + // GTK may dispatch another IPC while waiting for the cookie store. + let window_id = *self.window_id.lock().unwrap(); self.context.send_user_message(Message::Webview( - *self.window_id.lock().unwrap(), + window_id, self.webview_id, WebviewMessage::SetCookie(cookie.into_owned()), ))?; @@ -5130,6 +5132,11 @@ You may have it installed on another user account, but it is not available for t } } + if browser_guest { + webview_builder = webview_builder.with_initialization_script_for_main_only( + include_str!("../../../../ui/src/lib/native/remote-preview-guards.cjs"), false); + } + for (scheme, protocol) in uri_scheme_protocols { // Preview documents retain their browser globals (not app plugin overrides) // and carry neither the application IPC bridge nor app resource protocols. diff --git a/packages/tauri-app/vendor/wry-0.57.1/src/lib.rs b/packages/tauri-app/vendor/wry-0.57.1/src/lib.rs index 9835e3f6f0..2127c128ee 100644 --- a/packages/tauri-app/vendor/wry-0.57.1/src/lib.rs +++ b/packages/tauri-app/vendor/wry-0.57.1/src/lib.rs @@ -384,9 +384,13 @@ use objc2_web_kit::WKUserContentController; #[cfg(any(target_os = "macos", target_os = "ios"))] pub(crate) mod wkwebview; #[cfg(any(target_os = "macos", target_os = "ios"))] +mod preview_origin; +#[cfg(any(target_os = "macos", target_os = "ios"))] use wkwebview::*; #[cfg(any(target_os = "macos", target_os = "ios"))] pub use wkwebview::{PrintMargin, PrintOptions, WryWebView}; +#[cfg(target_os = "macos")] +pub use wkwebview::file_panels::set_file_panels_refused; #[cfg(target_os = "windows")] pub(crate) mod webview2; diff --git a/packages/tauri-app/vendor/wry-0.57.1/src/preview_origin.rs b/packages/tauri-app/vendor/wry-0.57.1/src/preview_origin.rs new file mode 100644 index 0000000000..ed735e055f --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/src/preview_origin.rs @@ -0,0 +1,16 @@ +pub(crate) fn private_preview_host(host: &str) -> bool { + host.ends_with(".preview.localhost") +} + +pub(crate) fn private_preview_url(raw: &str) -> bool { + let Ok(parsed) = url::Url::parse(raw) else { return false }; + let content = if parsed.scheme() == "blob" { + url::Url::parse(parsed.path()).ok() + } else { + Some(parsed) + }; + content.is_some_and(|url| { + matches!(url.scheme(), "http" | "https") + && url.host_str().is_some_and(private_preview_host) + }) +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/src/wkwebview/class/wry_web_view.rs b/packages/tauri-app/vendor/wry-0.57.1/src/wkwebview/class/wry_web_view.rs index 60c7893156..df46326167 100644 --- a/packages/tauri-app/vendor/wry-0.57.1/src/wkwebview/class/wry_web_view.rs +++ b/packages/tauri-app/vendor/wry-0.57.1/src/wkwebview/class/wry_web_view.rs @@ -55,6 +55,18 @@ define_class!( } } + #[cfg(target_os = "macos")] + #[unsafe(method_id(menuForEvent:))] + fn menu_for_event(&self, event: &NSEvent) -> Option> { + unsafe { + if self.URL().and_then(|url| url.absoluteString()).is_some_and(|url| crate::preview_origin::private_preview_url(&url.to_string())) { + None + } else { + objc2::msg_send![super(self), menuForEvent: event] + } + } + } + #[cfg(target_os = "macos")] #[unsafe(method(acceptsFirstMouse:))] fn accept_first_mouse(&self, _event: &NSEvent) -> Bool { diff --git a/packages/tauri-app/vendor/wry-0.57.1/src/wkwebview/class/wry_web_view_ui_delegate.rs b/packages/tauri-app/vendor/wry-0.57.1/src/wkwebview/class/wry_web_view_ui_delegate.rs index dc5ea9e8b7..7a361072f8 100644 --- a/packages/tauri-app/vendor/wry-0.57.1/src/wkwebview/class/wry_web_view_ui_delegate.rs +++ b/packages/tauri-app/vendor/wry-0.57.1/src/wkwebview/class/wry_web_view_ui_delegate.rs @@ -117,6 +117,10 @@ define_class!( #[unsafe(method(_webView:runBeforeUnloadConfirmPanelWithMessage:initiatedByFrame:completionHandler:))] fn before_unload(&self, webview: &WryWebView, message: &objc2_foundation::NSString, frame: &WKFrameInfo, completion: &Block) { + if crate::preview_origin::private_preview_host(&unsafe { frame.securityOrigin().host() }.to_string()) { + completion.call((false.into(),)); + return; + } if !self.ivars().preview_dialogs { completion.call((true.into(),)); return; } self.javascript_confirm(objc2::sel!(webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:), webview, message, frame, completion); } @@ -246,6 +250,13 @@ define_class!( handler: &block2::Block)>, ) { unsafe { + // CodeNomad: a panel the page opens during an agent's page action is cancelled unseen. + if crate::wkwebview::file_panels::file_panels_refused( + _webview as *const WryWebView as *const std::ffi::c_void, + ) { + (*handler).call((null_mut(),)); + return; + } if let Some(mtm) = MainThreadMarker::new() { let open_panel = NSOpenPanel::openPanel(mtm); open_panel.setCanChooseFiles(true); @@ -464,6 +475,9 @@ impl WryWebViewUIDelegate { fn preview_print(webview: &WryWebView) { // Use the same public print operation as Wry's host-initiated printing. unsafe { + if webview.URL().and_then(|url| url.absoluteString()).is_some_and(|url| crate::preview_origin::private_preview_url(&url.to_string())) { + return; + } if webview.window().is_none() || objc2_app_kit::NSPrintOperation::currentOperation(MainThreadMarker::new().unwrap()) .is_some() diff --git a/packages/tauri-app/vendor/wry-0.57.1/src/wkwebview/file_panels.rs b/packages/tauri-app/vendor/wry-0.57.1/src/wkwebview/file_panels.rs new file mode 100644 index 0000000000..c52b536fbd --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/src/wkwebview/file_panels.rs @@ -0,0 +1,28 @@ +// CodeNomad: an agent's page actions cancel the file panels a page opens (see the vendor README). +use std::{ + collections::HashSet, + ffi::c_void, + sync::{Mutex, OnceLock}, +}; + +fn refused() -> &'static Mutex> { + static REFUSED: OnceLock>> = OnceLock::new(); + REFUSED.get_or_init(Default::default) +} + +/// While set for a WKWebView, a file panel its page opens is cancelled without being shown. +pub fn set_file_panels_refused(webview: *mut c_void, refused_now: bool) { + if let Ok(mut set) = refused().lock() { + if refused_now { + set.insert(webview as usize); + } else { + set.remove(&(webview as usize)); + } + } +} + +pub(crate) fn file_panels_refused(webview: *const c_void) -> bool { + refused() + .lock() + .is_ok_and(|set| set.contains(&(webview as usize))) +} \ No newline at end of file diff --git a/packages/tauri-app/vendor/wry-0.57.1/src/wkwebview/mod.rs b/packages/tauri-app/vendor/wry-0.57.1/src/wkwebview/mod.rs index 9b1db532b4..00cd68eac7 100644 --- a/packages/tauri-app/vendor/wry-0.57.1/src/wkwebview/mod.rs +++ b/packages/tauri-app/vendor/wry-0.57.1/src/wkwebview/mod.rs @@ -4,6 +4,8 @@ mod download; #[cfg(target_os = "macos")] +pub(crate) mod file_panels; +#[cfg(target_os = "macos")] mod drag_drop; mod navigation; #[cfg(feature = "mac-proxy")] diff --git a/packages/ui/package.json b/packages/ui/package.json index 2276d9ff98..b05f44b3ec 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -1,6 +1,6 @@ { "name": "@codenomad/ui", - "version": "1.1.0", + "version": "1.2.0", "private": true, "license": "MIT", "type": "module", @@ -18,7 +18,7 @@ "@kobalte/core": "0.13.11", "@mermaid-js/tiny": "12.3.0", "@noble/hashes": "2.4.0", - "@opencode/client": "2.3.0", + "@opencode/client": "2.4.2", "@solidjs/router": "^0.13.0", "@suid/material": "^0.19.0", "@suid/system": "^0.14.0", diff --git a/packages/ui/src/App.tsx b/packages/ui/src/App.tsx index 52cf8d5895..19682198d1 100644 --- a/packages/ui/src/App.tsx +++ b/packages/ui/src/App.tsx @@ -6,17 +6,19 @@ import { Minimize2 } from "lucide-solid" import AlertDialog from "./components/alert-dialog" import AuthRecoveryDialog from "./components/auth-recovery-dialog" import FolderSelectionView from "./components/folder-selection-view" +import { selectRemoteServer } from "./stores/remote-project-open" +import { normalizeServerSelection, sameServerSelection } from "./lib/native/server-selection-intent" +import { serversManageable } from "./lib/server-meta" import NewInstanceLauncher from "./components/new-instance-launcher" import { useDesktopFolderLaunch } from "./lib/hooks/use-electron-folder-launch" import { useDesktopConnectionLaunch } from "./lib/hooks/use-desktop-connection-launch" -import { installKeyboardOffset } from "./lib/keyboard-offset" -import { closeTemporaryInstance, openTemporaryInstance } from "./stores/temporary-instances" +import { AppViewport } from "./components/app-viewport" +import { openTemporaryInstance } from "./stores/temporary-instances" import InstanceTabs from "./components/instance-tabs" import InstanceDisconnectedModal from "./components/instance-disconnected-modal" import InstanceShell from "./components/instance/instance-shell2" import { SettingsScreen } from "./components/settings-screen" import { NativeTitlebar, hasNativeTitlebar } from "./components/native-titlebar" -import { SideCarPickerDialog } from "./components/sidecar-picker-dialog" import { SideCarView } from "./components/sidecar-view" import { InstanceMetadataProvider } from "./lib/contexts/instance-metadata-context" import { showAlertDialog } from "./stores/alerts" @@ -27,7 +29,7 @@ import { useCommands } from "./lib/hooks/use-commands" import { useAppLifecycle } from "./lib/hooks/use-app-lifecycle" import { useAppSessionRestore } from "./lib/hooks/use-app-session-restore" import { loadedRestorableSession } from "./stores/client-state" -import { shouldShowAppHomeOverlay, shouldShowAppRestoreLoading } from "./stores/app-session-restore-gate" +import { appSessionRestoreGateActive } from "./stores/app-session-restore-gate" import { getLogger } from "./lib/logger" import { launchError, showLaunchError, clearLaunchError } from "./stores/launch-errors" import OpenCodeSetup from "./components/opencode-setup" @@ -40,25 +42,31 @@ import { listenMenuActions } from "./lib/native/menu-actions" import { useI18n } from "./lib/i18n" import { setWakeLockDesired } from "./lib/native/wake-lock" import { startNotificationIconBadge } from "./lib/notification-icon-badge" +import RemoteRestoreView from "./components/remote-restore-view" import { claimNativeBrowserOpen, + changeBrowserPreviewOwnership, + onBrowserPreviewOwnership, onNativeBrowserOpen, releaseNativeBrowserOpen, + selectBrowserOpenOwner, + type BrowserOpenDiscovery, + type BrowserOpenRequest, } from "./lib/native/browser" import { useViewMenu } from "./lib/native/view-menu" import { isSelectingFolder, setIsSelectingFolder, - showFolderSelection, - setShowFolderSelection, } from "./stores/ui" -import { recentFolders, useConfig } from "./stores/preferences" +import { preferencesForBackend, recentFolders, useConfig } from "./stores/preferences" import { createInstance, + WorkspaceCreationDeparture, instances, disconnectedInstance, acknowledgeDisconnectedInstance, reconcilePendingSessionIndicators, + needsPendingRequestLiveness, reconcilePendingRequestLiveness, refreshVolatileInstanceState, syncLoadedSessionInboxes, @@ -70,15 +78,17 @@ import { activeSessionId, clearSelectedSession, fetchSessions, + hydrateRestoredSessionChain, loadMessages, setActiveSessionFromList, startNewSession, updateSessionAgent, updateSessionModel, } from "./stores/sessions" -import { openSessionPreview } from "./stores/session-previews" +import { acceptPreviewOwnership, openSessionPreview, settleSessionPreviewOpen, showSessionPreview } from "./stores/session-previews" +import { isInstanceOccurrenceOpen } from "./stores/instance-lifecycle-authority" import { SessionPreviewHost } from "./components/session-preview-view" -import { beginGesture } from "./stores/session-surface" +import { observeSurfaceGesture } from "./stores/session-surface" import { useForegroundRefresh } from "./lib/hooks/use-foreground-refresh" import { messagesLoaded, invalidateSessionMessageLoad } from "./stores/session-state" @@ -86,21 +96,24 @@ import { hasWakeLockEligibleWork, getSessionStatus } from "./stores/session-stat import { shouldAppHoldWakeLock } from "./stores/wake-lock-eligibility" import { openSettings } from "./stores/settings-screen" import { showCommandPalette } from "./stores/command-palette" -import { - closeSidecarTab, - ensureSidecarsLoaded, - openSidecarTab, -} from "./stores/sidecars" +import { openSidecarTab } from "./stores/sidecars" +import { closeAppTab } from "./stores/app-tab-close" +import { parseInstanceKey, backendIdOf } from "./lib/backend-identity" +import { captureBackendOperation } from "./lib/backend-operation" import { activeAppTab, activeAppTabId, + allowsAutomaticLocalSetup, + appTabSelectionRevision, appTabs, - closeInstanceTab, + activeBlankTabId, + closeBlankTab, + openBlankTab, + replaceBlankTab, + getInstanceAppTabId, + getSidecarAppTabId, detachInstanceTab, ensureActiveAppTab, - getAdjacentAppTabId, - getAppTabById, - markAppTabUserInteraction, moveAppTab, selectAppTab, selectInstanceTab, @@ -113,12 +126,17 @@ async function withForegroundRefreshTimeout( promise: Promise, label: string, onTimeout?: () => void, + signal?: AbortSignal, ): Promise { let timer: ReturnType | undefined + let abort = () => {} try { return await Promise.race([ promise, new Promise((_, reject) => { + abort = () => { onTimeout?.(); reject(signal?.reason) } + signal?.addEventListener("abort", abort, { once: true }) + if (signal?.aborted) { abort(); return } timer = setTimeout(() => { onTimeout?.() reject(new Error(`${label} timed out`)) @@ -127,10 +145,29 @@ async function withForegroundRefreshTimeout( ]) } finally { if (timer !== undefined) clearTimeout(timer) + signal?.removeEventListener("abort", abort) } } const App: Component = () => { + onMount(() => { + window.__CODENOMAD_SELECT_SERVER__ = (intent, action) => { + if (action !== "remove") return selectRemoteServer(intent) + const target = normalizeServerSelection(intent) + const host = preferencesForBackend("local") + const relay = host.preferences().multiBackend + const current = () => relay === host.preferences().multiBackend && (relay !== true || serversManageable()) + if (!target || !current() || !host.remoteServers().some(profile => sameServerSelection(target, profile))) { + throw new Error("Server selection changed") + } + void host.removeRemoteServerProfile(target.id, current).catch(error => { + if (error?.name !== "AbortError") showAlertDialog(t("settings.preferenceSaveFailed"), { + title: t("folderSelection.servers.remove"), variant: "warning", + }) + }) + } + onCleanup(() => { delete window.__CODENOMAD_SELECT_SERVER__ }) + }) onMount(() => onCleanup(startNotificationIconBadge())) useAppSessionRestore() const { t } = useI18n() @@ -152,7 +189,6 @@ const App: Component = () => { } = useConfig() const [escapeInDebounce, setEscapeInDebounce] = createSignal(false) const [instanceTabBarHeight, setInstanceTabBarHeight] = createSignal(0) - const [sidecarPickerOpen, setSidecarPickerOpen] = createSignal(false) const phoneQuery = useMediaQuery("(max-width: 767px)") const isPhoneLayout = createMemo(() => phoneQuery()) @@ -206,12 +242,6 @@ const App: Component = () => { onCleanup(() => document.removeEventListener("fullscreenchange", syncBrowserFullscreenState)) }) - onMount(() => { - if (typeof window === "undefined") return - // On-screen keyboard inset, limited to touch devices editing text. - onCleanup(installKeyboardOffset(window)) - }) - // If the user exits browser fullscreen via browser UI, restore chrome. let lastBrowserFullscreen = false createEffect(() => { @@ -250,78 +280,134 @@ const App: Component = () => { onMount(() => { let disposed = false let browserOpenUnsubscribe = () => {} + let browserOwnershipUnsubscribe = () => {} + const browserDeliveries = new Map() void initGithubStars() updateInstanceTabBarHeight() const handleResize = () => updateInstanceTabBarHeight() window.addEventListener("resize", handleResize) const livenessTimer = window.setInterval(() => { + const hidden = typeof document !== "undefined" && document.visibilityState === "hidden" for (const instance of instances().values()) { - if (instance.status === "ready" && instance.client) void reconcilePendingRequestLiveness(instance.id).catch((error) => { - log.warn("Failed to reconcile pending request liveness", { instanceId: instance.id, error }) - }) + if (instance.status === "ready" && instance.client && needsPendingRequestLiveness(instance.id, hidden)) { + void reconcilePendingRequestLiveness(instance.id).catch((error) => { + log.warn("Failed to reconcile pending request liveness", { instanceId: instance.id, error }) + }) + } } }, 30_000) - const openRequestedPreview = async (sessionID: string, url: string, requestID: string) => { - const findOwners = () => appTabs().flatMap(tab => tab.kind === "instance" - && getSessions(tab.instance.id).some(session => session.id === sessionID) ? [tab.instance] : []) - let owners = findOwners() - if (owners.length === 0) { - await Promise.all([...instances().values()].filter((instance) => instance.client).map((instance) => fetchSessions(instance.id, { reset: true }).catch(() => undefined))) - owners = findOwners() + const localInstances = () => appTabs().flatMap(tab => tab.kind === "instance" + && parseInstanceKey(tab.instance.id).backendId === "local" && isInstanceOccurrenceOpen(tab.instance.id) + && tab.instance.status === "ready" && tab.instance.client ? [tab.instance] : []) + const recentTabs = new Map() + let lastUsedTab: string | undefined, lastUsedSession: string | undefined + const reportTabUse = () => { + if (lastUsedTab && lastUsedSession) { + void changeBrowserPreviewOwnership({ action: "used", instanceId: lastUsedTab, sessionId: lastUsedSession })?.catch(() => {}) } + } + window.addEventListener("focus", reportTabUse) + createEffect(() => { + const tab = activeAppTab() + const id = tab?.kind === "instance" && parseInstanceKey(tab.instance.id).backendId === "local" ? tab.instance.id : undefined + const session = id ? activeSessionId().get(id) : undefined + if (id && session && session !== "info") { + const previous = recentTabs.get(session) ?? [] + recentTabs.delete(session) + recentTabs.set(session, [id, ...previous.filter(other => other !== id)].slice(0, 32)) + if (recentTabs.size > 512) recentTabs.delete(recentTabs.keys().next().value!) + if (lastUsedTab !== id || lastUsedSession !== session) { + lastUsedTab = id + lastUsedSession = session + if (document.hasFocus()) reportTabUse() + } + } else { lastUsedTab = lastUsedSession = undefined } + }) + const discoverPreviewOwner = ({ workspaceIDs, requestID, sessionID }: BrowserOpenDiscovery) => { + if (disposed) return + const eligible = new Set(workspaceIDs) + const owners = localInstances().filter(instance => eligible.has(parseInstanceKey(instance.id).workspaceId)) const activeTab = activeAppTab() - const owner = owners.find(instance => activeTab?.kind === "instance" && instance.id === activeTab.instance.id) ?? owners[0] - if (disposed || !owner) { - if (!disposed) log.warn("Failed to route agent-requested web preview", { - sessionID, - owners: owners.map((instance) => instance.id), - activeInstanceID: activeTab?.kind === "instance" ? activeTab.instance.id : undefined, - }) - return - } - const intent = beginGesture({ instanceId: owner.id, sessionId: sessionID }) + const recent = recentTabs.get(sessionID)?.find(id => owners.some(owner => owner.id === id)) + const owner = selectBrowserOpenOwner(owners, recent ?? (activeTab?.kind === "instance" ? activeTab.instance.id : undefined)) + return claimNativeBrowserOpen(requestID, { kind: "discover", instanceId: owner?.id ?? owners[0]?.id ?? null }) + } + const openRequestedPreview = async ({ sessionID, url, requestID, instanceId }: BrowserOpenRequest) => { + const eligible = () => !disposed && localInstances().some(instance => instance.id === instanceId) + const delivery = new AbortController() + let published = false try { - if (!await claimNativeBrowserOpen(requestID)) return - const instance = owner - const stillOwned = () => !disposed && findOwners().some(candidate => candidate.id === instance.id) - await openSessionPreview(sessionID, url, instance.id, async () => stillOwned() && await claimNativeBrowserOpen(requestID) && stillOwned(), intent) - if (!stillOwned() || !intent.current()) { - await releaseNativeBrowserOpen(requestID) - return + if (!eligible()) return + browserDeliveries.set(requestID, delivery) + const operation = captureBackendOperation(instanceId, undefined, eligible) + const intent = observeSurfaceGesture({ instanceId, sessionId: sessionID }) + const selectionRevision = appTabSelectionRevision() + const loaded = () => getSessions(instanceId).some(session => session.id === sessionID) + const current = () => operation.current() && intent.current() && !delivery.signal.aborted + if (!loaded()) await hydrateRestoredSessionChain(instanceId, [sessionID], operation.signal, current) + if (!current() || !loaded()) return + await openSessionPreview(sessionID, url, instanceId, intent, { requestID, instanceId }, delivery.signal, () => + changeBrowserPreviewOwnership({ action: "ready", sessionId: sessionID, instanceId, requestID })) + if (!current()) return + if (appTabSelectionRevision() === selectionRevision) { + selectInstanceTab(instanceId) + setActiveSessionFromList(instanceId, sessionID, intent) } - setShowFolderSelection(false) - selectInstanceTab(instance.id) - setActiveSessionFromList(instance.id, sessionID, intent) - } catch (error) { - await releaseNativeBrowserOpen(requestID).catch((releaseError) => { + published = true + } finally { + browserDeliveries.delete(requestID) + if (!published) await releaseNativeBrowserOpen(requestID).catch((releaseError) => { log.warn("Failed to release agent-requested web preview", { sessionID, releaseError }) }) - throw error } } - void onNativeBrowserOpen(({ sessionID, url, requestID }) => { - void openRequestedPreview(sessionID, url, requestID).catch((error) => log.warn("Failed to open agent-requested web preview", { sessionID, error })) + void onNativeBrowserOpen((request) => { + void discoverPreviewOwner(request)?.catch(error => log.warn("Failed to discover the owning preview tab", { error })) + }, (request) => { + void openRequestedPreview(request).catch(error => log.warn("Failed to open agent-requested web preview", { sessionID: request.sessionID, error })) + }, ({ requestID, sessionID, instanceId, committedUrl, keepGuest, successorUrl }) => { + browserDeliveries.get(requestID)?.abort() + settleSessionPreviewOpen(sessionID, instanceId, requestID, committedUrl, keepGuest, successorUrl) }).then((cleanup) => { if (disposed) cleanup() else browserOpenUnsubscribe = cleanup }).catch((error) => log.warn("Failed to listen for native browser open requests", { error })) + void onBrowserPreviewOwnership(acceptPreviewOwnership, ({ sessionId, instanceId }) => { + if (!localInstances().some(instance => instance.id === instanceId)) return + selectInstanceTab(instanceId) + setActiveSessionFromList(instanceId, sessionId) + showSessionPreview(sessionId, instanceId) + }).then(cleanup => { + if (disposed) cleanup() + else browserOwnershipUnsubscribe = cleanup + }).catch(error => log.warn("Failed to listen for browser ownership changes", { error })) onCleanup(() => { disposed = true browserOpenUnsubscribe() + browserOwnershipUnsubscribe() + window.removeEventListener("focus", reportTabUse) window.removeEventListener("resize", handleResize) window.clearInterval(livenessTimer) }) }) createEffect(() => { - appTabs() - ensureActiveAppTab() + if (appSessionRestoreGateActive()) return + if (appTabs().length === 0) openBlankTab() + else ensureActiveAppTab() }) const activeInstance = createMemo(() => { const tab = activeAppTab() return tab?.kind === "instance" ? tab.instance : null }) + const automaticLocalSetup = () => { + const tab = activeAppTab() + if (tab) return allowsAutomaticLocalSetup(tab) + const saved = loadedRestorableSession() + const selected = saved?.tabs[saved.activeTabIndex] + return selected?.kind !== "workspace" || backendIdOf(selected) === "local" + } const activeSessionIdForInstance = createMemo(() => { const instance = activeInstance() if (!instance) return null @@ -329,9 +415,9 @@ const App: Component = () => { }) useForegroundRefresh({ - onRefresh: async () => { - // The SSE transport is global: a reconnect can mean missed events for - // EVERY loaded workspace/session, not just the one on screen. So we: + onRefresh: async (backendId, signal) => { + signal.throwIfAborted() + // A reconnect reconciles every loaded workspace/session of its backend: // 1. Re-fetch the session list for every instance (status/titles). // 2. Force-reload whatever session is active AFTER the fetch settles // (so a session switch during the await still lands on the right @@ -340,10 +426,11 @@ const App: Component = () => { // re-fetches lazily on next activation instead of returning stale // content (a non-forced load short-circuits once "loaded"). const instanceIds = Array.from(instances().values()) - .filter((instance) => instance.status === "ready" && Boolean(instance.client)) + .filter((instance) => backendIdOf(instance) === backendId && instance.status === "ready" && Boolean(instance.client)) .map((instance) => instance.id) const sessionListResults = await Promise.allSettled( instanceIds.map((id) => { + signal.throwIfAborted() let invalidateSessions = () => {} let invalidatePendingRequests = () => {} return withForegroundRefreshTimeout( @@ -351,18 +438,21 @@ const App: Component = () => { let sessionError: unknown try { await fetchSessions(id, { + signal, strictStatus: true, registerInvalidation: (invalidate) => { invalidateSessions = invalidate }, }) } catch (error) { sessionError = error } + signal.throwIfAborted() await Promise.all([ - reloadWorktrees(id), - syncPendingRequests(id, (invalidate) => { invalidatePendingRequests = invalidate }), - refreshVolatileInstanceState(id), - syncLoadedSessionInboxes(id), + reloadWorktrees(id, false, signal), + syncPendingRequests(id, (invalidate) => { invalidatePendingRequests = invalidate }, undefined, signal), + refreshVolatileInstanceState(id, undefined, signal), + syncLoadedSessionInboxes(id, signal), ]) + signal.throwIfAborted() if (sessionError) throw sessionError })(), `Foreground refresh for ${id}`, @@ -370,11 +460,14 @@ const App: Component = () => { invalidateSessions() invalidatePendingRequests() }, + signal, ) }), ) + signal.throwIfAborted() const failedInstanceIds: string[] = [] sessionListResults.forEach((result, i) => { + signal.throwIfAborted() reconcilePendingSessionIndicators(instanceIds[i]) if (result.status === "rejected") { failedInstanceIds.push(instanceIds[i]) @@ -385,14 +478,17 @@ const App: Component = () => { const activeInst = activeInstance() const activeSession = activeSessionIdForInstance() const hasActive = Boolean( - activeInst?.status === "ready" && activeInst.client && activeSession && activeSession !== "info", + activeInst?.status === "ready" && backendIdOf(activeInst) === backendId && activeInst.client && activeSession && activeSession !== "info", ) const canReloadActive = hasActive && !failedInstanceIds.includes(activeInst!.id) // Invalidate every loaded session except the active one (force-reloaded // below). Snapshot the map first; invalidate mutates it via setState. for (const [instId, sessionSet] of messagesLoaded().entries()) { + signal.throwIfAborted() + if (parseInstanceKey(instId).backendId !== backendId) continue for (const sId of sessionSet) { + signal.throwIfAborted() if (canReloadActive && instId === activeInst!.id && sId === activeSession) continue invalidateSessionMessageLoad(instId, sId) } @@ -400,18 +496,22 @@ const App: Component = () => { let activeReloadFailed = false if (canReloadActive) { + signal.throwIfAborted() const statusBefore = getSessionStatus(activeInst!.id, activeSession!) try { let invalidateMessages = () => {} await withForegroundRefreshTimeout( loadMessages(activeInst!.id, activeSession!, { + signal, force: true, registerInvalidation: (invalidate) => { invalidateMessages = invalidate }, }), `Active-session refresh for ${activeInst!.id}:${activeSession!}`, () => invalidateMessages(), + signal, ) } catch (error) { + signal.throwIfAborted() activeReloadFailed = true log.error("Foreground refresh: active session reload failed", { instanceId: activeInst!.id, @@ -419,6 +519,7 @@ const App: Component = () => { error, }) } + signal.throwIfAborted() const statusAfter = getSessionStatus(activeInst!.id, activeSession!) log.info("Foreground refresh: active session reloaded", { instanceId: activeInst!.id, @@ -457,7 +558,7 @@ const App: Component = () => { return recent?.projectName?.trim() || getPathBasename(folderPath) } - async function handleSelectFolder(folderPath: string): Promise { + async function handleSelectFolder(folderPath: string, blankId: string | null | undefined = activeBlankTabId()): Promise { if (!folderPath) { return false } @@ -472,13 +573,13 @@ const App: Component = () => { recordWorkspaceLaunch(instances().get(result.instanceId)?.folder ?? folderPath, folderPath) if (result.reused) { selectInstanceTab(result.instanceId) - setShowFolderSelection(false) + replaceBlankTab(blankId ?? undefined, getInstanceAppTabId(result.instanceId)) log.info("Selected reused instance", { instanceId: result.instanceId, folderPath }) return true } selectInstanceTab(result.instanceId) - setShowFolderSelection(false) + replaceBlankTab(blankId ?? undefined, getInstanceAppTabId(result.instanceId)) log.info("Created instance", { instanceId: result.instanceId, @@ -486,6 +587,7 @@ const App: Component = () => { }) return true } catch (error) { + if (error instanceof WorkspaceCreationDeparture) return false const message = formatLaunchErrorMessage( error, t("app.launchError.fallbackMessage"), @@ -494,7 +596,7 @@ const App: Component = () => { ) const missingBinary = isMissingBinaryMessage(message) if (missingBinary || message.includes("opencode_update_required")) { - openOpenCodeSetup(() => handleSelectFolder(folderPath)) + openOpenCodeSetup(() => handleSelectFolder(folderPath, blankId)) return false } showLaunchError({ source: "create", message, binaryPath: selectedBinary, missingBinary }) @@ -508,13 +610,15 @@ const App: Component = () => { useDesktopFolderLaunch(handleSelectFolder) useDesktopConnectionLaunch() - async function handleNewTemporaryInstance(): Promise { + async function handleNewTemporaryInstance(blankId: string | null | undefined = activeBlankTabId()): Promise { clearLaunchError() setIsSelectingFolder(true) try { - selectInstanceTab(await openTemporaryInstance()) - setShowFolderSelection(false) + const id = await openTemporaryInstance() + selectInstanceTab(id) + replaceBlankTab(blankId ?? undefined, getInstanceAppTabId(id)) } catch (error) { + if (error instanceof WorkspaceCreationDeparture) return const message = formatLaunchErrorMessage( error, t("app.launchError.fallbackMessage"), @@ -523,7 +627,7 @@ const App: Component = () => { ) const missingBinary = isMissingBinaryMessage(message) if (missingBinary || message.includes("opencode_update_required")) { - openOpenCodeSetup(() => handleNewTemporaryInstance()) + openOpenCodeSetup(() => handleNewTemporaryInstance(blankId)) return } showLaunchError({ source: "create", message, binaryPath: serverSettings().opencodeBinary || "opencode2", missingBinary }) @@ -533,12 +637,13 @@ const App: Component = () => { } } - function handleSelectExistingInstance(instanceId: string, recentPath: string) { - const instance = instances().get(instanceId) - if (!instance) return + function handleSelectExistingInstance(instanceId: string, recentPath: string, blankId: string | null | undefined = activeBlankTabId()) { + const tab = appTabs().find(tab => tab.kind === "instance" && tab.instance.id === instanceId) + if (tab?.kind !== "instance") return + const { instance } = tab recordWorkspaceLaunch(instance.folder, recentPath) selectInstanceTab(instanceId) - setShowFolderSelection(false) + if (blankId) closeBlankTab(blankId) log.info("Selected existing instance", { instanceId, folderPath: instance.folder }) } @@ -552,27 +657,21 @@ const App: Component = () => { } function handleNewInstanceRequest() { - setShowFolderSelection(true) + openBlankTab() } const [launcherOpen, setLauncherOpen] = createSignal(false) const [launcherAnchor, setLauncherAnchor] = createSignal() - // The launcher is anchored to the tab bar: the home page or a closed tab bar retires it. createEffect(() => { - if (showFolderSelection() || appTabs().length === 0) setLauncherOpen(false) + if (mobileFullscreenMode()) setLauncherOpen(false) }) - function handleOpenSidecarPicker() { - setSidecarPickerOpen(true) - void ensureSidecarsLoaded() - } - - async function handleOpenSidecar(sidecarId: string) { + async function handleOpenSidecar(sidecarId: string, blankId: string | null | undefined = activeBlankTabId()) { try { const tab = await openSidecarTab(sidecarId) selectSidecarTab(tab.token) - setShowFolderSelection(false) - setSidecarPickerOpen(false) + replaceBlankTab(blankId ?? undefined, getSidecarAppTabId(tab.token)) + preferencesForBackend("local").recordSidecarRecent(sidecarId) } catch (error) { const message = error instanceof Error ? error.message : String(error) showAlertDialog(message, { @@ -617,30 +716,6 @@ const App: Component = () => { } } - async function handleCloseAppTab(tabId: string) { - const tab = getAppTabById(tabId) - if (!tab) return - markAppTabUserInteraction() - - const fallbackTabId = activeAppTabId() === tabId ? getAdjacentAppTabId(tabId) : activeAppTabId() - - if (tab.kind === "instance" && tab.instance.temporary) { - // Asks to keep or discard unless untouched; a refused discard restores the tab. - await closeTemporaryInstance(tab.instance.id) - return - } - - if (tab.kind === "instance") { - closeInstanceTab(tab.instance.id) - } else { - closeSidecarTab(tab.sidecarTab.token) - } - - if (!getAppTabById(tabId)) { - ensureActiveAppTab(fallbackTabId) - } - } - const handleSidebarAgentChange = async (instanceId: string, sessionId: string, agent: string) => { if (!instanceId || !sessionId || sessionId === "info") return await updateSessionAgent(instanceId, sessionId, agent) @@ -669,7 +744,7 @@ const App: Component = () => { setToolInputsVisibility, handleNewInstanceRequest, handleNewTemporaryInstance: () => handleNewTemporaryInstance(), - handleCloseActiveTab: () => handleCloseAppTab(activeAppTabId() ?? ""), + handleCloseActiveTab: () => closeAppTab(activeAppTabId() ?? ""), handleNewSession, handleCloseSession, getActiveInstance: activeInstance, @@ -681,11 +756,9 @@ const App: Component = () => { executeCommand, setEscapeInDebounce, handleNewInstanceRequest, - handleCloseActiveTab: () => handleCloseAppTab(activeAppTabId() ?? ""), + handleCloseActiveTab: () => closeAppTab(activeAppTabId() ?? ""), handleNewSession, handleCloseSession, - showFolderSelection, - setShowFolderSelection, getActiveInstance: activeInstance, getActiveSessionIdForInstance: activeSessionIdForInstance, }) @@ -695,7 +768,7 @@ const App: Component = () => { onMount(() => { onCleanup(observeDesktopUpdates()) const executeMenuAction = (action: unknown) => { - if (typeof action !== "string") return + if (typeof action !== "string" || document.documentElement.inert) return if (action === "get-updates") { void requestDesktopUpdate(); return } if (executeViewMenuAction(action)) return if (action === "open-command-palette") { @@ -711,7 +784,7 @@ const App: Component = () => { return ( <> - + { -
+ - +
@@ -779,99 +852,81 @@ const App: Component = () => {
0} fallback={ - <> - - void handleCloseAppTab(tabId)} - onNew={handleNewInstanceRequest} - onOpenLauncher={(anchor) => { - // The home page already offers everything; a hidden tab bar must not reopen it. - if (showFolderSelection()) return - setLauncherAnchor(anchor) - setLauncherOpen(true) - }} - launcherOpen={launcherOpen()} - onMoveTab={moveAppTab} - /> - - - - {(tab) => { - const isVisible = () => activeAppTabId() === tab.id && !showFolderSelection() - return tab.kind === "instance" ? ( -
- - handleCloseSession(tab.instance.id, sessionId)} - onNewSession={() => handleNewSession(tab.instance.id)} - handleSidebarAgentChange={(sessionId, agent) => handleSidebarAgentChange(tab.instance.id, sessionId, agent)} - handleSidebarModelChange={(sessionId, model) => handleSidebarModelChange(tab.instance.id, sessionId, model)} - onExecuteCommand={executeCommand} - tabBarOffset={mobileFullscreenMode() ? 0 : instanceTabBarHeight()} - mobileFullscreenMode={mobileFullscreenMode()} - onEnterMobileFullscreen={() => void enterMobileFullscreen()} - onExitMobileFullscreen={() => void exitMobileFullscreen()} - /> - -
- ) : ( -
- -
- ) - }} -
- - +
+ } > - void handleNewTemporaryInstance()} - isLoading={isSelectingFolder() || shouldShowAppRestoreLoading(loadedRestorableSession())} - onOpenSidecar={handleOpenSidecarPicker} - /> - - - -
-
- void handleNewTemporaryInstance()} - isLoading={isSelectingFolder()} - onOpenSidecar={handleOpenSidecarPicker} - onClose={() => { - setShowFolderSelection(false) - clearLaunchError() - }} - /> -
-
+ + void closeAppTab(tabId)} + onNew={handleNewInstanceRequest} + onOpenLauncher={(anchor) => { + setLauncherAnchor(anchor) + setLauncherOpen(true) + }} + launcherOpen={launcherOpen()} + onMoveTab={moveAppTab} + /> + + + + {(tab) => { + const isVisible = () => activeAppTabId() === tab.id + return tab.kind === "instance" ? ( +
+ + handleCloseSession(tab.instance.id, sessionId)} + onNewSession={() => handleNewSession(tab.instance.id)} + handleSidebarAgentChange={(sessionId, agent) => handleSidebarAgentChange(tab.instance.id, sessionId, agent)} + handleSidebarModelChange={(sessionId, model) => handleSidebarModelChange(tab.instance.id, sessionId, model)} + onExecuteCommand={executeCommand} + tabBarOffset={mobileFullscreenMode() ? 0 : instanceTabBarHeight()} + mobileFullscreenMode={mobileFullscreenMode()} + onEnterMobileFullscreen={() => void enterMobileFullscreen()} + onExitMobileFullscreen={() => void exitMobileFullscreen()} + /> + +
+ ) : ( +
+ {tab.kind === "sidecar" ? : tab.kind === "remote-restore" ? : + void handleSelectFolder(path, tab.id)} + onSelectExistingInstance={(id, path) => handleSelectExistingInstance(id, path, tab.id)} + onNewTemporaryInstance={() => void handleNewTemporaryInstance(tab.id)} + onOpenSidecar={id => void handleOpenSidecar(id, tab.id)} + onJoined={() => closeBlankTab(tab.id)} + onRemoteOpened={id => replaceBlankTab(tab.id, getInstanceAppTabId(id))} />} +
+ ) + }} +
{ anchor={launcherAnchor()} isLoading={isSelectingFolder()} onOpenChange={setLauncherOpen} - onSelectFolder={(path) => void handleSelectFolder(path)} - onSelectExistingInstance={handleSelectExistingInstance} - onNewTemporaryInstance={() => void handleNewTemporaryInstance()} + onSelectFolder={(path) => void handleSelectFolder(path, null)} + onSelectExistingInstance={(id, path) => handleSelectExistingInstance(id, path, null)} + onNewTemporary={() => void handleNewTemporaryInstance(null)} + onOpenSidecar={id => void handleOpenSidecar(id, null)} /> - setSidecarPickerOpen(false)} onOpenSidecar={handleOpenSidecar} /> @@ -897,7 +952,7 @@ const App: Component = () => { className: "bg-transparent border-none shadow-none p-0", }} /> -
+
) } diff --git a/packages/ui/src/components/action-overflow-menu.tsx b/packages/ui/src/components/action-overflow-menu.tsx index fad541fea1..cdd2143884 100644 --- a/packages/ui/src/components/action-overflow-menu.tsx +++ b/packages/ui/src/components/action-overflow-menu.tsx @@ -1,5 +1,5 @@ import { DropdownMenu } from "@kobalte/core/dropdown-menu" -import { For, Show, createSignal, onCleanup, type JSXElement } from "solid-js" +import { For, Show, createMemo, createSignal, onCleanup, type JSXElement } from "solid-js" import { MoreHorizontal } from "lucide-solid" import { suppressCompatibilityClick } from "../lib/compatibility-click" @@ -10,6 +10,10 @@ export interface ActionOverflowMenuItem { icon?: JSXElement disabled?: boolean checked?: boolean + /** Use for actions that need the current user gesture rather than menu focus restoration. */ + selectBeforeClose?: boolean + /** Focus target of a window opened in the selection gesture. */ + focusAfterSelect?: () => HTMLElement | undefined onSelect: () => void | Promise onMouseEnter?: () => void onMouseLeave?: () => void @@ -21,12 +25,16 @@ interface ActionOverflowMenuProps { triggerClass?: string minItems?: number onOpenChange?: (open: boolean) => void + onFocusRestored?: () => void } export default function ActionOverflowMenu(props: ActionOverflowMenuProps) { let selectedAction: ActionOverflowMenuItem["onSelect"] | undefined + let gestureFocus: ActionOverflowMenuItem["focusAfterSelect"] + let trigger: HTMLButtonElement | undefined let pointerType: string | undefined const [hoveredItem, setHoveredItem] = createSignal(null) + const itemsByKey = createMemo(() => new Map(props.items.map(item => [item.key, item]))) const enabledItems = () => props.items.filter((item) => !item.disabled) const hasItems = () => props.items.length >= (props.minItems ?? 1) const clearHoveredItem = () => { @@ -45,6 +53,7 @@ export default function ActionOverflowMenu(props: ActionOverflowMenuProps) { props.onOpenChange?.(open) }}> { trigger = element }} class={`action-overflow-trigger ${props.triggerClass ?? ""}`.trim()} aria-label={props.label} title={props.label} @@ -54,51 +63,75 @@ export default function ActionOverflowMenu(props: ActionOverflowMenuProps) { - { + { + const active = document.activeElement + const button = trigger + const target = gestureFocus?.() + gestureFocus = undefined + if (target?.isConnected && button && !button.inert) { + // Kobalte focuses the trigger even when the autofocus event is prevented. + button.inert = true + queueMicrotask(() => { button.inert = false }) + if (!active || active === document.body || active === button || (event.currentTarget as Element)?.contains(active)) { + target.focus({ preventScroll: true }) + } + } // Kobalte restores the trigger after this callback. Launch selected // actions afterwards so a newly opened window keeps its autofocus. const action = selectedAction selectedAction = undefined - if (action) queueMicrotask(() => { void action() }) + if (action || props.onFocusRestored) queueMicrotask(() => { + void action?.() + props.onFocusRestored?.() + }) }}> - - {(item) => ( - { - if (item.disabled) return - const previous = hoveredItem() - if (previous !== item) previous?.onMouseLeave?.() - setHoveredItem(item) - item.onMouseEnter?.() - }} - onPointerLeave={() => { - if (item.disabled) return - if (hoveredItem() === item) setHoveredItem(null) - item.onMouseLeave?.() - }} - // Kobalte selects on pointerup; record it for the selection below. - onPointerUp={(event) => { pointerType = event.pointerType }} - onKeyDown={() => { pointerType = undefined }} - onSelect={() => { - clearHoveredItem() - selectedAction = item.onSelect - if (pointerType && pointerType !== "mouse") suppressCompatibilityClick() - pointerType = undefined - }} - > - - {item.label} - - )} + + {(key) => { + const item = () => itemsByKey().get(key) + onCleanup(() => { if (hoveredItem()?.key === key) clearHoveredItem() }) + return ( + { + const entry = item() + if (!entry || entry.disabled) return + clearHoveredItem() + setHoveredItem(entry) + entry.onMouseEnter?.() + }} + onPointerLeave={() => { + if (hoveredItem()?.key === key) clearHoveredItem() + }} + // Kobalte selects on pointerup; record it for the selection below. + onPointerUp={(event) => { pointerType = event.pointerType }} + onKeyDown={() => { pointerType = undefined }} + onSelect={() => { + const entry = item() + clearHoveredItem() + if (pointerType && pointerType !== "mouse") suppressCompatibilityClick() + pointerType = undefined + if (!entry || entry.disabled) return + if (entry.selectBeforeClose) { + gestureFocus = entry.focusAfterSelect + void entry.onSelect() + } + else selectedAction = entry.onSelect + }} + > + + {item()?.label} + + ) + }} diff --git a/packages/ui/src/components/advanced-settings-modal.tsx b/packages/ui/src/components/advanced-settings-modal.tsx deleted file mode 100644 index 8fbdf38453..0000000000 --- a/packages/ui/src/components/advanced-settings-modal.tsx +++ /dev/null @@ -1,63 +0,0 @@ -import { Component } from "solid-js" -import { Dialog } from "@kobalte/core/dialog" -import OpenCodeBinarySelector from "./opencode-binary-selector" -import EnvironmentVariablesEditor from "./environment-variables-editor" -import { useI18n } from "../lib/i18n" - -interface AdvancedSettingsModalProps { - open: boolean - onClose: () => void - selectedBinary: string - onBinaryChange: (binary: string) => void - isLoading?: boolean -} - -const AdvancedSettingsModal: Component = (props) => { - const { t } = useI18n() - - return ( - !open && props.onClose()}> - - -
- -
- {t("advancedSettings.title")} -
- -
- - -
-
-

{t("advancedSettings.environmentVariables.title")}

-

{t("advancedSettings.environmentVariables.subtitle")}

-
-
- -
-
-
- - -
-
-
-
- ) -} - -export default AdvancedSettingsModal diff --git a/packages/ui/src/components/app-actions.tsx b/packages/ui/src/components/app-actions.tsx index 01df74b1e2..425c817732 100644 --- a/packages/ui/src/components/app-actions.tsx +++ b/packages/ui/src/components/app-actions.tsx @@ -2,16 +2,10 @@ import { Component, Show, createEffect, createSignal, onCleanup } from "solid-js import { Bell, MonitorUp, Settings } from "lucide-solid" import ToastHistoryPanel from "./toast-history-panel" import { useI18n } from "../lib/i18n" -import { canOpenRemoteWindows } from "../lib/runtime-env" import { getUnreadToastCountSignal } from "../lib/notifications" import { openSettings, toggleSettings } from "../stores/settings-screen" -interface AppActionsProps { - class: string -} - -/** Settings, the notification history bell and Remote Access: the project tab bar's end, or the macOS title bar. */ -const AppActions: Component = (props) => { +const AppActions: Component = () => { const { t } = useI18n() const [showToastHistory, setShowToastHistory] = createSignal(false) let notificationTriggerRef: HTMLButtonElement | undefined @@ -40,7 +34,7 @@ const AppActions: Component = (props) => { const unreadCount = getUnreadToastCountSignal() return ( -
+
- - - +
) } diff --git a/packages/ui/src/components/app-viewport.tsx b/packages/ui/src/components/app-viewport.tsx new file mode 100644 index 0000000000..13cefdfbd9 --- /dev/null +++ b/packages/ui/src/components/app-viewport.tsx @@ -0,0 +1,12 @@ +import { onCleanup, onMount, type ParentProps } from "solid-js" +import { installKeyboardOffset } from "../lib/keyboard-offset" + +export function AppViewport(props: ParentProps) { + onMount(() => onCleanup(installKeyboardOffset(window))) + return ( +
+ {props.children} +
+ ) +} diff --git a/packages/ui/src/components/attachment-chip.tsx b/packages/ui/src/components/attachment-chip.tsx deleted file mode 100644 index e6e4e43a7e..0000000000 --- a/packages/ui/src/components/attachment-chip.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Component } from "solid-js" -import type { Attachment } from "../types/attachment" -import { useI18n } from "../lib/i18n" - -interface AttachmentChipProps { - attachment: Attachment - onRemove: () => void -} - -const AttachmentChip: Component = (props) => { - const { t } = useI18n() - return ( -
- {props.attachment.display} - -
- ) -} - -export default AttachmentChip diff --git a/packages/ui/src/components/backend-view-indicators.test.ts b/packages/ui/src/components/backend-view-indicators.test.ts new file mode 100644 index 0000000000..eda2e23bfd --- /dev/null +++ b/packages/ui/src/components/backend-view-indicators.test.ts @@ -0,0 +1,350 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import { generateUUID } from "../lib/client-identity" +import ts from "typescript" +import { evaluateExpression, productionHandler, readSource } from "../../tests/test-support/production-ast" +import { deferred } from "../../tests/test-support/deferred" +import { isMissionPickerSource } from "./mission-scheduling-data" +import { createEffect, createMemo, createRoot, createSignal, createUniqueId, mapArray, on, onCleanup, untrack } from "solid-js" + +// Execute production AST, including the actual finally/cleanup branches. Imports +// and JSX are outside these indicator tests; request and view owners are explicit. +function bindings(scope: Record) { + scope.generateUUID ??= generateUUID + scope.backendOf ??= () => ({ api: scope.serverApi }) + return scope +} +function method(path: string, name: string, scope: Record) { + return productionHandler(new URL(path, import.meta.url), name, bindings(scope)) +} +function component(path: string, name: string, expose: string, scope: Record) { + const file = readSource(new URL(path, import.meta.url)) + const declaration = file.statements.find(node => ts.isFunctionDeclaration(node) && node.name?.text === name) as ts.FunctionDeclaration + assert.ok(declaration?.body) + const statements = declaration.body.statements.slice(0, -1).map(node => node.getText(file)).join("\n") + return evaluateExpression(`function(props) { ${statements}\nreturn ${expose} }`, bindings(scope)) +} +function effect(path: string, marker: string, scope: Record) { + return productionHandler(new URL(path, import.meta.url), "createEffect", bindings(scope), marker) +} +const flush = async () => { for (let i = 0; i < 30; i++) await Promise.resolve() } +function attachment() { + let controller = new AbortController() + const [signal, setSignal] = createSignal(controller.signal) + return { + captureBackendOperation: (_id: string, parent?: AbortSignal, owns = () => true) => { + const captured = parent ? AbortSignal.any([signal(), parent]) : signal() + return { signal: captured, current: () => !captured.aborted && owns() } + }, + revoke: () => controller.abort(), + replace: () => { controller.abort(); controller = new AbortController(); setSignal(controller.signal) }, + } +} +const solid = { createEffect, createMemo, createSignal, createUniqueId, mapArray, on, onCleanup, untrack } + +for (const outcome of ["success", "failure", "cancellation"] as const) { + for (const successor of [false, true]) { + test(`lifecycle retained refresh: ${outcome}, successor=${successor}`, async () => { + const backend = attachment(), requests: ReturnType[] = [] + let refreshing = false + const scope = { ...backend, props: { instanceId: "i", disabled: false }, alive: true, epoch: 0, + identity: () => "same-client-and-generation", active: () => true, busy: () => refreshing, + setRefreshing: (value: boolean) => { refreshing = value }, + missionStore: { refresh: () => { const request = deferred(); requests.push(request); return request.promise } }, + } + const check = method("./mission-lifecycle-controls.tsx", "checkStatus", scope) + const first = check().catch(() => {}) + backend.revoke() + if (successor) { + // Production identity effect retires the previous epoch before a B read. + scope.epoch++; refreshing = false; backend.replace() + void check() + } + if (outcome === "success") requests[0].resolve(undefined) + else requests[0].reject(new DOMException(outcome, outcome === "cancellation" ? "AbortError" : "Error")) + await first + assert.equal(refreshing, successor) + if (successor) { requests[1].resolve(undefined); await flush(); assert.equal(refreshing, false) } + }) + } +} + +for (const outcome of ["success", "failure"] as const) { + for (const successor of [false, true]) { + test(`metadata retained load: ${outcome}, successor=${successor}`, async () => { + const backend = attachment(), requests: ReturnType[] = [] + const instance = { id: "i", client: {} } + let loading = false + const scope = { ...backend, metadataLoadId: 0, disposed: false, resolvedInstance: () => instance, + getInstanceMetadata: () => undefined, getActiveCatalogLocation: () => ({}), hasMetadataLoaded: () => false, + setIsLoading: (value: boolean) => { loading = value }, waitForInstanceInitialSessionHydration: async () => {}, + loadInstanceMetadata: () => { const request = deferred(); requests.push(request); return request.promise }, + } + const ensure = method("../lib/contexts/instance-metadata-context.tsx", "ensureMetadata", scope) + const first = ensure(true).catch(() => {}); await flush() + backend.revoke(); backend.replace() + let second: Promise | undefined + if (successor) { second = ensure(true); await flush() } + if (outcome === "success") requests[0].resolve(undefined) + else requests[0].reject(new Error("failed")) + await first + assert.equal(loading, successor) + if (second) { requests[1].resolve(undefined); await second; assert.equal(loading, false) } + }) + } +} + +for (const name of ["reload", "reconcile"] as const) { + for (const outcome of ["success", "failure", "cancellation"] as const) { + test(`editor schedule ${name}: revoked ${outcome} releases its serial read`, async () => { + const backend = attachment(), requests = [deferred(), deferred()] + let reading = false, reads = 0, writes = 0 + const hold = { payload: JSON.stringify({ missionID: "m", requestID: "r", expectedRevision: 1, objective: "objective", notes: "" }), state: "uncertain" } + const ownerValue = { signal: backend.captureBackendOperation("i").signal } + const scope = { props: { instanceId: "i", directory: "/repo", action: {}, active: () => true, scope: () => "s" }, + held: () => name === "reload" ? undefined : hold, reading: () => reading, target: "m", + capture: () => backend.captureBackendOperation("i").current, + owner: () => ownerValue, + captureOwner: (controller: AbortController) => () => !controller.signal.aborted, + reconcileRead: undefined, + setReading: (value: boolean) => { reading = value }, setFailed: () => {}, setReady: () => {}, + serverApi: { + fetchMission: () => requests[reads++].promise, + editMission: () => { writes++; return {} }, + }, + } + const run = method("./mission-editor-schedule.ts", name, scope) + const first = run() + assert.equal(reads, 1) + if (name === "reload") assert.equal(reading, true) + backend.revoke(); backend.replace() + await run() // No successor is admitted while this same view's read owns the serial slot. + assert.equal(reads, 1) + if (outcome === "success") requests[0].resolve({ available: true, mission: { id: "m", history: [] } }) + else requests[0].reject(new DOMException(outcome, outcome === "cancellation" ? "AbortError" : "Error")) + await first + assert.equal(reading, false); assert.equal(writes, 0) + const next = run() + assert.equal(reads, 2, "revoked outcome must release the serial read for subsequent reads") + requests[1].reject(new DOMException("cleanup", "AbortError")) + await next + assert.equal(reading, false); assert.equal(writes, 0) + }) + } +} + +for (const outcome of ["success", "failure", "cancellation"] as const) { + test(`editor defaults: hidden/revoked ${outcome} releases the serial flag`, async () => { + const backend = attachment(), request = deferred() + let refreshing = false, publications = 0 + const scope = { busy: () => false, defaultsRefreshing: () => refreshing, isActive: () => true, + captureView: () => backend.captureBackendOperation("i").current, + config: { reloadMissionPreferences: () => request.promise }, + setDefaultsRefreshing: (value: boolean) => { refreshing = value }, setDefaultsFailed: () => { publications++ }, + } + const run = method("./mission-editor.tsx", "useSavedDefaults", scope) + const first = run(); backend.revoke(); await run() + if (outcome === "success") request.resolve(undefined) + else request.reject(new DOMException(outcome, outcome === "cancellation" ? "AbortError" : "Error")) + await first + assert.equal(refreshing, false); assert.equal(publications, 1) // Initial reset only. + }) +} + +for (const outcome of ["success", "failure", "cancellation"] as const) { + test(`editor source retained view: ${outcome}, hidden cancellation then active B`, async () => { + const backend = attachment(), requests: ReturnType[] = [] + const [active, setActive] = createSignal(true) + const client = {}, scope = { ...solid, ...backend, isMissionPickerSource, getOpenCodeInstanceGeneration: () => 1, + getRootClient: () => client, serverApi: { fetchMissionScheduleSourcePage: () => {} } } + // Branch sources avoid loading unrelated native session/cursor adapters. + Object.assign(scope.serverApi, { fetchLocalGitBranches: () => { const request = deferred(); requests.push(request); return request.promise } }) + Object.assign(scope, { backendOf: () => ({ api: scope.serverApi }) }) + const create = method("./mission-editor-sources.ts", "createMissionEditorSources", scope) + let dispose!: () => void + const reader = createRoot(close => { dispose = close; return create({ instanceId: "i", projectID: "p", directory: () => "/repo", + kinds: () => ["branch-commits"], selected: () => [], active, captureView: () => () => active() }) }) + // Assert the fixture reaches production dispatch, rather than merely its cleanup. + reader.loading(); await new Promise(resolve => setTimeout(resolve, 0)); assert.equal(requests.length, 1) + backend.revoke(); setActive(false) + assert.equal(reader.loading(), false) + backend.replace(); setActive(true) + await new Promise(resolve => setTimeout(resolve, 0)) + assert.equal(requests.length, 2); assert.equal(reader.loading(), true) + if (outcome === "success") requests[0].resolve({ branches: [] }) + else requests[0].reject(new DOMException(outcome, outcome === "cancellation" ? "AbortError" : "Error")) + await flush(); assert.equal(reader.loading(), true) + requests[1].resolve({ branches: [] }); await flush(); assert.equal(reader.loading(), false) + dispose() + }) +} + +test("history open: revoked owner releases opening, but cannot clear a successor target", async () => { + for (const successor of [false, true]) { + const backend = attachment(), request = deferred() + let opening = false, failed = false + const scope = { ...backend, target: 0, props: { instanceId: "i", sessionId: "s", messageId: "m" }, + setOpening: (value: boolean) => { opening = value }, setOpenFailed: (value: boolean) => { failed = value }, + openHistoryMatchSession: () => request.promise, + } + const run = method("./history-message-preview.tsx", "open", scope), first = run() + backend.revoke(); backend.replace() + if (successor) scope.target++ + request.resolve(false); await first + assert.equal(opening, successor); assert.equal(failed, false) + } +}) + +test("shell polling: cancellation releases loading; old completion leaves a retained B busy", async () => { + const backend = attachment(), requests: ReturnType[] = [] + let dispose!: () => void + const create = component("./shell-output-dialog.tsx", "ShellOutputDialog", "{ loading }", { ...solid, ...backend, + useI18n: () => ({ t: (key: string) => key }), shellStore: { output: () => { const request = deferred(); requests.push(request); return request.promise } }, + }) + const reader = createRoot(close => { dispose = close; return create({ open: true, instanceId: "i", shell: { id: "s" }, directory: "/repo" }) }) + assert.equal(reader.loading(), true) + backend.replace(); assert.equal(requests.length, 2) + requests[0].reject(new DOMException("cancelled", "AbortError")); await flush() + assert.equal(reader.loading(), true) + backend.revoke(); requests[1].reject(new DOMException("cancelled", "AbortError")); await flush() + assert.equal(reader.loading(), false) + dispose() +}) + +for (const kind of ["create", "edit", "delete"] as const) { + for (const outcome of ["success", "failure", "cancellation"] as const) { + test(`editor ${kind}: revoked ${outcome} releases pending without admitting B`, async () => { + const backend = attachment(), request = deferred(), action = {} + let pending = false, dispatched = 0, errors = 0 + const dispatch = () => { dispatched++; return request.promise } + const scope = { kind, action, original: { id: "m", revision: 1 }, lastPayload: "", requestId: "r", + coordinatorReady: method("./mission-editor.tsx", "coordinatorReady", { coordinatorSessionID: () => undefined }), + props: { instanceId: "i", directory: "/repo", action, onSaved: () => { throw new Error("stale publication") } }, + locked: () => pending, isActive: () => true, setFieldError: () => {}, structuralLocked: () => true, + immediateCreationFollowed: () => false, mode: () => "immediate", textLocked: () => false, + startOnCreation: () => false, coordinatorGoal: () => false, + captureStart: () => async () => assert.fail("stale creation must not start"), + captureView: () => backend.captureBackendOperation("i").current, objective: () => "draft", notes: () => "notes", + template: () => "custom", identity: () => "view", taskMode: () => undefined, effectiveProfiles: () => undefined, watchedIDs: () => [], + submittedTitle: () => "title", selectedModel: () => undefined, deleteManagedSessions: () => false, deleteAttempted: () => false, + uncertainRecurrence: () => undefined, missionCreationHold: () => undefined, holdMissionCreation: () => true, + missionCreationPayloadIdentity: JSON.stringify, releaseMissionCreation: () => {}, retainUncertainMissionCreation: () => {}, + retainSubmittedMissionModel: () => {}, setShownRequestId: () => {}, setAdopted: () => {}, setDeleteAttempted: () => {}, + isDefinitiveCreationRejection: () => false, missionStore: { demandedInstanceIds: () => [] }, + schedule: { journal: () => ({}), saveJournalEdit: dispatch }, conversation: undefined, replaces: undefined, removeReplaced: async () => {}, + serverApi: { createMission: dispatch, deleteMission: dispatch }, + setPending: (value: boolean) => { pending = value }, setError: () => { errors++ }, + } + const save = method("./mission-editor.tsx", "save", scope) + const first = save({ preventDefault() {} }); assert.equal(pending, true) + backend.revoke(); backend.replace() + await save({ preventDefault() {} }); assert.equal(dispatched, 1) + if (outcome === "success") request.resolve({ mission: {} }) + else request.reject(new DOMException(outcome, outcome === "cancellation" ? "AbortError" : "Error")) + await first + assert.equal(pending, false); assert.equal(errors, 1) + }) + } +} + +test("history preview: cancelled old read cannot clear B; revoked B settles its flag", async () => { + const backend = attachment(), requests: ReturnType[] = [] + let dispose!: () => void + const create = component("./history-message-preview.tsx", "HistoryMessagePreview", "{ pending }", { ...solid, ...backend, + useI18n: () => ({ t: (key: string) => key }), getOpenCodeInstanceGeneration: () => 1, getOpenCodeMutationRevision: () => 0, + getRootClient: () => ({ session: { get: async () => ({ title: "session" }), message: { get: () => { + const request = deferred(); requests.push(request); return request.promise + } } } }), + }) + const reader = createRoot(close => { dispose = close; return create({ instanceId: "i", sessionId: "s", messageId: "m" }) }) + backend.replace(); assert.equal(requests.length, 2) + requests[0].resolve({ type: "user", text: "A" }); await flush(); assert.equal(reader.pending(), true) + backend.revoke(); requests[1].reject(new DOMException("cancelled", "AbortError")); await flush() + assert.equal(reader.pending(), false) + dispose() +}) + +test("skills: already revoked demand never advertises an undispatched read", () => { + const backend = attachment(); backend.revoke() + let loading = false, dispose!: () => void, dispatched = 0 + const callback = effect("./unified-picker.tsx", "skill.list", { ...solid, ...backend, + props: { open: true, workspaceId: "i", directory: "/repo" }, mode: () => "mention", + setSkills: () => {}, setSkillsError: () => {}, setSkillsLoading: (value: boolean) => { loading = value }, + getRootClient: () => { dispatched++; throw new Error("revoked dispatch") }, + serverEvents: { on: () => () => {}, forInstance: () => ({ onOpen: () => () => {} }) }, + }) + createRoot(close => { dispose = close; createEffect(callback) }) + assert.equal(loading, false); assert.equal(dispatched, 0) + dispose() +}) + +test("lifecycle: revocation during the acknowledged control's refresh releases its local flag", async () => { + const backend = attachment(), refresh = deferred(), mission = { id: "m", revision: 1 } + let refreshing = false + const scope = { ...backend, props: { instanceId: "i", mission }, alive: true, epoch: 0, attempt: 0, + identity: () => "scope", location: () => ({}), active: () => true, busy: () => refreshing, + retry: () => false, pending: () => false, full: () => false, + missionLifecycleIntents: { reserve: (_scope: string, _id: string, input: unknown) => ({ input }), start: () => true, finish: () => true }, + serverApi: { controlMission: async () => ({ mission }) }, missionLifecycleSource: () => "scope", + setRefreshing: (value: boolean) => { refreshing = value }, missionStore: { refresh: () => refresh.promise }, + } + const act = method("./mission-lifecycle-controls.tsx", "act", scope), result = act("pause") + await flush(); assert.equal(refreshing, true) + backend.revoke(); backend.replace(); refresh.resolve(undefined); await result + assert.equal(refreshing, false) +}) + +test("playbook reader: owner routing and replacement reject a detached response", async () => { + const backend = attachment(), requests: ReturnType[] = [], owners: string[] = [] + let shown: unknown, failed = false, dispose!: () => void + const callback = effect("./mission-playbook-reader.tsx", "fetchMissionPlaybooks", { ...solid, ...backend, + props: { instanceId: "remote~same", taskMode: "native" }, attempt: () => 0, + serverApi: { fetchMissionPlaybooks: () => assert.fail("local singleton reached") }, + backendOf: (id: string) => { owners.push(id); return { api: { fetchMissionPlaybooks: () => { + const request = deferred(); requests.push(request); return request.promise + } } } }, + setDetails: (value: unknown) => { shown = value }, setFailed: (value: boolean) => { failed = value }, + }) + createRoot(close => { dispose = close; createEffect(callback) }) + assert.deepEqual(owners, ["remote~same"]) + backend.replace(); assert.equal(requests.length, 2) + requests[1].resolve({ taskMode: "native", source: "replacement" }); await flush() + requests[0].resolve({ taskMode: "native", source: "detached" }); await flush() + assert.deepEqual(shown, { taskMode: "native", source: "replacement" }); assert.equal(failed, false) + backend.revoke(); backend.replace(); assert.equal(requests.length, 3) + dispose(); requests[2].reject(new Error("disposed")); await flush() + assert.equal(failed, false) +}) + +test("MissionControl refresh: detachment prevents recurrence publication and control resend", async () => { + const backend = attachment(), request = deferred() + let refreshing = false, publications = 0, resends = 0 + const retry = { reconcile: () => request.promise, pending: () => true, resend: async () => { resends++ } } + const run = method("./instance/shell/right-panel/tabs/MissionControl.tsx", "refresh", { ...backend, + props: { instanceId: "remote~same" }, refreshing: () => refreshing, controlRetry: () => retry, + captureView: () => () => true, setRefreshing: (value: boolean) => { refreshing = value }, + missionStore: { refresh: () => request.promise }, setRecurrenceRefresh: () => { publications++ }, + }) + const pending = run(); assert.equal(refreshing, true) + backend.replace(); request.resolve(true); await pending + assert.equal(publications, 0); assert.equal(resends, 0); assert.equal(refreshing, false) +}) + +test("cleanup: remote preflight detachment never advances to a destructive retry", async () => { + const backend = attachment(), request = deferred(), owners: string[] = [] + let pending = "", deletes = 0, refreshes = 0 + const saved = { missionID: "m", deletionID: "d", requestID: "r", expectedRevision: 1, deleteManagedSessions: false } + const run = method("./mission-cleanup.tsx", "retry", { ...backend, + props: { instanceId: "remote~same", active: true, disabled: false, refresh: async () => { refreshes++ } }, + pending: () => pending, rows: () => new Map([["row", saved]]), missionCleanupPending: () => true, + captureView: () => () => true, attempt: 0, alive: true, + setPending: (value: string) => { pending = value }, setError: () => {}, + serverApi: { fetchMission: () => assert.fail("local singleton reached") }, + backendOf: (id: string) => { owners.push(id); return { api: { + fetchMission: () => request.promise, deleteMission: async () => { deletes++ }, + } } }, + }) + const result = run("row"); assert.deepEqual(owners, ["remote~same"]) + backend.replace(); request.resolve({ available: true, cleanups: [saved] }); await result + assert.equal(deletes, 0); assert.equal(refreshes, 0); assert.equal(pending, "") +}) diff --git a/packages/ui/src/components/backend-view-lifetime.test.ts b/packages/ui/src/components/backend-view-lifetime.test.ts new file mode 100644 index 0000000000..9741ea6439 --- /dev/null +++ b/packages/ui/src/components/backend-view-lifetime.test.ts @@ -0,0 +1,255 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import { productionModule } from "../../tests/test-support/production-ast" +import { deferred } from "../../tests/test-support/deferred" +import { createEffect, createMemo, createRoot, createSignal, on, onCleanup, untrack } from "solid-js" +import { z } from "zod" +import { sha256 } from "@noble/hashes/sha2.js" +import { bytesToHex } from "@noble/hashes/utils.js" +import { BackgroundReadQueue } from "../lib/background-read-queue" +import { integrationAttachChoice, integrationLink } from "../lib/integration-row-state" + +// Execute the real view functions, with imports supplied explicitly. No JSX or +// application singleton is needed to test their asynchronous authority boundary. +function view(path: string, imports: Record) { + return productionModule(new URL(path, import.meta.url), { backendOf: () => ({ api: imports.serverApi }), ...imports }) +} +const solid = { createEffect, createMemo, createSignal, on, onCleanup, untrack } +const fileDraftImports = { sha256, bytesToHex, instances: () => new Map(), localServerMeta: { meta: () => undefined } } +const flush = async () => { for (let i = 0; i < 20; i++) await Promise.resolve() } +function attachment() { + let controller = new AbortController() + const [signal, setSignal] = createSignal(controller.signal) + return { + capture: (_id: string, parent?: AbortSignal, owns = () => true) => { + const captured = parent ? AbortSignal.any([signal(), parent]) : signal() + return { signal: captured, current: () => !captured.aborted && owns() } + }, + revoke: () => controller.abort(), + replace: () => { controller.abort(); controller = new AbortController(); setSignal(controller.signal) }, + } +} +const events = { on: () => () => {}, forInstance: () => ({ onOpen: () => () => {} }) } + +test("files: revocation during the conflict read cannot prepare a write or lose the draft", async () => { + const backend = attachment(), disk = deferred<{ contents: string }>() + let writes = 0, signal!: AbortSignal, close!: () => void + const { useWorkspaceFileEditor } = view("./workspace-file-editor.ts", { + ...solid, ...fileDraftImports, serverApi: { + previewWorkspaceFile: (_id: string, _path: string, _directory: string, requestSignal: AbortSignal) => { signal = requestSignal; return disk.promise }, + writeWorkspaceFile: async () => { writes++ }, + }, showConfirmDialog: async () => true, showToastNotification: () => {}, invalidateFilesystemCaches: () => {}, + }) + const target = { directory: "/repo", path: "a.txt" } + const options = { instanceId: "i", target: () => target, active: () => true, t: (key: string) => key, onError: () => {}, captureOperation: backend.capture } + const editor = createRoot(dispose => { close = dispose; return useWorkspaceFileEditor(options) }) + editor.adopt("baseline"); editor.change("my draft") + const saving = editor.save() + backend.revoke(); backend.replace() + assert.equal(signal.aborted, true) + disk.resolve({ contents: "baseline" }); await saving + assert.equal(writes, 0) + assert.equal(editor.text(), "my draft") + assert.equal(editor.dirty(), true) + assert.equal(editor.saving(), false) + close() + const reopened = createRoot(dispose => { close = dispose; return useWorkspaceFileEditor(options) }) + assert.equal(reopened.reset(), "my draft") + close() +}) + +test("files: revocation during confirmation prevents the later write", async () => { + const backend = attachment(), consent = deferred() + let writes = 0, close!: () => void + const { useWorkspaceFileEditor } = view("./workspace-file-editor.ts", { + ...solid, ...fileDraftImports, serverApi: { previewWorkspaceFile: async () => ({ contents: "changed on disk" }), writeWorkspaceFile: async () => { writes++ } }, + showConfirmDialog: () => consent.promise, showToastNotification: () => {}, invalidateFilesystemCaches: () => {}, + }) + const target = { directory: "/repo", path: "confirm.txt" } + const editor = createRoot(dispose => { close = dispose; return useWorkspaceFileEditor({ instanceId: "i", target: () => target, + active: () => true, t: (key: string) => key, onError: () => {}, captureOperation: backend.capture }) }) + editor.adopt("baseline"); editor.change("my draft") + const saving = editor.save(); await flush() + backend.revoke(); consent.resolve(true); await saving + assert.equal(writes, 0); assert.equal(editor.text(), "my draft") + close() +}) + +test("providers: a retained settings view reacquires, and the old read cannot publish", async () => { + const backend = attachment(), reads: ReturnType>[] = [] + let close!: () => void, writes = 0 + const { useImageSettings } = view("./settings/useImageSettings.ts", { ...solid, + captureBackendOperation: backend.capture, serverEvents: events, getActiveCatalogLocation: () => ({ directory: "/repo" }), + serverApi: { getImageSettings: () => { const read = deferred(); reads.push(read); return read.promise }, setImageSettings: async () => { writes++ } }, + }) + const settings = createRoot(dispose => { close = dispose; return useImageSettings({ instanceId: "i" }) }) + assert.equal(reads.length, 1) + backend.replace() + assert.equal(reads.length, 2) + reads[1].resolve({ generation: "new" }); await flush() + reads[0].resolve({ generation: "old" }); await flush() + assert.equal(settings.snapshot().generation, "new") + backend.revoke(); await settings.save({ mediaStorage: true }) + assert.equal(writes, 0) + close() +}) + +test("providers: detached web search completion cannot start its trailing reload", async () => { + const backend = attachment(), write = deferred() + let reads = 0, close!: () => void + const client = { websearch: { providers: async () => ({ data: [] }) }, integration: { list: async () => ({ data: [] }) } } + const { useWebSearchSettings } = view("./settings/useWebSearchSettings.ts", { ...solid, + captureBackendOperation: backend.capture, serverEvents: events, getRootClient: () => client, + getActiveCatalogLocation: () => ({ directory: "/repo" }), toRequestLocation: (value: unknown) => value, requestLocationOptions: () => ({}), + serverApi: { getWebSearchSettings: async () => { reads++; return {} }, setWebSearchSettings: () => write.promise }, + }) + const settings = createRoot(dispose => { close = dispose; return useWebSearchSettings({ instanceId: "i" }) }) + await flush() + const saving = settings.save("project", "provider") + backend.revoke(); write.resolve(); assert.equal(await saving, false) + assert.equal(reads, 1) + close() +}) + +test("integrations: old consent cannot admit an installation on a new attachment", async () => { + const backend = attachment(), consent = deferred() + let installs = 0, refreshes = 0, close!: () => void + const { createIntegrationHostInstallation } = view("./integration-host-installation.ts", { ...solid, + captureBackendOperation: backend.capture, useI18n: () => ({ t: (key: string) => key }), + integrationEpoch: () => "epoch", integrations: { refreshDemanded: () => { refreshes++ } }, + confirmIntegrationAction: () => consent.promise, integrationAttachmentRequest: async () => { installs++; return { outcome: "installed" } }, + showToastNotification: () => {}, HttpResponseError: Error, document: { activeElement: null }, HTMLElement: class {}, + }) + const installation = createRoot(dispose => { close = dispose; return createIntegrationHostInstallation({ instanceId: "i", directory: "/repo", entries: () => [ + { id: "integration", family: "native", state: "ok", app: { name: "App" }, status: { version: "1", host: { state: "available", action: "install" } } }, + ] }) }) + const pending = installation.open("integration") + backend.replace(); consent.resolve(true); await pending + assert.equal(installs, 0); assert.equal(refreshes, 0) + close() +}) + +test("integrations: reinstall stays confirmed for open and closed applications", async () => { + const backend = attachment(), titles: string[] = [] + let installs = 0, close!: () => void + const [host, setHost] = createSignal({ state: "available" }) + const { createIntegrationHostInstallation } = view("./integration-host-installation.ts", { ...solid, + captureBackendOperation: backend.capture, useI18n: () => ({ t: (key: string) => key }), + integrationEpoch: () => "epoch", integrations: { refreshDemanded: () => {} }, + confirmIntegrationAction: async (_warning: string, options: { title: string }) => { titles.push(options.title); return true }, + integrationAttachmentRequest: async () => { installs++; return { outcome: "unchanged" } }, + showToastNotification: () => {}, HttpResponseError: Error, document: { activeElement: null }, HTMLElement: class {}, + }) + const installation = createRoot(dispose => { close = dispose; return createIntegrationHostInstallation({ + instanceId: "i", directory: "/repo", entries: () => [ + { id: "integration", family: "native", state: "ok", app: { name: "App" }, status: { version: "1", host: host() } }, + ], + }) }) + for (const state of ["available", "unknown"]) { + setHost({ state }) + assert.equal(installation.action("integration"), "reinstall") + await installation.open("integration") + } + setHost({ state: "unsupported" }) + assert.equal(installation.action("integration"), undefined) + await installation.open("integration") + assert.deepEqual(titles, ["integrations.installHost.reinstall", "integrations.installHost.reinstall"]) + assert.equal(installs, 2) + close() +}) + +test("integrations: state-line document reads reacquire and fence late backend replies", async () => { + const backend = attachment(), reads: ReturnType>[] = [] + let close!: () => void + const { createIntegrationRowBinding } = view("./integration-row-binding.ts", { ...solid, + captureBackendOperation: backend.capture, + backendEvents: { signalForInstance: () => backend.capture("i").signal }, + integrationEpoch: () => "epoch", integrationLink, integrationAttachChoice, + integrationBindings: { demand: () => () => {}, state: () => ({ state: "none" }), busy: () => false }, + useI18n: () => ({ t: (key: string) => key }), showToastNotification: () => {}, + integrationAttachmentRequest: () => { const read = deferred(); reads.push(read); return read.promise }, + }) + const row = createRoot(dispose => { close = dispose; return createIntegrationRowBinding({ + instanceId: () => "i", directory: () => "/repo", sessionId: () => "ses_1", active: () => true, + integration: () => ({ id: "integration", family: "native", state: "ok", status: { host: { state: "available" }, connection: { offers: 1 } } }), + }) }) + assert.equal(reads.length, 1) + backend.replace() + assert.equal(reads.length, 2) + const current = [{ offerID: "new", protocol: "ok", label: "Current" }] + reads[1].resolve({ offers: current }); await flush() + assert.deepEqual(row.offers(), current) + reads[0].resolve({ offers: [{ offerID: "old", protocol: "ok", label: "Old" }] }); await flush() + assert.deepEqual(row.offers(), current) + backend.replace() + assert.equal(row.offers(), undefined) + assert.equal(reads.length, 3) + close() + reads[2].resolve({ offers: current }); await flush() + assert.equal(row.offers(), undefined) +}) + +test("providers: an old quota response cannot publish or perform its coalesced follow-up", async () => { + const backend = attachment(), response = deferred(), published: unknown[] = [] + let reads = 0 + const { createProviderUsageState } = view("./session/provider-usage-state.ts", {}) + const state = createProviderUsageState(() => { reads++; return response.promise }, (value: unknown) => published.push(value), () => backend.capture("i")) + state.select({ instanceId: "i", sessionId: "s", directory: "/repo", providerId: "p", modelId: "m" }) + const pending = state.refresh(); state.refresh() + backend.revoke(); response.resolve({ account: "old" }); await pending + assert.deepEqual(published, [undefined]); assert.equal(reads, 1) + state.dispose() +}) + +test("files: a queued directory read cannot dispatch with revoked authority", async () => { + const backend = attachment(), queue = new BackgroundReadQueue(1), occupied = deferred() + const busy = queue.run(new AbortController().signal, () => occupied.promise) + await flush() + let reads = 0, close!: () => void + const { useWorkspaceTree } = view("./instance/shell/right-panel/useWorkspaceTree.ts", { ...solid, + backgroundReads: queue, serverApi: { listWorkspaceFiles: async () => { reads++; return [] } }, + filesystemInvalidationVersion: () => 0, createDebouncedRefresh: (run: () => void) => ({ trigger: run, cancel: () => {} }), + }) + const tree = createRoot(dispose => { close = dispose; return useWorkspaceTree("i", () => "/repo", () => true, backend.capture) }) + backend.revoke(); occupied.resolve(); await busy; await flush() + assert.equal(reads, 0); assert.equal(tree.rows().length, 0) + close() +}) + +test("extensions: a late forge address cannot open a browser or answer a replacement attachment", async () => { + const backend = attachment(), address = deferred<{ url: string }>(), answers: unknown[] = [] + let opened = 0, close!: () => void + const { useWorkItemsChannel } = view("./panel-extensions/work-items-channel.ts", { ...solid, z, + serverEvents: { forInstance: () => ({ onTransportStatus: () => () => {} }) }, + panelExtensionsApi: { workItemUrl: () => address.promise }, openExternalUrl: async () => { opened++; return true }, + }) + const receive = createRoot(dispose => { close = dispose; return useWorkItemsChannel({ instanceId: "i", id: "extension", digest: "d", + send: (value: unknown) => answers.push(value), captureOperation: backend.capture }) }) + const pending = receive({ type: "workItems:request", id: 1, method: "open", input: { kind: "issue", number: 1 } }) + backend.replace(); address.resolve({ url: "https://example.com/issue/1" }); await pending + assert.equal(opened, 0); assert.deepEqual(answers, []) + close() +}) + +test("sessions: hydration from the old attachment cannot start a message read", async () => { + const backend = attachment(), hydration: ReturnType>[] = [], reads: AbortSignal[] = [] + const forces: boolean[] = [] + let close!: () => void + const { useActiveSessionMessageLoad } = view("../lib/hooks/use-active-session-message-load.ts", solid) + createRoot(dispose => { + close = dispose + useActiveSessionMessageLoad({ isActive: () => true, instanceId: () => "i", session: () => ({ id: "s" }), + forceLoad: true, + captureOperation: backend.capture, waitForHydration: () => { const gate = deferred(); hydration.push(gate); return gate.promise }, + loadMessages: (_id: string, _session: string, options: { signal: AbortSignal; force: boolean }) => { reads.push(options.signal); forces.push(options.force) }, + }) + }) + backend.replace() + assert.equal(hydration.length, 2) + hydration[0].resolve(); await flush() + assert.equal(reads.length, 0) + hydration[1].resolve(); await flush() + assert.equal(reads.length, 1); assert.equal(reads[0].aborted, false) + assert.deepEqual(forces, [true]) + close() +}) diff --git a/packages/ui/src/components/background-shell-row.tsx b/packages/ui/src/components/background-shell-row.tsx new file mode 100644 index 0000000000..43e80236a3 --- /dev/null +++ b/packages/ui/src/components/background-shell-row.tsx @@ -0,0 +1,107 @@ +import { Show, createEffect, createMemo, createSignal, onCleanup } from "solid-js" +import type { ShellInfo } from "@opencode/client" +import { Tooltip } from "@kobalte/core/tooltip" +import { Check, Circle, Minus, Trash2, X } from "lucide-solid" +import { useI18n } from "../lib/i18n" +import { createLongPressHandlers } from "../lib/long-press" +import { shellCommandLabel } from "../lib/shell-command-label" + +interface BackgroundShellRowProps { + shell: ShellInfo + removing: boolean + onOutput: () => void + onRemove: (button: HTMLButtonElement) => void +} + +export function BackgroundShellRow(props: BackgroundShellRowProps) { + const { t, locale } = useI18n() + const [open, setOpen] = createSignal(false) + const [pinned, setPinned] = createSignal(false) + let button!: HTMLButtonElement + let content: HTMLDivElement | undefined + let pointerStart: { x: number; y: number } | undefined + const label = createMemo(() => shellCommandLabel(props.shell.command)) + const state = () => { + if (props.shell.status === "running") return "running" + if (props.shell.status === "killed") return "killed" + if (props.shell.status === "timeout") return "timeout" + return props.shell.exit !== undefined && props.shell.exit !== 0 ? "failed" : "exited" + } + const status = () => t(`instanceShell.backgroundProcesses.status.${state()}`) + const removeLabel = () => t(`instanceShell.backgroundProcesses.actions.${state() === "running" ? "stopRemove" : "remove"}`) + const close = () => { setPinned(false); setOpen(false) } + const handlers = createLongPressHandlers({ onClick: () => { close(); props.onOutput() }, onLongPress: () => setPinned(true) }) + const onKeyDown = (event: KeyboardEvent) => { + handlers.onKeyDown(event) + if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || (!open() && !pinned()) || !content) return + const distance = { ArrowDown: 40, ArrowUp: -40, PageDown: content.clientHeight * .9, + PageUp: -content.clientHeight * .9, Home: -content.scrollHeight, End: content.scrollHeight }[event.key] + if (distance === undefined) return + event.preventDefault() + content.scrollTop += distance + } + const date = (value: number) => new Date(value).toLocaleString(locale(), { + year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit", + }) + createEffect(() => { + if (!open() && !pinned()) return + const outside = (event: PointerEvent) => { + if (!button.contains(event.target as Node) && !content?.contains(event.target as Node)) close() + } + const escape = (event: KeyboardEvent) => { if (event.key === "Escape") close() } + document.addEventListener("pointerdown", outside, true) + document.addEventListener("keydown", escape, true) + onCleanup(() => { + document.removeEventListener("pointerdown", outside, true) + document.removeEventListener("keydown", escape, true) + }) + }) + return ( +
+ + { pointerStart = { x: event.clientX, y: event.clientY }; handlers.onPointerDown(event) }} + onPointerMove={(event: PointerEvent) => { + if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) > 8) handlers.onPointerCancel() + }} + onPointerUp={handlers.onPointerUp} onPointerCancel={handlers.onPointerCancel} + onPointerLeave={handlers.onPointerLeave} onTouchEnd={handlers.onTouchEnd} + onContextMenu={handlers.onContextMenu} onKeyDown={onKeyDown} + > + + + {props.shell.command}}> + {(value) => <>{value().program} + {value().args} + } + + + + + + + + +
+ ) +} diff --git a/packages/ui/src/components/browse-menu.tsx b/packages/ui/src/components/browse-menu.tsx new file mode 100644 index 0000000000..43264b1588 --- /dev/null +++ b/packages/ui/src/components/browse-menu.tsx @@ -0,0 +1,169 @@ +import { For, Show, createEffect, createMemo, createSignal, on, onMount } from "solid-js" +import { Globe, Laptop, Plus, Server } from "lucide-solid" +import type { RemoteServerBrowseResponse, RemoteServerProfile, SideCar } from "../../../server/src/api-types" +import { useI18n } from "../lib/i18n" +import { qualifiedServerDisplayName } from "../lib/codenomad-link" +import { allowsPlainNavigation, withHotkey } from "../lib/hotkeys" +import { sameServerSelection, type ServerSelectionIntent } from "../lib/native/server-selection-intent" +import { getServerMeta, serversManageable, sidecarsAllowed } from "../lib/server-meta" +import ServerAddField from "./server-add-field" +import { RemoteServerBrowser } from "./remote-server-browser" +import { useConfig } from "../stores/preferences" +import { remoteRecentProjectsUsable, savedProjectProfile } from "../stores/recent-projects" +import { ensureSidecarsLoaded, sidecars } from "../stores/sidecars" +import { openSettingsRow } from "../stores/settings-screen" +import { joinRecentOpenTarget, recentAccessibleName, recentOpenTarget, type LaunchableRecent } from "../lib/recent-open-target" + +interface BrowseMenuProps { + isLoading: boolean + active?: boolean + initialServer?: ServerSelectionIntent + onSourceChange: (source: { profile: RemoteServerProfile; listing?: RemoteServerBrowseResponse } | undefined) => void + /** Browses this computer's folders (native dialog or folder browser). */ + onBrowseLocal: () => void + onOpenSidecar: (id: string) => void + onJoined?: () => void + onRemoteOpened?: (instanceId: string) => void +} + +/** Choices only: this computer, available saved servers and configured SideCars (the add field is an action). */ +export function createBrowseEntryCount() { + const { remoteServers } = useConfig() + return () => 1 + (remoteRecentProjectsUsable() ? remoteServers().length : 0) + (sidecarsAllowed() ? sidecars().size : 0) +} + +/** + * Browse in the canonical project selector: this computer's folders, saved + * CodeNomad servers, configured SideCars, then the inline server-add field. + */ +export default function BrowseMenu(props: BrowseMenuProps) { + const { t } = useI18n() + const { remoteServers } = useConfig() + const [selectedServer, setSelectedServer] = createSignal() + const [connectionFailures, setConnectionFailures] = createSignal([]) + onMount(() => { void getServerMeta().catch(() => {}) }) + // A delayed capability read must admit the native intent once, without replaying it after Back. + let appliedIntent: ServerSelectionIntent | undefined + createEffect(on([() => props.initialServer, remoteRecentProjectsUsable], ([intent, usable]) => { + if (!usable || intent === appliedIntent) return + appliedIntent = intent + const profile = intent && savedProjectProfile(intent) + const selected = selectedServer() + if (profile && (!selected || !sameServerSelection(profile, selected))) selectServer(profile) + })) + createEffect(() => { + const selected = selectedServer() + if (selected && (!remoteRecentProjectsUsable() || !remoteServers().some(profile => sameServerSelection(profile, selected)))) selectServer(undefined) + }) + function selectServer(profile: RemoteServerProfile | undefined) { + props.onSourceChange(profile ? { profile } : undefined) + setSelectedServer(profile) + } + let bodyRef: HTMLDivElement | undefined + + createEffect(() => { if (sidecarsAllowed()) void ensureSidecarsLoaded() }) + + const navItems = () => [...(bodyRef?.querySelectorAll("[data-browse-nav]") ?? [])].filter((item) => !item.hasAttribute("disabled")) + const servers = () => (remoteRecentProjectsUsable() ? remoteServers() : []) + const displayName = (profile: RemoteServerProfile) => qualifiedServerDisplayName(profile, remoteServers()) + const orderedSidecars = createMemo(() => sidecarsAllowed() ? [...sidecars().values()].sort((left, right) => left.name.localeCompare(right.name)) : []) + + function run(action: () => void) { + if (props.isLoading) return + action() + } + + function handleKeyDown(event: KeyboardEvent) { + if (!allowsPlainNavigation(event)) return + const items = navItems() + const index = items.indexOf(document.activeElement as HTMLElement) + const move = (next: number) => { if (items.length) { event.preventDefault(); items[(next + items.length) % items.length]?.focus() } } + // Home and End stay with the address field's text. + const inField = event.target instanceof HTMLInputElement + if (inField && !event.target.hasAttribute("data-browse-nav") && event.key !== "Escape") return + if (event.key === "ArrowDown") move(index + 1) + else if (event.key === "ArrowUp") move(index - 1) + else if (event.key === "Home" && !inField) move(0) + else if (event.key === "End" && !inField) move(items.length - 1) + else if (event.key === "Escape" && selectedServer()) { + event.preventDefault() + backToRoot() + } + } + + function backToRoot() { + const id = selectedServer()?.id + selectServer(undefined) + queueMicrotask(() => { if (props.active !== false) bodyRef?.querySelector(`[data-remote-server="${CSS.escape(id ?? "")}"]`)?.focus() }) + } + + const sidecarRunning = (sidecar: SideCar) => sidecar.status === "running" + const AddField = () => + setConnectionFailures(ids => ids.includes(id) ? ids : [...ids, id])} + onAdded={(id, mayFocus) => { + setConnectionFailures(ids => ids.filter(value => value !== id)) + queueMicrotask(() => { if (props.active !== false && (mayFocus?.() ?? true)) bodyRef?.querySelector(`[data-remote-server="${CSS.escape(id)}"]`)?.focus() }) + }} /> + + + return ( +
+
+ {(profile) => { + if (selectedServer() !== profile) return + props.onSourceChange({ profile, listing }) + if (listing) setConnectionFailures(ids => ids.filter(id => id !== profile.id)) + }} onConnectionRequired={() => setConnectionFailures(ids => ids.includes(profile.id) ? ids : [...ids, profile.id])} + onOpened={props.onRemoteOpened} />} + + + + {(profile) => ( + + )} + + {/* A SideCar opens only while it runs; its state shows on the row. */} + + {(sidecar) => { + const recent: LaunchableRecent = { kind: "sidecar", key: sidecar.id, path: sidecar.id, projectName: sidecar.name, lastAccessed: 0 } + return
+ + + + +
+ }} +
+ +
+
+ +
+ ) +} diff --git a/packages/ui/src/components/browser-frame-security.ts b/packages/ui/src/components/browser-frame-security.ts index a1ae28640e..b0e26fac36 100644 --- a/packages/ui/src/components/browser-frame-security.ts +++ b/packages/ui/src/components/browser-frame-security.ts @@ -4,16 +4,16 @@ import { PREVIEW_SANDBOX_FLAGS as FRAME_SANDBOX } from "../../../server/src/prev /** * `allow-same-origin` lets a frame's own fetches and WebSocket handshakes stay * same-origin, so the `SameSite=Lax` session cookie reaches app-authenticated - * routes. Reserved for app-proxied content the user explicitly configured - * (SideCars): without it the sandboxed frame is an opaque origin, its requests - * carry `Origin: null`, and `/sidecars/*` rejects them before the proxy runs. + * routes. Reserved for explicitly trusted SideCars or host-issued isolated + * preview origins with origin-bound content admission. Ordinary path previews + * retain opaque origins; SideCars require the application's same-origin cookie. */ export function getBrowserFramePolicy( _environment: Pick, - options: { trustedSameOrigin?: boolean } = {}, + options: { trustedSameOrigin?: boolean; isolatedOrigin?: boolean } = {}, ) { return { - sandbox: options.trustedSameOrigin ? `${FRAME_SANDBOX} allow-same-origin` : FRAME_SANDBOX, + sandbox: options.trustedSameOrigin || options.isolatedOrigin ? `${FRAME_SANDBOX} allow-same-origin` : FRAME_SANDBOX, canInspectDom: false, } } @@ -46,7 +46,8 @@ export function isLoopbackPreviewUrl(rawUrl: string): boolean { export function isLoopbackHttpUrl(rawUrl: string): boolean { if (!/^https?:\/\//i.test(rawUrl)) return false try { - return isLoopbackHostname(new URL(rawUrl).hostname.toLowerCase()) + const target = new URL(rawUrl) + return !target.username && !target.password && isLoopbackHostname(target.hostname.toLowerCase()) } catch { return false } @@ -67,9 +68,12 @@ export function normalizeBrowserPreviewUrl(rawUrl: string): string { export function getPreviewFrameSource( environment: Pick, - preview: { token: string; targetUrl: string; proxyUrl: string }, + preview: { token: string; targetUrl: string; proxyUrl: string; contentUrl?: string }, parentUrl: string, + backendId = "local", ): string { + // Host path capabilities are issued relative to the page origin. + if (backendId !== "local") return new URL(preview.contentUrl ?? preview.proxyUrl, parentUrl).href if (environment.windowContext !== "local" || (environment.host !== "electron" && environment.host !== "tauri")) { return preview.proxyUrl } diff --git a/packages/ui/src/components/browser-frame.tsx b/packages/ui/src/components/browser-frame.tsx index 5231a722a5..96663b6476 100644 --- a/packages/ui/src/components/browser-frame.tsx +++ b/packages/ui/src/components/browser-frame.tsx @@ -18,9 +18,11 @@ import { unregisterTauriBrowserTarget, updateTauriBrowserTarget, readBrowserHistory, + releaseNativeBrowserOpen, goToBrowserHistoryEntry, } from "../lib/native/browser" import { getBrowserFramePolicy, normalizeBrowserPreviewUrl } from "./browser-frame-security" +import { remotePreviewNavigationTarget } from "../lib/remote-preview-address" import WindowCloseButton from "./window-close-button" import { BrowserHistoryJournal, type BrowserHistory, type NativeBrowserHistory } from "../lib/browser-history" @@ -72,12 +74,21 @@ const VIEWPORT_OPTIONS = [ ] interface BrowserFrameProps { + instanceId?: string + openRequestId?: string + interruptedOpenId?: string + ownershipRevision?: number + onNativeRegistration?: (registrationId: string) => Promise active?: boolean onClose?: () => void sessionId?: string title: string initialUrl: string initialAddress?: string + isolatedSource?: boolean + /** An isolated source on the application's own origin (a host path capability): its documents stay opaque. */ + opaqueSource?: boolean + sourceAddress?: (source: string) => string | undefined proxyBasePath: string /** * Content proxied through the app's authenticated origin that the user @@ -139,8 +150,22 @@ export const BrowserFrame: Component = (props) => { const { t } = useI18n() const [emulationBusy, setEmulationBusy] = createSignal(false) const [registrationReady, setRegistrationReady] = createSignal(false) + const [visibleRegistration, setVisibleRegistration] = createSignal<{ id: string; instanceId: string }>() + const [openAcknowledgement, setOpenAcknowledgement] = createSignal<{ requestId: string; id: string; instanceId: string }>() + createEffect(() => { + const target = visibleRegistration() + const requestId = props.openRequestId + if (requestId && target && props.active !== false && props.instanceId === target.instanceId) { + void props.onNativeRegistration?.(target.id).then(admitted => { + if (admitted && props.openRequestId === requestId && canNavigate(target.instanceId) + && visibleRegistration()?.id === target.id) setOpenAcknowledgement({ requestId, ...target }) + }).catch(reportNativeError) + } + }) const [frameSrc, setFrameSrc] = createSignal(props.initialUrl) - const [pathInput, setPathInput] = createSignal(props.initialAddress ?? "/") + const [liveAddress, setPathInput] = createSignal(props.initialAddress ?? "/") + const [addressDraft, setAddressDraft] = createSignal() + const pathInput = () => addressDraft() ?? liveAddress() const [viewportPreset, setViewportPreset] = createSignal(props.initialViewport ?? "responsive") const commitViewport = (preset: BrowserViewportPreset) => { setViewportPreset(preset); props.onViewportChange?.(preset) } const [viewportMenuOpen, setViewportMenuOpen] = createSignal(false) @@ -152,7 +177,13 @@ export const BrowserFrame: Component = (props) => { const emulationReady = () => registrationReady() && capabilities.emulation const nativeBrowserAvailable = Boolean(browserHost) && props.addressMode === "url" const [nativeMode, setNativeMode] = createSignal(nativeBrowserAvailable) - const [nativeTarget, setNativeTarget] = createSignal(props.initialAddress ?? "") + const initialOpenRequestId = untrack(() => props.openRequestId) + const initialOwnershipRevision = untrack(() => props.ownershipRevision) + const [nativeTarget, setNativeTarget] = createSignal(initialOpenRequestId && browserHost === "electron" + ? "about:blank" : props.isolatedSource ? props.initialUrl : props.initialAddress ?? "") + let observedFrameSource: string | undefined + let appliedInitialSource: string | undefined + let appliedInitialAddress: string | undefined let iframeRef: HTMLIFrameElement | undefined let webviewRef: ElectronBrowserWebviewElement | undefined // Electron exposes the methods before its guest is ready to accept them. @@ -163,8 +194,30 @@ export const BrowserFrame: Component = (props) => { let cleanupWebviewListeners: (() => void) | null = null let cleanupTauriTarget: (() => void) | null = null let tauriRegistered = false + // Latest navigation requested before the Tauri target exists, replayed once its + // emulation is restored. Kept apart from nativeTarget, which the initial load's + // navigation events can overwrite. Any later direct action supersedes it. + let pendingTauriNavigation: { url: string; logicalAddress?: string; sessionId?: string } | undefined + const navigateTauri = (url: string, logicalAddress?: string) => { + if (!tauriRegistered) { pendingTauriNavigation = { url, logicalAddress, sessionId: props.sessionId }; return Promise.resolve() } + pendingTauriNavigation = undefined + return controlTauriBrowserTarget(browserRegistrationId, "navigate", url, logicalAddress) + } + const actOnTauri = (action: "back" | "reload") => { + if (!tauriRegistered) return + pendingTauriNavigation = undefined + void controlTauriBrowserTarget(browserRegistrationId, action).catch(reportNativeError) + } let browserRegistrationId = nativeBrowserAvailable ? generateUUID() : "" let disposed = false + const loadFrameSource = (source: string) => { + if (props.isolatedSource) { + // Site navigation changes the document without changing the iframe's src attribute. + if (source === frameSrc() && observedFrameSource !== undefined && observedFrameSource !== source) iframeRef?.setAttribute("src", source) + observedFrameSource = source + } + setFrameSrc(source) + } let appliedEmulation: { registrationId: string; preset: BrowserEmulationPreset } | undefined let emulationGeneration = 0 const journal = props.onHistoryChange ? new BrowserHistoryJournal(untrack(() => props.initialHistory ?? { urls: [props.initialAddress ?? props.initialUrl], index: 0 })) : undefined @@ -172,7 +225,17 @@ export const BrowserFrame: Component = (props) => { const [historyBusy, setHistoryBusy] = createSignal(false) let historyRead = 0 let historyTravelVersion = 0 + let preparingHistory: Promise | undefined const historyGuestId = () => webviewReady ? webviewRef?.getWebContentsId() : undefined + const logicalHistory = (value: NativeBrowserHistory): NativeBrowserHistory => { + if (!props.isolatedSource) return value + const current = value.entries[value.index]?.id + const entries = value.entries.flatMap(entry => { + const url = props.sourceAddress?.(entry.url) + return url ? [{ ...entry, url }] : [] + }) + return { entries, index: entries.findIndex(entry => entry.id === current) } + } const supersedeHistoryTraversal = () => { if (journal?.traversing || historyBusy()) props.onCancelNavigation?.() ++historyTravelVersion @@ -190,19 +253,22 @@ export const BrowserFrame: Component = (props) => { props.onHistoryChange?.(value) setHistoryBusy(journal?.traversing ?? false) } - const captureHistory = async () => { - if (!journal || !capabilities.history || disposed || !(browserHost === "electron" ? webviewReady : untrack(registrationReady))) return + const captureHistory = async (confirmedUrl?: string) => { + if (props.openRequestId || (preparingHistory && !confirmedUrl) || !journal || !capabilities.history || disposed + || !(browserHost === "electron" ? webviewReady : untrack(registrationReady))) return const sequence = ++historyRead const registration = browserRegistrationId const guestId = historyGuestId() try { const value = await readBrowserHistory(registration, guestId) - if (disposed || sequence !== historyRead || registration !== browserRegistrationId || guestId !== historyGuestId()) return + if (props.openRequestId || (preparingHistory && !confirmedUrl) || disposed || sequence !== historyRead || registration !== browserRegistrationId || guestId !== historyGuestId()) return // CDP can report the destination cursor before Chromium emits its commit // event. Publishing that intent as a prop would start a second navigation. - if (browserHost === "electron" && value.entries[value.index]?.url !== webviewObservedUrl) return - if (browserHost === "tauri" && value.entries[value.index]?.url !== nativeTarget()) return - publishHistory(journal.observe(value)) + const currentUrl = confirmedUrl ?? (browserHost === "electron" ? webviewObservedUrl : nativeTarget()) + const entry = value.entries[value.index] + if (!entry || entry.url !== currentUrl) return + if (confirmedUrl) { journal.bindCurrent(entry); return } + publishHistory(journal.observe(logicalHistory(value))) } catch (error) { if (!disposed && sequence === historyRead) { journal.cancel() @@ -212,7 +278,39 @@ export const BrowserFrame: Component = (props) => { } } - const framePolicy = getBrowserFramePolicy(runtimeEnv, { trustedSameOrigin: props.trustedSameOrigin }) + let interruptedCandidate: { requestId: string; registration: string; guestId?: number; id: number } | undefined + const retireInterruptedEntry = () => { + const entry = interruptedCandidate + if (entry && entry.requestId === props.interruptedOpenId + && entry.registration === browserRegistrationId && entry.guestId === historyGuestId()) { + journal?.retireEntry(entry.id) + interruptedCandidate = undefined + } + } + const startNavigation = () => { + props.onNavigationStart?.() + const requestId = props.openRequestId + if (!requestId || !journal || !capabilities.history || !untrack(registrationReady)) return + const registration = browserRegistrationId + const guestId = historyGuestId() + const observed = browserHost === "electron" ? webviewObservedUrl : untrack(nativeTarget) + // Electron reads history through the same queue as the pending load. Retire + // only that load; the owner and the guest remain available for navigation. + const ready = browserHost === "electron" ? releaseNativeBrowserOpen(requestId).catch(() => false) : Promise.resolve() + const preparing = ready.then(() => readBrowserHistory(registration, guestId)).then(value => { + const entry = value.entries[value.index] + if (!disposed && entry && entry.url === observed && registration === browserRegistrationId && guestId === historyGuestId()) { + interruptedCandidate = { requestId, registration, guestId, id: entry.id } + retireInterruptedEntry() + } + }).catch(() => {}).finally(() => { + if (preparingHistory === preparing) preparingHistory = undefined + }) + preparingHistory = preparing + return preparing + } + + const framePolicy = getBrowserFramePolicy(runtimeEnv, { trustedSameOrigin: props.trustedSameOrigin, isolatedOrigin: props.isolatedSource && !props.opaqueSource }) const canComment = createMemo(() => !nativeMode() && (framePolicy.canInspectDom || props.commentBridge) && Boolean(props.onToggleCommentMode && props.onCommentTarget)) const viewport = createMemo(() => VIEWPORT_PRESETS[viewportPreset()]) const isResponsiveViewport = createMemo(() => viewportPreset() === "responsive") @@ -249,7 +347,9 @@ export const BrowserFrame: Component = (props) => { setViewportMenuOpen(false) const previous = appliedEmulation?.registrationId === browserRegistrationId ? appliedEmulation.preset : undefined const next = emulationProfile(preset) - if ((previous === next && !webkitEmulation) || !nativeMode() || !capabilities.emulation) { commitViewport(preset); return } + // A Tauri target still registering applies the committed preset when it is ready. + if ((previous === next && !webkitEmulation) || !nativeMode() || !capabilities.emulation + || (browserHost === "tauri" && !tauriRegistered)) { commitViewport(preset); return } setEmulationBusy(true) const generation = ++emulationGeneration const registrationId = browserRegistrationId @@ -261,6 +361,7 @@ export const BrowserFrame: Component = (props) => { } const getEditablePathFromUrl = (url: string): string => { + if (props.isolatedSource) return props.sourceAddress?.(url) ?? props.initialAddress ?? "/" try { const parsed = new URL(url, window.location.origin) const basePath = props.proxyBasePath @@ -336,11 +437,12 @@ export const BrowserFrame: Component = (props) => { if (props.commentBridge && !framePolicy.canInspectDom) { frameWindow.postMessage({ type: "codenomad-preview-comment-mode", enabled: Boolean(props.commentMode) }, "*") const handleMessage = (event: MessageEvent) => { - if (event.source !== frameWindow || event.origin !== "null") return + if (event.source !== frameWindow || event.origin !== (props.isolatedSource && !props.opaqueSource ? new URL(props.initialUrl).origin : "null")) return if (event.data?.type === "codenomad-preview-location") { const path = event.data.path if (typeof path !== "string" || path.length > 4_096 || !path.startsWith("/")) return const address = props.onFrameLocation?.(path) + if (props.isolatedSource) observedFrameSource = new URL(`${props.proxyBasePath}${path}`, props.initialUrl).href if (address) setPathInput(address) if (address && journal) publishHistory(journal.visitUrl(address)) return @@ -410,7 +512,7 @@ export const BrowserFrame: Component = (props) => { const currentHref = iframeRef?.contentWindow?.location.href if (currentHref) setPathInput(getEditablePathFromUrl(currentHref)) } catch { - setPathInput(getEditablePathFromUrl(frameSrc())) + setPathInput(getEditablePathFromUrl(observedFrameSource ?? frameSrc())) } attachCommentListeners() // A trusted same-origin document (SideCar) opens its new-window links like the app's own. @@ -422,11 +524,12 @@ export const BrowserFrame: Component = (props) => { const reportNativeError = (error: unknown) => { if (!disposed && props.active !== false) props.onNavigationError?.(error) } + const canNavigate = (instanceId: string | undefined) => !disposed && props.active !== false && props.instanceId === instanceId const requestNativeTarget = (address: string) => { webviewObservedUrl = undefined const previousTarget = nativeTarget() - if (nativeMode() && (browserHost === "electron" || previousTarget !== address)) supersedeHistoryTraversal() + if (!props.isolatedSource && nativeMode() && (browserHost === "electron" || previousTarget !== address)) supersedeHistoryTraversal() setNativeTarget(address) // Electron reflects redirects into src, while the desired-URL signal can // still hold the original URL. Reapply that explicit intent when the signal @@ -436,6 +539,12 @@ export const BrowserFrame: Component = (props) => { } } + const navigateFromGuest = (source: string) => { + // A late commit for a previous capability (or a guest placeholder) is not user input. + const target = remotePreviewNavigationTarget(source, props.opaqueSource ? window.location.origin : undefined) + if (target) void navigateIsolated(target) + } + const bindWebview = (webview: ElectronBrowserWebviewElement) => { cleanupWebviewListeners?.() webviewRef = webview @@ -450,11 +559,15 @@ export const BrowserFrame: Component = (props) => { let retryTimer: ReturnType | undefined const syncLocation = (event: Event) => { if (!active || webviewRef !== webview) return - const url = (event as Event & { url?: string }).url ?? (webviewReady ? webview.getURL() : undefined) - if (!url) return + const navigation = event as Event & { url?: string; isMainFrame?: boolean } + if (navigation.isMainFrame === false) return + const url = navigation.url ?? (webviewReady ? webview.getURL() : undefined) + if (!url || (initialOpenRequestId && url === "about:blank")) return + const address = props.isolatedSource ? props.sourceAddress?.(url) : url + if (!address) { navigateFromGuest(url); return } webviewObservedUrl = url - setPathInput(url) - props.onFrameLocation?.(url) + setPathInput(address) + props.onFrameLocation?.(address) void captureHistory() } const reportLoadError = (event: Event) => { @@ -474,13 +587,16 @@ export const BrowserFrame: Component = (props) => { } if (active) retryTimer = setTimeout(syncRegistration, 100) } + let registeredInstanceId: string | undefined const syncRegistration = () => { const rect = webview.getBoundingClientRect() const visible = active && props.active !== false && rect.width > 0 && rect.height > 0 const sessionId = props.sessionId + const instanceId = props.instanceId || undefined if (!webviewReady || !sessionId || registering) return - if (registered && registeredSessionId !== sessionId) { + if (registered && (registeredSessionId !== sessionId || registeredInstanceId !== instanceId)) { setRegistrationReady(false) + setVisibleRegistration(undefined) const previousId = browserRegistrationId browserRegistrationId = generateUUID() registering = true @@ -495,6 +611,7 @@ export const BrowserFrame: Component = (props) => { if (visible === registered) return if (!visible) { setRegistrationReady(false) + setVisibleRegistration(undefined) if (retryTimer) clearTimeout(retryTimer) retryTimer = undefined if (registered) { @@ -515,8 +632,10 @@ export const BrowserFrame: Component = (props) => { try { void register({ sessionId, + instanceId, registrationId, guestWebContentsId: webview.getWebContentsId(), + ...(props.isolatedSource ? { logicalAddress: props.initialAddress } : {}), }).then(async () => { registering = false if (!active) { @@ -525,7 +644,9 @@ export const BrowserFrame: Component = (props) => { } registered = true registeredSessionId = sessionId + registeredInstanceId = instanceId await restoreEmulation(registrationId) + if (active && props.active !== false && instanceId && props.instanceId === instanceId) setVisibleRegistration({ id: registrationId, instanceId }) void captureHistory() registrationFailures = 0 registrationErrorReported = false @@ -547,17 +668,19 @@ export const BrowserFrame: Component = (props) => { webview.addEventListener("did-navigate-in-page", syncLocation) webview.addEventListener("did-fail-load", reportLoadError) webview.addEventListener("dom-ready", handleReady) - webview.addEventListener("did-finish-load", captureHistory) + const handleFinish = () => { void captureHistory() } + webview.addEventListener("did-finish-load", handleFinish) syncRegistration() cleanupWebviewListeners = () => { setRegistrationReady(false) + setVisibleRegistration(undefined) active = false if (retryTimer) clearTimeout(retryTimer) webview.removeEventListener("did-navigate", syncLocation) webview.removeEventListener("did-navigate-in-page", syncLocation) webview.removeEventListener("did-fail-load", reportLoadError) webview.removeEventListener("dom-ready", handleReady) - webview.removeEventListener("did-finish-load", captureHistory) + webview.removeEventListener("did-finish-load", handleFinish) resizeObserver.disconnect() if (registered) void window.electronAPI?.unregisterBrowserTarget?.(browserRegistrationId).catch(reportNativeError) if (webviewRef === webview) { @@ -601,9 +724,11 @@ export const BrowserFrame: Component = (props) => { } const syncBounds = () => { const sessionId = props.sessionId + const instanceId = props.instanceId || undefined if (!active || registering || !sessionId) return const next = bounds() if (!next) { + setVisibleRegistration(undefined) lastBounds = "" if (registered && nativeVisible) { registering = true @@ -617,6 +742,7 @@ export const BrowserFrame: Component = (props) => { return } if (registered && registeredSessionId !== sessionId) { + setVisibleRegistration(undefined) const previousId = browserRegistrationId browserRegistrationId = generateUUID() registering = true @@ -626,6 +752,7 @@ export const BrowserFrame: Component = (props) => { nativeVisible = false registeredSessionId = "" tauriRegistered = false + pendingTauriNavigation = undefined setRegistrationReady(false) void unregisterTauriBrowserTarget(previousId).catch(reportNativeError).finally(() => { registering = false @@ -633,18 +760,20 @@ export const BrowserFrame: Component = (props) => { }) return } - const serialized = JSON.stringify(webkitEmulation + const serialized = JSON.stringify([instanceId, webkitEmulation ? { bounds: next, presentation: presentation(), window: [window.innerWidth, window.innerHeight, window.devicePixelRatio] } - : next) + : next]) if (registered && nativeVisible && serialized === lastBounds) return if (registered) { const revealing = !nativeVisible registering = true - void updateTauriBrowserTarget(browserRegistrationId, next, true, presentation()).then(() => { + const registrationId = browserRegistrationId + void updateTauriBrowserTarget(registrationId, next, true, presentation(), instanceId).then(() => { lastBounds = serialized nativeVisible = true syncErrorReported = false registering = false + if (active && instanceId && props.instanceId === instanceId && bounds()) setVisibleRegistration({ id: registrationId, instanceId }) if (revealing) void captureHistory() if (active) syncBounds() }).catch(reportSyncError) @@ -653,11 +782,17 @@ export const BrowserFrame: Component = (props) => { registering = true const target = nativeTarget() const registrationId = browserRegistrationId + // This registration loads the pending address itself (e.g. a retry). + if (pendingTauriNavigation?.url === target) pendingTauriNavigation = undefined + let loaded = target void onTauriBrowserNavigation(registrationId, (url) => { if (!active) return + loaded = url + const address = props.isolatedSource ? props.sourceAddress?.(url) : url + if (!address) { navigateFromGuest(url); return } setNativeTarget(url) - setPathInput(url) - props.onFrameLocation?.(url) + setPathInput(address) + props.onFrameLocation?.(address) void captureHistory() }).then(async (unlisten) => { if (!active) { @@ -668,8 +803,11 @@ export const BrowserFrame: Component = (props) => { unlistenNavigation = unlisten await registerTauriBrowserTarget({ sessionId, + instanceId, + openRequestId: props.openRequestId, registrationId, url: target, + ...(props.isolatedSource ? { logicalAddress: props.initialAddress } : {}), bounds: next, ...(webkitEmulation ? { presentation: presentation() } : {}), }) @@ -687,8 +825,16 @@ export const BrowserFrame: Component = (props) => { await restoreEmulation(registrationId) void captureHistory() syncErrorReported = false - if (nativeTarget() !== target) { - await controlTauriBrowserTarget(registrationId, "navigate", nativeTarget()) + // Load the address requested before the target existed, under the restored + // profile, unless a direct action superseded it or this target was replaced. + // A replaced target leaves the queue to its successor; an intent of another + // session is dropped; the page the target already shows is not requested again. + if (active && registrationId === browserRegistrationId) { + const pending = pendingTauriNavigation + pendingTauriNavigation = undefined + if (pending && pending.sessionId === sessionId && props.sessionId === sessionId && pending.url !== loaded) { + await controlTauriBrowserTarget(registrationId, "navigate", pending.url, pending.logicalAddress) + } } syncBounds() }).catch(reportSyncError) @@ -711,6 +857,7 @@ export const BrowserFrame: Component = (props) => { queueMicrotask(syncBounds) cleanupTauriTarget = () => { active = false + setVisibleRegistration(undefined) resizeObserver.disconnect() overlayObserver.disconnect() window.removeEventListener("resize", syncBounds) @@ -721,25 +868,71 @@ export const BrowserFrame: Component = (props) => { registered = false nativeVisible = false tauriRegistered = false + pendingTauriNavigation = undefined setRegistrationReady(false) } } + let openPending = false + let openSource: string | undefined + let historyBeforeOpen: BrowserHistory | undefined + let addressBeforeOpen: string | undefined createEffect(() => { const initialUrl = props.initialUrl const initialAddress = props.initialAddress + const pending = Boolean(props.openRequestId) + const settled = openPending && !pending && openSource === untrack(() => props.proxyBasePath) + if (openPending !== pending) { + ++historyRead + if (pending) { + openSource = untrack(() => props.proxyBasePath) + historyBeforeOpen = untrack(() => props.initialHistory) + addressBeforeOpen = untrack(liveAddress) + ++historyTravelVersion + journal?.cancel() + setHistoryBusy(false) + } + } + openPending = pending untrack(() => { + if (settled) { + retireInterruptedEntry() + // The receipt updates only the journal; native location events own the live address. + const committed = props.initialHistory + if (journal && committed && committed !== historyBeforeOpen) { + const address = committed.urls[committed.index] + if (address) { + setHistory(journal.visitUrl(address)) + void captureHistory(address) + } + } + if (initialAddress && liveAddress() === addressBeforeOpen) setPathInput(initialAddress) + appliedInitialSource = initialUrl + appliedInitialAddress = initialAddress + return + } + if (initialOpenRequestId && appliedInitialSource === undefined) { appliedInitialSource = initialUrl; return } + if (pending) return + if (appliedInitialSource === initialUrl && (props.isolatedSource || appliedInitialAddress === initialAddress)) return + appliedInitialSource = initialUrl + appliedInitialAddress = initialAddress + observedFrameSource = undefined setFrameSrc(initialUrl) const address = initialAddress ?? getEditablePathFromUrl(initialUrl) + const source = props.isolatedSource ? initialUrl : address setPathInput(address) + if (props.isolatedSource && browserHost === "electron" && webviewReady && webviewRef) { + void window.electronAPI?.registerBrowserTarget?.({ sessionId: props.sessionId!, registrationId: browserRegistrationId, + guestWebContentsId: webviewRef.getWebContentsId(), logicalAddress: address, instanceId: props.instanceId || undefined }).catch(reportNativeError) + } // A redirect commits before dom-ready; do not reload it when its location // notification comes back through the preview props. - if (nativeMode() && webviewRef && (webviewReady ? webviewRef.getURL() : webviewObservedUrl) === address) return + if (nativeMode() && webviewRef && (webviewReady ? webviewRef.getURL() : webviewObservedUrl) === source) return const previousTarget = nativeTarget() - requestNativeTarget(address) + requestNativeTarget(source) const nextNativeMode = nativeBrowserAvailable - if (nextNativeMode && browserHost === "tauri" && tauriRegistered && previousTarget !== address) { - void controlTauriBrowserTarget(browserRegistrationId, "navigate", address).catch(reportNativeError) + if (nextNativeMode && browserHost === "tauri" && previousTarget !== source) { + void navigateTauri(source, props.isolatedSource ? address : undefined).catch(reportNativeError) } setNativeMode(nextNativeMode) }) @@ -766,13 +959,16 @@ export const BrowserFrame: Component = (props) => { cleanupTauriTarget?.() }) - const handleBack = (event: MouseEvent) => { + const handleBack = async (event: MouseEvent) => { event.preventDefault() event.stopPropagation() if (journal) { void traverseHistory(-1); return } - props.onNavigationStart?.() + const instanceId = props.instanceId + const preparing = startNavigation() + if (preparing) await preparing + if (!canNavigate(instanceId)) return if (nativeMode()) { - if (browserHost === "tauri") void controlTauriBrowserTarget(browserRegistrationId, "back").catch(reportNativeError) + if (browserHost === "tauri") actOnTauri("back") else if (webviewReady && webviewRef?.canGoBack()) webviewRef.goBack() return } @@ -787,23 +983,31 @@ export const BrowserFrame: Component = (props) => { if (!journal || historyBusy()) return const index = journal.value.index + offset if (index < 0 || index >= journal.value.urls.length) return - props.onNavigationStart?.() + setAddressDraft(undefined) + const instanceId = props.instanceId + const preparing = startNavigation() + pendingTauriNavigation = undefined setHistoryBusy(true) const version = ++historyTravelVersion ++historyRead // Fence reads started before this explicit traversal. try { + if (preparing) await preparing + if (disposed || version !== historyTravelVersion) return + if (!canNavigate(instanceId)) { setHistoryBusy(false); return } const native: NativeBrowserHistory = nativeMode() ? await readBrowserHistory(browserRegistrationId, historyGuestId()) : { entries: [], index: -1 } if (disposed || version !== historyTravelVersion) return - if (props.active === false) { setHistoryBusy(false); return } - const target = journal.request(index, native) + if (!canNavigate(instanceId)) { setHistoryBusy(false); return } + const target = journal.request(index, logicalHistory(native)) if (target.id !== undefined) await goToBrowserHistoryEntry(browserRegistrationId, target.id, historyGuestId()) else if (nativeMode()) { - if (browserHost === "tauri") await controlTauriBrowserTarget(browserRegistrationId, "navigate", target.url) - else if (webviewReady) await webviewRef?.loadURL(target.url) + const source = props.isolatedSource ? await props.onNavigate!(target.url) : target.url + if (disposed || version !== historyTravelVersion) return + if (browserHost === "tauri") await navigateTauri(source, props.isolatedSource ? target.url : undefined) + else if (webviewReady) await webviewRef?.loadURL(source) } else { const source = await props.onNavigate!(target.url) if (disposed || version !== historyTravelVersion) return - setFrameSrc(source) + loadFrameSource(source) publishHistory(journal.visitUrl(target.url)) } // Committed navigation/load events capture the result, not the early CDP @@ -816,11 +1020,24 @@ export const BrowserFrame: Component = (props) => { } } - const handleRefresh = () => { - props.onNavigationStart?.() + const initialOpenPending = () => Boolean(initialOpenRequestId && props.openRequestId === initialOpenRequestId) + const addressSubmissionBlocked = () => { + if (!initialOpenPending()) return false + const attached = openAcknowledgement() + const visible = visibleRegistration() + return !attached || !visible || attached.requestId !== props.openRequestId + || attached.id !== visible.id || attached.instanceId !== props.instanceId || visible.instanceId !== props.instanceId + } + const handleRefresh = async () => { + if (initialOpenPending()) return + const instanceId = props.instanceId supersedeHistoryTraversal() + const version = historyTravelVersion + const preparing = startNavigation() + if (preparing) await preparing + if (version !== historyTravelVersion || !canNavigate(instanceId)) return if (nativeMode()) { - if (browserHost === "tauri") void controlTauriBrowserTarget(browserRegistrationId, "reload").catch(reportNativeError) + if (browserHost === "tauri") actOnTauri("reload") else if (webviewReady) webviewRef?.reload() return } @@ -830,26 +1047,58 @@ export const BrowserFrame: Component = (props) => { } catch { // Fall back to resetting the iframe source if the frame cannot be reloaded directly. } + const source = props.isolatedSource ? observedFrameSource ?? frameSrc() : props.initialUrl setFrameSrc("about:blank") - requestAnimationFrame(() => setFrameSrc(props.initialUrl)) + requestAnimationFrame(() => { if (!props.isolatedSource || !disposed) setFrameSrc(source) }) + } + + const navigateIsolated = async (address: string) => { + if (navigating() || disposed) return + setNavigating(true) + try { + const target = normalizeBrowserPreviewUrl(address) + if (new URL(target).hostname.endsWith(".preview.localhost")) throw new Error(props.labels.invalidUrl ?? props.labels.path) + supersedeHistoryTraversal() + const version = historyTravelVersion + const source = await props.onNavigate!(target) + if (disposed || version !== historyTravelVersion) return + setPathInput(target) + if (journal) publishHistory(journal.visitUrl(target)) + if (nativeMode()) { + requestNativeTarget(source) + if (browserHost === "tauri") await navigateTauri(source, target) + } else { + loadFrameSource(source) + props.onFrameLocation?.(target) + } + } catch (error) { if (!disposed) reportNativeError(error) } + finally { if (!disposed) setNavigating(false) } } const handleGo = async (event?: Event) => { event?.preventDefault() + if (addressSubmissionBlocked()) return if (props.addressMode === "url" && props.onNavigate) { if (navigating()) return + if (props.isolatedSource) { await navigateIsolated(pathInput()); return } if (nativeBrowserAvailable) { try { const target = normalizeBrowserPreviewUrl(pathInput()) - props.onNavigationStart?.() + const submittedDraft = addressDraft() + const instanceId = props.instanceId supersedeHistoryTraversal() + const version = historyTravelVersion + const preparing = startNavigation() + if (preparing) await preparing + if (version !== historyTravelVersion || !canNavigate(instanceId)) return setPathInput(target) + setAddressDraft(current => current === submittedDraft ? undefined : current) if (nativeMode() && webviewReady && webviewRef?.getURL() === target) { webviewRef.reload() } else { requestNativeTarget(target) if (nativeMode() && browserHost === "tauri") { - void controlTauriBrowserTarget(browserRegistrationId, "navigate", target).catch(reportNativeError) + void navigateTauri(target).catch(reportNativeError) } else setNativeMode(true) } if (!journal) props.onFrameLocation?.(target) @@ -892,7 +1141,7 @@ export const BrowserFrame: Component = (props) => { - @@ -907,14 +1156,17 @@ export const BrowserFrame: Component = (props) => { style={{ background: "var(--surface-secondary)", color: "var(--text-primary)", border: "1px solid var(--border-base)" }} value={pathInput()} disabled={navigating()} - onInput={(event) => setPathInput(event.currentTarget.value)} + onInput={(event) => { + if (nativeBrowserAvailable && !props.isolatedSource) setAddressDraft(event.currentTarget.value) + else setPathInput(event.currentTarget.value) + }} spellcheck={false} autocomplete="off" autocorrect="off" autocapitalize="off" aria-label={props.labels.path} /> - @@ -977,7 +1229,10 @@ export const BrowserFrame: Component = (props) => { - {close => } + {close => { + setAddressDraft(undefined) + close()() + }} />}
= (props) => { }} referrerPolicy="same-origin" sandbox={framePolicy.sandbox} + allow="microphone 'none'; camera 'none'" onLoad={syncPathInputFromFrame} /> @@ -1005,6 +1261,7 @@ export const BrowserFrame: Component = (props) => { {/* Electron's shadow iframe needs its :host display:flex to fill the webview height. */} { + const handlers = new Map void>(), opens: Array<() => void> = [] + return { handlers, opens, serverEvents: { + on: (type: string, handler: (payload: any) => void) => { handlers.set(type, handler); return () => handlers.delete(type) }, + forInstance: () => ({ onOpen: (handler: () => void) => { opens.push(handler); return () => {} } }), + } } +} + +test("the provider manager rereads once for a catalog event that crossed its initial read", async () => { + const [loading, setLoading] = createSignal(true), events = listeners(), reads: string[] = [] + const effect = productionHandler(new URL("./provider-auth/provider-manager-modal.tsx", import.meta.url), "createEffect", { + createEffect, on, onCleanup, loading, isCatalogEvent, serverEvents: events.serverEvents, props: { instanceId: id, open: true }, + client: () => ({}), currentCatalogLocation: () => ({ directory: "/repo" }), loadVersion: 1, + captureBackendOperation: () => ({ current: () => true }), + loadProviderData: async () => { reads.push("read") }, + }, "isCatalogEvent") as () => void + let dispose!: () => void + createRoot(close => { dispose = close; createEffect(effect) }) + // The initial read answered before the plugin's models loaded; their event arrives meanwhile. + events.handlers.get("instance.event")!({ type: "instance.event", instanceId: id, event: { type: "model.updated" } }) + events.handlers.get("instance.event")!({ type: "instance.event", instanceId: id, event: { type: "provider.updated" } }) + assert.deepEqual(reads, [], "no overlapping read") + setLoading(false) + await Promise.resolve() + assert.deepEqual(reads, ["read"], "one trailing reread after the initial read") + dispose() +}) + +test("Mission profile pickers invalidate on model and provider updates", () => { + const invalidations: string[] = [], events = listeners() + productionHandler(new URL("./mission-profile-controls.tsx", import.meta.url), "events", { + props: { instanceId: id }, isCatalogEvent, invalidate: () => invalidations.push("invalidate"), serverEvents: events.serverEvents, + }) + const handler = events.handlers.get("instance.event")! + for (const type of ["model.updated", "provider.updated", "plugin.updated", "session.updated"]) + handler({ type: "instance.event", instanceId: id, event: { type } }) + handler({ type: "instance.event", instanceId: "other", event: { type: "model.updated" } }) + assert.equal(invalidations.length, 3) +}) diff --git a/packages/ui/src/components/directory-browser-dialog.tsx b/packages/ui/src/components/directory-browser-dialog.tsx index 776271c58d..6f82503b35 100644 --- a/packages/ui/src/components/directory-browser-dialog.tsx +++ b/packages/ui/src/components/directory-browser-dialog.tsx @@ -490,7 +490,7 @@ const DirectoryBrowserDialog: Component = (props) =
{error()}}>
- + {t("directoryBrowser.loadingFolders")}
@@ -543,7 +543,7 @@ const DirectoryBrowserDialog: Component = (props) = {entry.name || entry.path}
- + {isSelectable ? ( diff --git a/packages/ui/src/components/entry-count.tsx b/packages/ui/src/components/entry-count.tsx new file mode 100644 index 0000000000..58c573a2b9 --- /dev/null +++ b/packages/ui/src/components/entry-count.tsx @@ -0,0 +1,7 @@ +import { useI18n } from "../lib/i18n" + +/** An empty tab's section counter. */ +export default function EntryCount(props: { count: number }) { + const { t } = useI18n() + return

{t(props.count === 1 ? "newTab.items.one" : "newTab.items.other", { count: props.count })}

+} diff --git a/packages/ui/src/components/file-viewer/monaco-file-viewer.tsx b/packages/ui/src/components/file-viewer/monaco-file-viewer.tsx index 4f52320025..a8d25ddb6e 100644 --- a/packages/ui/src/components/file-viewer/monaco-file-viewer.tsx +++ b/packages/ui/src/components/file-viewer/monaco-file-viewer.tsx @@ -114,7 +114,7 @@ export function MonacoFileViewer(props: MonacoFileViewerProps) { createEffect(() => { if (!ready() || !editor) return - editor.updateOptions({ wordWrap: props.wordWrap === "on" ? "on" : "off" }) + editor.updateOptions({ wordWrap: props.wordWrap === "on" ? "on" : "off", readOnly: props.readOnly ?? false }) }) createEffect(() => { diff --git a/packages/ui/src/components/folder-selection-view.tsx b/packages/ui/src/components/folder-selection-view.tsx index 6068864ac6..ea98b45914 100644 --- a/packages/ui/src/components/folder-selection-view.tsx +++ b/packages/ui/src/components/folder-selection-view.tsx @@ -1,7 +1,20 @@ -import { Component, createSignal, Show, For, onMount, onCleanup, createEffect } from "solid-js" -import { Folder, Clock, Trash2, FolderPlus, Settings, ChevronRight, MonitorUp, Star, X, Globe, Loader2, GitBranch, Pencil, Hourglass } from "lucide-solid" +import { Component, createMemo, createSignal, Show, For, onMount, onCleanup, createEffect, on } from "solid-js" +import { Trash2, FolderPlus, Star, Pencil, Laptop, Server, Heart, Hourglass, GitBranch } from "lucide-solid" import { useConfig } from "../stores/preferences" -import { isHotkeyRecording, matchesHotkey, withHotkey } from "../lib/hotkeys" +import type { RemoteServerBrowseResponse, RemoteServerProfile } from "../../../server/src/api-types" +import { sameServerSelection, type ServerSelectionIntent } from "../lib/native/server-selection-intent" +import { qualifiedServerDisplayName } from "../lib/codenomad-link" +import { captureRequestFocus } from "../lib/request-focus" +import BrowseMenu, { createBrowseEntryCount } from "./browse-menu" +import EntryCount from "./entry-count" +import RemoteRecentSession from "./remote-recent-session" +import ActionOverflowMenu from "./action-overflow-menu" +import { Tooltip } from "@kobalte/core/tooltip" +import { joinRecentOpenTarget, recentAccessibleName, recentOpenElsewhere, recentOpenTarget, launchableRecents, type LaunchableRecent } from "../lib/recent-open-target" +import RecentOpenElsewhere, { RecentOpenElsewhereTooltip } from "./recent-open-elsewhere" +import { helpUrl } from "../lib/help-url" +import RecentTabIcon from "./recent-tab-icon" +import { isHotkeyRecording, matchesHotkey } from "../lib/hotkeys" import ProjectRenameDialog from "./project-rename-dialog" import { useFolderDrop } from "../lib/hooks/use-folder-drop" import VersionPill from "./version-pill" @@ -11,60 +24,108 @@ import { githubStars } from "../stores/github-stars" import { formatCompactCount } from "../lib/formatters" import { useI18n } from "../lib/i18n" import { showAlertDialog } from "../stores/alerts" -import { openSettings, settingsOpen } from "../stores/settings-screen" +import { settingsOpen } from "../stores/settings-screen" import { openExternalUrl } from "../lib/external-url" -import { canOpenRemoteWindows } from "../lib/runtime-env" -import { getExistingInstanceForFolder } from "../stores/instances" +import { browsedRemoteRecents, remoteRecentProjectsUsable, removeRecentProject, renameRecentProject, type RecentProject, type RemoteRecentProject } from "../stores/recent-projects" import { renameProject } from "../stores/project-names" -import { LocaleSelector } from "./locale-selector" import { createNewInstanceDialogs } from "./new-instance-dialogs" -import { useRemoteServerProfiles } from "../lib/hooks/use-remote-server-profiles" -import { getServerMeta, localRequest, sidecarsAllowed } from "../lib/server-meta" import { formatRelativeTime, getDisplayPath, getProjectDisplayName } from "../lib/recent-folder-display" const GITHUB_URL = "https://github.com/NeuralNomadsAI/CodeNomad" const DISCORD_URL = "https://discord.com/channels/1391832426048651334/1458412028325793887/1464701235683917945" -type HomeTab = "local" | "servers" - - interface FolderSelectionViewProps { onSelectFolder: (folder: string) => void onSelectExistingInstance: (instanceId: string, recentPath: string) => void /** Creates a new temporary instance; open ones come back with the restored tabs. */ onNewTemporaryInstance?: () => void - onOpenSidecar?: () => void isLoading?: boolean - onClose?: () => void + initialServer?: ServerSelectionIntent + active?: boolean + onOpenSidecar?: (id: string) => void + onJoined?: () => void + onRemoteOpened?: (instanceId: string) => void } const FolderSelectionView: Component = (props) => { - const { - recentFolders, - removeRecentFolder, - } = useConfig() - const { remoteServers, connectingServerId, saveServer, connectSavedServer, removeRemoteServerProfile } = useRemoteServerProfiles() - const { t } = useI18n() + const { remoteServers } = useConfig() + const { t, locale } = useI18n() + const [remoteSource, setRemoteSource] = createSignal<{ profile: RemoteServerProfile; listing?: RemoteServerBrowseResponse }>() + const browseEntryCount = createBrowseEntryCount() const [selectedIndex, setSelectedIndex] = createSignal(0) + const [connectingRecent, setConnectingRecent] = createSignal() const [hoveredRecentActionPath, setHoveredRecentActionPath] = createSignal(null) const [focusedRecentActionPath, setFocusedRecentActionPath] = createSignal(null) - const [focusMode, setFocusMode] = createSignal<"recent" | "new" | null>("recent") - const [renameProjectTarget, setRenameProjectTarget] = createSignal<{ path: string; name: string; label: string } | null>(null) + const [highlightRecent, setHighlightRecent] = createSignal(false) + const [renameProjectTarget, setRenameProjectTarget] = createSignal<{ recent: RecentProject; name: string } | null>(null) const [isRenamingProject, setIsRenamingProject] = createSignal(false) - const [activeTab, setActiveTab] = createSignal("local") - let homeRootRef: HTMLDivElement | undefined - let actionsColumnRef: HTMLDivElement | undefined + const sourcePolicy = createMemo(() => remoteSource()?.profile, undefined, { + equals: (a, b) => a === b || !!a && !!b && sameServerSelection(a, b), + }) + createEffect(on([() => props.active, sourcePolicy], () => setConnectingRecent(undefined), { defer: true })) + createEffect(() => { if (!remoteRecentProjectsUsable()) setConnectingRecent(undefined) }) + let rootRef: HTMLDivElement | undefined let recentListRef: HTMLDivElement | undefined + let releaseBrowseHeight: (() => void) | undefined + onCleanup(() => releaseBrowseHeight?.()) + + function holdBrowseHeight(event: PointerEvent & { currentTarget: HTMLElement }) { + if (!event.isPrimary || event.button !== 0 || !(event.target instanceof Element) + || !event.target.closest(".browse-menu-footer button[type=submit]:enabled")) return + const panel = event.currentTarget + const grid = panel.parentElement + if (!grid || !matchMedia("(max-width: 639px)").matches) return + releaseBrowseHeight?.() + // Keep native hit testing stable while async rows change either stacked panel. + grid.style.setProperty("--folder-home-pressed-browse-height", `${panel.getBoundingClientRect().height}px`) + const listeners = new AbortController() + const options = { capture: true, signal: listeners.signal } + let clickDeadline: number | undefined + const release = releaseBrowseHeight = () => { + window.clearTimeout(clickDeadline) + listeners.abort() + grid.style.removeProperty("--folder-home-pressed-browse-height") + releaseBrowseHeight = undefined + } + const finish = (end: PointerEvent) => { + if (end.pointerId !== event.pointerId) return + if (end.type === "pointercancel" || event.pointerType === "mouse") return release() + // Touch hit-tests the synthesized click after pointerup. A non-clicking release still unpins. + window.addEventListener("click", click => { + if (click.isTrusted && click.detail > 0 && (!(click instanceof PointerEvent) || click.pointerId === event.pointerId)) release() + }, options) + clickDeadline = window.setTimeout(release, 400) + } + window.addEventListener("pointerup", finish, options) + window.addEventListener("pointercancel", finish, options) + window.addEventListener("blur", release, { signal: listeners.signal }) + } - const folders = () => recentFolders() - const serverList = () => remoteServers() + createEffect(on(() => props.active === true, (active) => { + if (!active) return + const focus = captureRequestFocus() + let cancelled = false + onCleanup(() => { cancelled = true; focus.dispose() }) + requestAnimationFrame(() => { + if (!cancelled && props.active && focus.retained()) { + const first = rootRef?.querySelector('[data-list-index="0"]') ?? rootRef?.querySelector("[data-browse-nav]") + first?.focus({ preventScroll: true }) + } + focus.dispose() + }) + })) + + // This computer's folders, the remote projects this window reopens and SideCars, newest first. + const allRecents = createMemo(() => { + const source = remoteSource() + const rows = source ? browsedRemoteRecents(source.profile, source.listing?.recents ?? []) : launchableRecents() + const opening = connectingRecent() + // The row owns the request until selection; a refreshed timestamp must not replace it. + return opening ? rows.map(row => row.kind === "remote" && row.key === opening.key && sameServerSelection(row.policy, opening.policy) ? opening : row) : rows + }) + const recentsAvailable = () => !remoteSource() || !!remoteSource()?.listing + const folders = allRecents const isLoading = () => Boolean(props.isLoading) - const canUseRemoteServerWindows = () => localRequest() && canOpenRemoteWindows() - onMount(() => { void getServerMeta().catch(() => {}) }) - - function getActiveListLength() { - return activeTab() === "local" ? folders().length : serverList().length - } function scrollToIndex(index: number) { const container = recentListRef @@ -72,23 +133,18 @@ const FolderSelectionView: Component = (props) => { const element = container.querySelector(`[data-list-index="${index}"]`) as HTMLElement | null if (!element) return - const containerRect = container.getBoundingClientRect() - const elementRect = element.getBoundingClientRect() - - if (elementRect.top < containerRect.top) { - container.scrollTop -= containerRect.top - elementRect.top - } else if (elementRect.bottom > containerRect.bottom) { - container.scrollTop += elementRect.bottom - containerRect.bottom - } + element.focus() + element.scrollIntoView({ block: "nearest" }) } function handleKeyDown(e: KeyboardEvent) { - if (e.defaultPrevented || e.isComposing || isHotkeyRecording()) return + if (props.active === false || e.defaultPrevented || e.isComposing || isHotkeyRecording()) return let activeElement: HTMLElement | null = null if (typeof document !== "undefined") { activeElement = document.activeElement as HTMLElement | null } + if (activeElement && activeElement !== document.body && !rootRef?.contains(activeElement)) return const insideModal = activeElement?.closest(".modal-surface") || activeElement?.closest("[role='dialog']") const isEditingField = activeElement && @@ -116,46 +172,47 @@ const FolderSelectionView: Component = (props) => { } if (isInteractiveControl && (e.key === "Enter" || e.key === " ")) return + if (activeElement?.closest(".browse-menu, [data-remote-view-session]")) return - const listLength = getActiveListLength() + const listLength = folders().length if (listLength === 0) return if (e.key === "ArrowDown") { e.preventDefault() - const newIndex = Math.min(selectedIndex() + 1, listLength - 1) + const newIndex = (selectedIndex() + 1) % listLength setSelectedIndex(newIndex) - setFocusMode("recent") + setHighlightRecent(true) scrollToIndex(newIndex) } else if (e.key === "ArrowUp") { e.preventDefault() - const newIndex = Math.max(selectedIndex() - 1, 0) + const newIndex = (selectedIndex() - 1 + listLength) % listLength setSelectedIndex(newIndex) - setFocusMode("recent") + setHighlightRecent(true) scrollToIndex(newIndex) } else if (e.key === "PageDown") { e.preventDefault() const pageSize = 5 const newIndex = Math.min(selectedIndex() + pageSize, listLength - 1) setSelectedIndex(newIndex) - setFocusMode("recent") + setHighlightRecent(true) scrollToIndex(newIndex) } else if (e.key === "PageUp") { e.preventDefault() const pageSize = 5 const newIndex = Math.max(selectedIndex() - pageSize, 0) setSelectedIndex(newIndex) - setFocusMode("recent") + setHighlightRecent(true) scrollToIndex(newIndex) } else if (e.key === "Home") { e.preventDefault() setSelectedIndex(0) - setFocusMode("recent") + setHighlightRecent(true) scrollToIndex(0) } else if (e.key === "End") { e.preventDefault() const newIndex = listLength - 1 setSelectedIndex(newIndex) - setFocusMode("recent") + setHighlightRecent(true) scrollToIndex(newIndex) } else if (e.key === "Enter") { e.preventDefault() @@ -166,34 +223,12 @@ const FolderSelectionView: Component = (props) => { function handleEnterKey() { if (isLoading()) return - const index = selectedIndex() - - if (activeTab() === "local") { - const folder = folders()[index] - if (folder) { - handleFolderSelect(folder.path) - } - return - } - - const server = serverList()[index] - if (server) { - void connectSavedServer(server.id) - } + const folder = folders()[selectedIndex()] + if (folder) openRecent(folder) } createEffect(() => { - activeTab() - if (!canUseRemoteServerWindows() && activeTab() !== "local") { - setActiveTab("local") - return - } - setSelectedIndex(0) - setFocusMode("recent") - }) - - createEffect(() => { - const length = getActiveListLength() + const length = folders().length if (length === 0) { setSelectedIndex(0) return @@ -212,30 +247,8 @@ const FolderSelectionView: Component = (props) => { }) }) - onMount(() => { - const syncActionsHeight = () => { - if (!homeRootRef || !actionsColumnRef) return - const height = actionsColumnRef.getBoundingClientRect().height - homeRootRef.style.setProperty("--folder-home-actions-height", `${Math.ceil(height)}px`) - } - - syncActionsHeight() - window.addEventListener("resize", syncActionsHeight) - - let observer: ResizeObserver | undefined - if (typeof ResizeObserver !== "undefined" && actionsColumnRef) { - observer = new ResizeObserver(syncActionsHeight) - observer.observe(actionsColumnRef) - } - - onCleanup(() => { - window.removeEventListener("resize", syncActionsHeight) - observer?.disconnect() - }) - }) - function dropTargetBlocked() { - return isLoading() || dialogs.isFolderBrowserOpen() || settingsOpen() + return props.active === false || isLoading() || dialogs.isFolderBrowserOpen() || settingsOpen() } function showInvalidFolderDropAlert() { @@ -264,9 +277,11 @@ const FolderSelectionView: Component = (props) => { props.onSelectFolder(path) } - function handleExistingInstanceSelect(instanceId: string, recentPath: string) { + function openRecent(folder: LaunchableRecent) { if (isLoading()) return - props.onSelectExistingInstance(instanceId, recentPath) + if (folder.kind === "sidecar") props.onOpenSidecar?.(folder.path) + else if (folder.kind === "remote") setConnectingRecent(folder) + else handleFolderSelect(folder.path) } function setRecentActionHovered(path: string, active: boolean) { @@ -277,34 +292,32 @@ const FolderSelectionView: Component = (props) => { setFocusedRecentActionPath((current) => active ? path : current === path ? null : current) } - function clearRecentActionState(path: string) { - setRecentActionHovered(path, false) - setRecentActionFocused(path, false) - } - const dialogs = createNewInstanceDialogs({ - defaultPath: () => folders()[0]?.path, + defaultPath: () => launchableRecents().find(folder => folder.kind === "local")?.path, isLoading, onSelectFolder: handleFolderSelect, - onSaveServer: saveServer, }) - const openCloneDialog = () => dialogs.clone() - - function openServerDialog() { - if (canUseRemoteServerWindows()) dialogs.addServer() - } + const RecentSource = () => + + + }>{(source) => <> +
+ }} + +
+ + +
@@ -852,7 +611,7 @@ const FolderSelectionView: Component = (props) => { {}) setLoading(true) setError(null) try { - const result = await previewReads.run<{ before: string; after: string; isBinary?: boolean; image?: GitImageDiff }>(request.signal, () => target.commit - ? serverApi.fetchGitCommitDiff(props.instanceId, target.slug, target.commit, target.path, request.signal) - : serverApi.fetchWorktreeGitDiff(props.instanceId, target.slug, { + const result = await previewReads.run<{ before: string; after: string; isBinary?: boolean; image?: GitImageDiff }>(signal, () => target.commit + ? backendOf(props.instanceId).api.fetchGitCommitDiff(props.instanceId, target.slug, target.commit, target.path, signal) + : backendOf(props.instanceId).api.fetchWorktreeGitDiff(props.instanceId, target.slug, { path: target.path, originalPath: target.originalPath, scope: target.scope ?? "unstaged", - }, request.signal), "visible") - if (request.signal.aborted) return + }, signal), "visible") + if (!operation.current()) return if (result.isBinary && !result.image) { setContent(null); setError(t("instanceShell.gitChanges.binaryViewer")) } else setContent(result) } catch (cause) { - if (!request.signal.aborted) setError(cause instanceof Error ? cause.message : String(cause)) + if (operation.current()) setError(cause instanceof Error ? cause.message : String(cause)) } finally { if (controller === request) { setLoading(false) - if (pending) { pending = false; void load() } + if (pending && operation.current()) { pending = false; void load() } } } } @@ -82,6 +87,10 @@ export function GitDiffView(props: { instanceId: string; target: FilePreviewTarg void load() })) createEffect(on(() => props.active, active => { if (!active) cancel(); else void load() }, { defer: true })) + createEffect(on(() => backendEvents.signalForInstance(props.instanceId), signal => { + cancel() + if (!signal.aborted) void load() + }, { defer: true })) const refresh = createDebouncedRefresh(() => void load()) createEffect(on(() => filesystemInvalidationVersion(props.instanceId), () => { if (props.active && !props.target.commit) refresh.trigger() diff --git a/packages/ui/src/components/hidden-text.tsx b/packages/ui/src/components/hidden-text.tsx index 158862c332..8ad943993e 100644 --- a/packages/ui/src/components/hidden-text.tsx +++ b/packages/ui/src/components/hidden-text.tsx @@ -8,6 +8,7 @@ import { type TextSource, } from "../lib/render-text-window" import { + getRecordPartSearchReveal, getRevealedRecordText, revealHiddenRecordText, type RecordTextRevealTarget, @@ -36,7 +37,10 @@ export function createTextWindow(options: { const [localSteps, setLocalSteps] = createSignal(0) const steps = () => { const target = options.target() - return target ? getRevealedRecordText(target) : localSteps() + if (!target) return localSteps() + // Search navigation reveals the whole part once; the reader's own reveals + // stack on top of that base step. + return getRevealedRecordText(target) + getRecordPartSearchReveal(target.instanceId, target.messageId, target.partId) } const window = createMemo(() => getRenderTextWindow(options.source(), options.limit(), steps()), undefined, { equals: sameWindow }) const reveal = () => { diff --git a/packages/ui/src/components/history-message-preview.tsx b/packages/ui/src/components/history-message-preview.tsx index 94814bb1a2..687e72a3a0 100644 --- a/packages/ui/src/components/history-message-preview.tsx +++ b/packages/ui/src/components/history-message-preview.tsx @@ -1,5 +1,6 @@ import { For, Show, createEffect, createMemo, createSignal, onCleanup } from "solid-js" import { useI18n } from "../lib/i18n" +import { captureBackendOperation } from "../lib/backend-operation" import { formatRelativeTime } from "../lib/recent-folder-display" import { openHistoryMatchSession } from "../stores/history-search-sessions" import { getRootClient } from "../stores/opencode-client" @@ -29,16 +30,18 @@ export default function HistoryMessagePreview(props: { instanceId: string; sessi const generation = getOpenCodeInstanceGeneration(instanceId) const revision = getOpenCodeMutationRevision(instanceId, sessionID) const controller = new AbortController() - const current = () => !controller.signal.aborted && generation === getOpenCodeInstanceGeneration(instanceId) + const operation = captureBackendOperation(instanceId, controller.signal) + const current = () => operation.current() && generation === getOpenCodeInstanceGeneration(instanceId) && revision === getOpenCodeMutationRevision(instanceId, sessionID) target += 1 setTitle(""); setDirectory(undefined); setCreated(undefined); setBlocks([]); setFailed(false); setPending(true) setOpening(false); setOpenFailed(false) void (async () => { + if (!current()) return const client = getRootClient(instanceId) const [session, message] = await Promise.all([ - client.session.get({ sessionID }, { signal: controller.signal }), - client.session.message.get({ sessionID, messageID }, { signal: controller.signal }), + client.session.get({ sessionID }, { signal: operation.signal }), + client.session.message.get({ sessionID, messageID }, { signal: operation.signal }), ]) if (!current()) return setTitle(session.title ?? sessionID) @@ -54,17 +57,19 @@ export default function HistoryMessagePreview(props: { instanceId: string; sessi else if (message.type === "shell") setBlocks([message.command, message.output?.output ?? ""]) else if (message.type === "compaction" && "summary" in message) setBlocks([message.summary]) })().catch(() => { if (current()) setFailed(true) }) - .finally(() => { if (current()) setPending(false) }) - onCleanup(() => controller.abort()) + .finally(() => { if (!controller.signal.aborted) setPending(false) }) + onCleanup(() => { controller.abort(); setPending(false) }) }) async function open() { const opened = target - const current = () => opened === target + const operation = captureBackendOperation(props.instanceId) + const current = () => operation.current() && opened === target + if (!current()) return setOpening(true) setOpenFailed(false) const result = await openHistoryMatchSession(props.instanceId, props.sessionId, props.messageId, current, props.highlight).catch(() => false) + if (opened === target) setOpening(false) if (!current()) return - setOpening(false) setOpenFailed(!result) } return
diff --git a/packages/ui/src/components/info-popover-button.tsx b/packages/ui/src/components/info-popover-button.tsx index d4a52ace5b..170fc4a4e9 100644 --- a/packages/ui/src/components/info-popover-button.tsx +++ b/packages/ui/src/components/info-popover-button.tsx @@ -1,19 +1,27 @@ import { Popover } from "@kobalte/core/popover" import { Info } from "lucide-solid" -import type { JSX } from "solid-js" +import { createSignal, type JSX } from "solid-js" /** * The shared "i" button: a short accessible name; Enter or Space opens its text, Escape closes it and returns focus * to the button. `label` and `children` may be catalogue text, which never passes through the i18n catalogue. */ export function InfoPopoverButton(props: { label: string; children: JSX.Element; class?: string }) { + const [open, setOpen] = createSignal(false) + const dismissOnEscape = (event: KeyboardEvent) => { + if (event.key !== "Escape" || event.defaultPrevented || event.isComposing || !open()) return + event.preventDefault() + event.stopPropagation() + setOpen(false) + } return ( - - + + - diff --git a/packages/ui/src/components/instance-service-status.tsx b/packages/ui/src/components/instance-service-status.tsx index d08c82faad..aef98c57ab 100644 --- a/packages/ui/src/components/instance-service-status.tsx +++ b/packages/ui/src/components/instance-service-status.tsx @@ -3,6 +3,8 @@ import Switch from "@suid/material/Switch" import type { Instance, RawMcpStatus } from "../types/instance" import { useOptionalInstanceMetadataContext } from "../lib/contexts/instance-metadata-context" import { useI18n } from "../lib/i18n" +import { captureBackendOperation } from "../lib/backend-operation" +import { getRootClient } from "../stores/opencode-client" import { getLogger } from "../lib/logger" import { PluginActivationControls } from "./plugin-activation-controls" import { createIntegrationContext } from "./integration-context" @@ -68,6 +70,7 @@ const InstanceServiceStatus: Component = (props) => const [pendingMcpActions, setPendingMcpActions] = createSignal>({}) + const pendingMcpOwners = new Map() const setPendingMcpAction = (name: string, action?: "connect" | "disconnect") => { setPendingMcpActions((prev) => { @@ -79,25 +82,32 @@ const InstanceServiceStatus: Component = (props) => } const toggleMcpServer = async (serverName: string, shouldEnable: boolean) => { - const client = instance().client - if (!client?.mcp) return + const operation = captureBackendOperation(instance().id) + if (!operation.current()) return + const instanceId = instance().id + if (!instance().client) return const action: "connect" | "disconnect" = shouldEnable ? "connect" : "disconnect" + pendingMcpOwners.set(serverName, operation) setPendingMcpAction(serverName, action) try { + const client = getRootClient(instanceId) const resolved = metadata()?.mcpStatus?.location const location = resolved ? { directory: resolved.directory } : { directory: instance().folder } if (shouldEnable) { - await client.mcp.connect({ server: serverName, location }) + await client.experimental.mcp.connect({ server: serverName, location }, { signal: operation.signal }) } else { - await client.mcp.disconnect({ server: serverName, location }) + await client.experimental.mcp.disconnect({ server: serverName, location }, { signal: operation.signal }) } - await refreshMetadata() + if (operation.current()) await refreshMetadata() } catch (error) { log.error("Failed to toggle MCP server", { serverName, action, error }) } finally { - setPendingMcpAction(serverName) + if (pendingMcpOwners.get(serverName) === operation) { + pendingMcpOwners.delete(serverName) + setPendingMcpAction(serverName) + } } } @@ -140,14 +150,14 @@ const InstanceServiceStatus: Component = (props) =>
- + - +
diff --git a/packages/ui/src/components/instance-tab.tsx b/packages/ui/src/components/instance-tab.tsx index 4c9909afd3..a96399d13e 100644 --- a/packages/ui/src/components/instance-tab.tsx +++ b/packages/ui/src/components/instance-tab.tsx @@ -1,13 +1,16 @@ import { ContextMenu } from "@kobalte/core/context-menu" -import { Component, Show, createMemo, createSignal, onCleanup } from "solid-js" +import { Component, Show, createMemo, createUniqueId } from "solid-js" import type { Instance } from "../types/instance" -import { getInstanceIdleFadeClass, getInstanceSessionIndicatorStatus } from "../stores/session-status" -import { FolderCheck, FolderOpen, Hourglass, Pencil, ShieldAlert, X } from "lucide-solid" +import { getInstanceStatusPresentation } from "../stores/session-status" +import { createDeadlineMemo } from "../lib/deadline-memo" +import { Activity, FolderCheck, FolderOpen, Hourglass, Pencil, Server, ShieldAlert, X } from "lucide-solid" import { useI18n } from "../lib/i18n" import { useConfig } from "../stores/preferences" import { keepTemporaryInstance } from "../stores/temporary-instances" import { withHotkey, matchesHotkey } from "../lib/hotkeys" import { getInstanceLabel } from "../lib/instance-label" +import { backendIdOf } from "../lib/backend-identity" +import { qualifiedServerDisplayName } from "../lib/codenomad-link" interface InstanceTabProps { instance: Instance @@ -20,24 +23,18 @@ interface InstanceTabProps { const InstanceTab: Component = (props) => { const { t } = useI18n() - const { preferences } = useConfig() - const [now, setNow] = createSignal(Date.now()) - - if (typeof window !== "undefined") { - const timer = window.setInterval(() => setNow(Date.now()), 1000) - onCleanup(() => window.clearInterval(timer)) - } - - const aggregatedStatus = createMemo(() => - getInstanceSessionIndicatorStatus(props.instance.id, now(), preferences().keepUnseenSubagentIdleStatus), + const { preferences, remoteServers } = useConfig() + const statusId = createUniqueId() + const statusPresentation = createDeadlineMemo((now, wakeAt) => + getInstanceStatusPresentation(props.instance.id, now, preferences().keepUnseenSubagentIdleStatus, wakeAt), ) + const aggregatedStatus = () => statusPresentation().status const statusClassName = createMemo(() => { const status = aggregatedStatus() if (!status) return null if (status === "permission") return "session-permission" const base = `session-${status}` - const fadeClass = - status === "idle" ? getInstanceIdleFadeClass(props.instance.id, now(), preferences().keepUnseenSubagentIdleStatus) : "" + const fadeClass = statusPresentation().fade return fadeClass ? `${base} ${fadeClass}` : base }) const statusTitle = createMemo(() => { @@ -54,7 +51,14 @@ const InstanceTab: Component = (props) => { return null } }) - const tabLabel = createMemo(() => getInstanceLabel(props.instance)) + const serverName = createMemo(() => { + const id = backendIdOf(props.instance) + if (id === "local") return + const profile = remoteServers().find(p => p.id === id) + return profile ? qualifiedServerDisplayName(profile, remoteServers()) : id + }) + const tabLabel = createMemo(() => getInstanceLabel(props.instance) || serverName() || "") + const remoteDetail = () => serverName() ? `${tabLabel()} · ${serverName()} · ${props.instance.folder}` : undefined const requestRename = () => props.onRename(tabLabel()) // The menu restores focus to the tab when it closes; open the dialog after // that so the dialog keeps focus on its input. @@ -76,12 +80,16 @@ const InstanceTab: Component = (props) => { event.stopPropagation() requestRename() }} - title={props.instance.temporary ? t("instanceTab.temporary.title") : props.instance.folder} + title={remoteDetail() ?? (props.instance.temporary ? t("instanceTab.temporary.title") : props.instance.folder)} + aria-label={remoteDetail()} + aria-describedby={statusTitle() ? statusId : undefined} role="tab" aria-selected={props.active} > - }> - + {tabLabel()} @@ -90,14 +98,17 @@ const InstanceTab: Component = (props) => { void onClose: (tabId: string) => void - onRename: (folder: string, label: string) => void + onRename: (folder: string, label: string, backendId?: BackendId) => void } const AppTabContent: Component = (props) => { const { t } = useI18n() + const { remoteServers } = useConfig() + const snapshot = () => props.tab.kind === "remote-restore" ? props.tab.snapshot : undefined + const server = () => { + const saved = snapshot() + if (!saved) return + const id = backendIdOf(saved) + if (id === LOCAL_BACKEND_ID) return + const profile = remoteServers().find(entry => entry.id === id) + return profile ? qualifiedServerDisplayName(profile, remoteServers()) : id + } + const restoreLabel = () => getInstanceLabel(snapshot()!) || server() + const remoteDetail = () => server() ? `${restoreLabel()} · ${server()} · ${snapshot()!.folder}` : undefined return ( <> {props.tab.kind === "instance" ? ( @@ -51,7 +69,7 @@ const AppTabContent: Component = (props) => { active={props.tab.id === props.activeTabId} onSelect={() => props.onSelect(props.tab.id)} onClose={() => props.onClose(props.tab.id)} - onRename={(label) => props.tab.kind === "instance" && props.onRename(props.tab.instance.folder, label)} + onRename={(label) => props.tab.kind === "instance" && props.onRename(props.tab.instance.folder, label, props.tab.instance.backendId)} /> ) : (
= (props) => { role="tab" tabIndex={0} aria-selected={props.tab.id === props.activeTabId} + aria-label={remoteDetail()} + title={remoteDetail()} onClick={() => props.onSelect(props.tab.id)} onKeyDown={(event) => { if (event.key !== "Enter" && event.key !== " ") return @@ -67,7 +87,9 @@ const AppTabContent: Component = (props) => { }} > - {props.tab.sidecarTab.name} + + {props.tab.kind === "sidecar" ? props.tab.sidecarTab.name + : props.tab.kind === "blank" ? t("newTab.title") : restoreLabel()}
- - - +
diff --git a/packages/ui/src/components/instance-welcome-view.tsx b/packages/ui/src/components/instance-welcome-view.tsx index 5c1b57779e..c3ce4f2b0d 100644 --- a/packages/ui/src/components/instance-welcome-view.tsx +++ b/packages/ui/src/components/instance-welcome-view.tsx @@ -19,7 +19,7 @@ const InstanceWelcomeView: Component = (props) => { >
  • -
diff --git a/packages/ui/src/components/instance/instance-shell2.tsx b/packages/ui/src/components/instance/instance-shell2.tsx index a2d935bdcc..9eb9f61b3b 100644 --- a/packages/ui/src/components/instance/instance-shell2.tsx +++ b/packages/ui/src/components/instance/instance-shell2.tsx @@ -29,6 +29,7 @@ import { MissionReader } from "../mission-reader" import { missionProjectView } from "../../stores/mission-view-state" import MessageSection from "../message-section" import PromptAttachmentsBar from "../prompt-input/PromptAttachmentsBar" +import RecoveredDrafts from "../prompt-input/recovered-drafts" import { formatTokenTotal } from "../../lib/formatters" import ContextMeter from "../context-meter" import ActionOverflowMenu, { type ActionOverflowMenuItem } from "../action-overflow-menu" @@ -38,6 +39,8 @@ import { getLogger } from "../../lib/logger" import PromptInput from "../prompt-input" import PromptContextControls from "../prompt-input/PromptContextControls" import { useI18n } from "../../lib/i18n" +import { captureBackendOperation } from "../../lib/backend-operation" +import { projectScope } from "../../lib/backend-identity" import { hotkeyLabel, withHotkey } from "../../lib/hotkeys" import { getInterruptionQueue } from "../../stores/interruption-scope" import SessionSidebar from "./shell/SessionSidebar" @@ -48,19 +51,18 @@ import { useDrawerChrome } from "./shell/useDrawerChrome" import { useFilePreviewLifetime } from "./shell/file-preview-lifetime" import ShellPanelToggle from "./shell/ShellPanelToggle" import { useSessionNavigationHistory } from "./shell/useSessionNavigationHistory" -import { getRetrySeconds, getSessionIdleFadeClass, getSessionRetry, getSessionStatus, shouldShowSessionStatus } from "../../stores/session-status" +import { getRetrySeconds, idleFadeClassForSession, shouldShowSessionStatusForRow } from "../../stores/session-status" +import { createDeadlineMemo } from "../../lib/deadline-memo" import { Command as CommandIcon, Globe, ListFilter, Maximize2, Search, ShieldAlert } from "lucide-solid" import type { PromptInputApi } from "../prompt-input/types" import type { Attachment } from "../../types/attachment" import { setAgentModelPreference, useConfig } from "../../stores/preferences" import { showAlertDialog } from "../../stores/alerts" import { - DEFAULT_PREVIEW_URL, getSessionPreview, - openSessionPreview, - restoreSessionPreview, + previewBlockedByOwner, + requestSessionPreview, showSessionChatFor, - showSessionPreview, setPreviewSessionOwners, } from "../../stores/session-previews" import { clearSelectedSession, createSession, executeCustomCommand, getDefaultModel, providers, runShellCommand, sendMessage, setActiveParentSession, updateSessionModel } from "../../stores/sessions" @@ -85,10 +87,9 @@ import { useDrawerResize } from "./shell/useDrawerResize" import { clampEmbeddedDrawerWidth } from "./shell/drawer-layout" import { useSessionCache } from "./shell/useSessionCache" import { useInstanceSessionContext } from "./shell/useInstanceSessionContext" -import { isPermissionAutoAcceptEnabled } from "../../stores/permission-auto-accept" import { readClientLayoutValue, writeClientLayoutValue } from "../../stores/client-state" import { runtimeEnv } from "../../lib/runtime-env" -import { getServerMeta, previewsUnavailable } from "../../lib/server-meta" +import { createProjectServerMeta } from "../../lib/project-server-meta" import { useInterruptionViewport } from "./shell/useInterruptionViewport" const log = getLogger("session") @@ -147,7 +148,6 @@ const InstanceShell2: Component = (props) => { let headerRightEl: HTMLElement | undefined const [headerIndicatorsEl, setHeaderIndicatorsEl] = createSignal() - const [now, setNow] = createSignal(Date.now()) const [sessionPromptApis, setSessionPromptApis] = createSignal>({}) const pendingFirstPromptText = new Map() const [draftAgent, setDraftAgent] = createSignal("") @@ -287,7 +287,7 @@ const InstanceShell2: Component = (props) => { }) // Remote Control clients hide the preview entry points while their host keeps previews off. - onMount(() => { void getServerMeta().catch(() => undefined) }) + const { previewsUnavailable } = createProjectServerMeta(() => props.instance.id) onMount(() => { if (typeof window === "undefined") return @@ -378,12 +378,6 @@ const InstanceShell2: Component = (props) => { writeClientLayoutValue(RIGHT_DRAWER_STORAGE_KEY, rightDrawerWidth().toString()) }) - createEffect(() => { - if (typeof window === "undefined") return - const timer = window.setInterval(() => setNow(Date.now()), 1000) - onCleanup(() => window.clearInterval(timer)) - }) - createEffect(() => { if (!props.isActiveInstance) return const element = sessionCenterEl() @@ -444,7 +438,7 @@ const InstanceShell2: Component = (props) => { const activeSessionPreview = createMemo(() => { const sessionId = activeSessionIdForInstance() - return sessionId ? getSessionPreview(sessionId) : null + return sessionId ? getSessionPreview(sessionId, props.instance.id) : null }) const showingPreview = () => getSessionSurface({ instanceId: props.instance.id, sessionId: activeSessionIdForInstance() }).kind === "web" @@ -463,13 +457,13 @@ const InstanceShell2: Component = (props) => { async function handleOpenPreview() { const sessionId = activeSessionIdForInstance() if (!sessionId || sessionId === "info") return - const intent = beginGesture({ instanceId: props.instance.id, sessionId }) + const instanceId = props.instance.id + const operation = captureBackendOperation(instanceId, undefined, () => props.instance.id === instanceId && activeSessionIdForInstance() === sessionId) try { - const restored = await restoreSessionPreview(sessionId, props.instance.id) - if (!intent.current()) return - if (restored) showSessionPreview(sessionId, props.instance.id, intent) - else await openSessionPreview(sessionId, DEFAULT_PREVIEW_URL, props.instance.id, undefined, intent) + if (!operation.current()) return + await requestSessionPreview(sessionId, instanceId) } catch (error) { + if (!operation.current()) return if (error instanceof Error && error.name === "AbortError") return if (props.isActiveInstance === false || activeSessionIdForInstance() !== sessionId) return showAlertDialog(t("sessionPreview.open.title"), { @@ -484,36 +478,30 @@ const InstanceShell2: Component = (props) => { const sessionId = activeSessionIdForInstance() if (!sessionId || sessionId === "info") return - const preview = activeSessionPreview() - if (showingPreview() && preview) { + if (showingPreview() && (activeSessionPreview() || previewBlockedByOwner(sessionId, props.instance.id))) { showSessionChatFor(sessionId, props.instance.id) return } - if (preview) { - showSessionPreview(sessionId, props.instance.id) - return - } void handleOpenPreview() } const previewToggleLabel = createMemo(() => { - return showingPreview() && activeSessionPreview() ? t("sessionPreview.chat.button") : t("sessionPreview.open.button") + const sessionId = activeSessionIdForInstance() + return showingPreview() && (activeSessionPreview() || (sessionId && previewBlockedByOwner(sessionId, props.instance.id))) + ? t("sessionPreview.chat.button") : t("sessionPreview.open.button") }) - const yoloModeEnabled = createMemo(() => { - const session = activeSessionForInstance() - if (!session) return false - return isPermissionAutoAcceptEnabled(props.instance.id, session.id) + const statusRow = createMemo(() => { + const id = activeSessionIdForInstance() + return props.isActiveInstance !== false && id && id !== "info" ? allInstanceSessions().get(id) ?? null : null }) + const activeSessionStatusPill = createDeadlineMemo((now, wakeAt) => { + const activeSession = statusRow() + if (!activeSession) return null - const activeSessionStatusPill = createMemo(() => { - const activeSessionId = activeSessionIdForInstance() - if (!activeSessionId || activeSessionId === "info") return null - - const activeSession = activeSessionForInstance() - const needsPermission = Boolean(activeSession?.pendingPermission) - const needsQuestion = Boolean(activeSession?.pendingForm) + const needsPermission = Boolean(activeSession.pendingPermission) + const needsQuestion = Boolean(activeSession.pendingForm) const needsInput = needsPermission || needsQuestion if (needsInput) { @@ -526,20 +514,21 @@ const InstanceShell2: Component = (props) => { } } - const status = getSessionStatus(props.instance.id, activeSessionId) - const retry = getSessionRetry(props.instance.id, activeSessionId) - const showStatus = shouldShowSessionStatus( + const status = activeSession.status + const retry = activeSession.retry + const showStatus = shouldShowSessionStatusForRow( props.instance.id, - activeSessionId, - now(), + activeSession, + now, preferences().keepUnseenSubagentIdleStatus, + wakeAt, ) if (!showStatus) { return null } const text = retry ? (() => { - const seconds = getRetrySeconds(retry.next, now()) + const seconds = getRetrySeconds(retry.next, now, wakeAt) return seconds > 0 ? t("sessionList.status.retryingIn", { seconds: String(seconds) }) : t("sessionList.status.retrying") })() : status === "working" @@ -549,7 +538,7 @@ const InstanceShell2: Component = (props) => { : t("sessionList.status.idle") const baseClassName = `session-${retry ? "retrying" : status}` - const fadeClassName = getSessionIdleFadeClass(props.instance.id, activeSessionId) + const fadeClassName = idleFadeClassForSession(props.instance.id, activeSession) return { className: fadeClassName ? `${baseClassName} ${fadeClassName}` : baseClassName, @@ -579,20 +568,6 @@ const InstanceShell2: Component = (props) => { ) } - const renderYoloModePill = () => { - if (!yoloModeEnabled()) return null - return ( - - - {t("instanceShell.yoloMode.badge")} - - ) - } - const renderSessionHeaderIndicators = () => (
@@ -601,7 +576,6 @@ const InstanceShell2: Component = (props) => { onClick={handleProjectInterruptionClick} /> - {renderYoloModePill()}
) @@ -901,9 +875,8 @@ const InstanceShell2: Component = (props) => { // Keep action items stable so unrelated updates do not rebuild their icon DOM. const headerActionMenuItems = createMemo(() => buildHeaderActionMenuItems()) - // Readers that need no conversation: schedules and playbook details. - const readingWithoutConversation = () => Boolean(props.isActiveInstance) - && ["recurrence", "playbook"].includes(missionProjectView(props.instance.id).reader?.kind ?? "") + // A reader that needs no conversation: playbook details. + const readingWithoutConversation = () => Boolean(props.isActiveInstance) && missionProjectView(props.instance.id).reader?.kind === "playbook" const activeSessionTitle = createMemo(() => { if (showingInfoView()) return null const title = activeSessionForInstance()?.title?.trim() @@ -981,16 +954,22 @@ const InstanceShell2: Component = (props) => { function createAndActivateDraftSession() { if (draftSessionCreation) return draftSessionCreation + const operation = captureBackendOperation(props.instance.id) + const assertCurrent = () => { if (!operation.current()) throw new DOMException("Backend detached", "AbortError") } const intent = beginGesture({ instanceId: props.instance.id, sessionId: activeSessionIdForInstance() ?? null }) const creation = (async () => { + assertCurrent() const agent = draftAgent() const model = draftModel() if (agent && model.providerId && model.modelId) { await setAgentModelPreference(props.instance.id, agent, model) + assertCurrent() } const session = await createSession(props.instance.id, agent || undefined) + assertCurrent() if (model.providerId && model.modelId) { await updateSessionModel(props.instance.id, session.id, model) + assertCurrent() } if (intent.current() && (!window.matchMedia?.("(pointer: coarse)")?.matches || window.matchMedia?.("(any-pointer: fine)")?.matches)) { setFocusConversationSessionId(session.id) @@ -1009,10 +988,15 @@ const InstanceShell2: Component = (props) => { submit: (sessionId: string) => Promise, draft?: { text: string; attachments: Attachment[] }, ) { + const operation = captureBackendOperation(props.instance.id) + if (!operation.current()) throw new DOMException("Backend detached", "AbortError") const session = await createAndActivateDraftSession() + if (!operation.current()) throw new DOMException("Backend detached", "AbortError") try { await submit(session.id) + if (!operation.current()) throw new DOMException("Backend detached", "AbortError") } catch (error) { + if (!operation.current()) throw error if (draft) { const api = sessionPromptApis()[session.id] if ((!api || !api.getPromptText()) && getAttachments(props.instance.id, session.id).length === 0) { @@ -1210,9 +1194,10 @@ const InstanceShell2: Component = (props) => { onSidebarToggle={() => setLeftOpen(true)} forceCompactStatusLayout={showEmbeddedSidebarToggle()} /> - +
+ 0}> = (props) => { } }} > - {/* The tab's scroller contains its absolutely positioned descendants, so no tab diff --git a/packages/ui/src/components/instance/shell/right-panel/RightPanelCustomizationPopover.tsx b/packages/ui/src/components/instance/shell/right-panel/RightPanelCustomizationPopover.tsx index e0c57cf94a..9cd60a20ae 100644 --- a/packages/ui/src/components/instance/shell/right-panel/RightPanelCustomizationPopover.tsx +++ b/packages/ui/src/components/instance/shell/right-panel/RightPanelCustomizationPopover.tsx @@ -25,6 +25,7 @@ interface RightPanelCustomizationPopoverProps { visibleStatusSectionCount: Accessor customization: Accessor onCustomizationChange: (updater: (current: RightPanelCustomization) => RightPanelCustomization) => void + onMissionsToggle: (enabled: boolean, setVisible: () => void, checkbox: HTMLInputElement) => void } /** Visibility and order of the right panel's tabs and Status sections. Up/Down reorders the focused Status section. */ @@ -94,20 +95,26 @@ export function RightPanelCustomizationPopover(props: RightPanelCustomizationPop type="checkbox" checked={visible()} disabled={tab.alwaysVisible || (Boolean(extension()) && (!props.extensions.verified() || props.extensions.activating() || !props.isActive()))} - // Activating an extension is a trust decision, never swept along. - data-toggle-sweep={extension() ? undefined : toggleSweepGroup("right-panel-customization")} + // Plugin activation requires an explicit gesture. + data-toggle-sweep={extension() || tab.id === "missions" ? undefined : toggleSweepGroup("right-panel-customization")} onChange={(event) => { + const enabled = event.currentTarget.checked const entry = extension() if (entry) { - const enabled = event.currentTarget.checked event.currentTarget.checked = entry.enabled void props.extensions.activate(entry, enabled) return } - props.onCustomizationChange((current) => ({ + const setVisible = () => props.onCustomizationChange((current) => ({ ...current, - hiddenTabIds: setRightPanelItemHidden(current.hiddenTabIds, tab.id, !event.currentTarget.checked), + hiddenTabIds: setRightPanelItemHidden(current.hiddenTabIds, tab.id, !enabled), })) + if (tab.id === "missions") { + event.currentTarget.checked = visible() + props.onMissionsToggle(enabled, setVisible, event.currentTarget) + return + } + setVisible() }} /> {label()} diff --git a/packages/ui/src/components/instance/shell/right-panel/components/OverlayList.tsx b/packages/ui/src/components/instance/shell/right-panel/components/OverlayList.tsx deleted file mode 100644 index 43299f6873..0000000000 --- a/packages/ui/src/components/instance/shell/right-panel/components/OverlayList.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import type { Component, JSX } from "solid-js" - -interface OverlayListProps { - ariaLabel: string - children: JSX.Element -} - -const OverlayList: Component = (props) => { - return ( - - ) -} - -export default OverlayList diff --git a/packages/ui/src/components/instance/shell/right-panel/components/WorkspaceTree.tsx b/packages/ui/src/components/instance/shell/right-panel/components/WorkspaceTree.tsx index a651e08b5d..9fca142cd6 100644 --- a/packages/ui/src/components/instance/shell/right-panel/components/WorkspaceTree.tsx +++ b/packages/ui/src/components/instance/shell/right-panel/components/WorkspaceTree.tsx @@ -77,7 +77,7 @@ export function WorkspaceTree(props: { get icon() { return }, disabled: !props.canOpen, checked: props.previewPath === row.path, onSelect: () => props.onOpen(row.path), }) - if (canOpenWorkspacePaths()) { + if (canOpenWorkspacePaths(props.instanceId)) { if (row.type === "directory") { const isMacApp = isMacDesktop && row.path.toLowerCase().endsWith(".app") items.push( @@ -146,7 +146,7 @@ export function WorkspaceTree(props: { }> }>}> - {row.name} + {row.name} }} diff --git a/packages/ui/src/components/instance/shell/right-panel/core-plugin.test.ts b/packages/ui/src/components/instance/shell/right-panel/core-plugin.test.ts index b9315f20a0..8995af6daa 100644 --- a/packages/ui/src/components/instance/shell/right-panel/core-plugin.test.ts +++ b/packages/ui/src/components/instance/shell/right-panel/core-plugin.test.ts @@ -13,15 +13,17 @@ it("defines built-in tabs and status sections without a plugin loading layer", a const render = () => undefined as any const summary = () => undefined as any const module = createCoreRightPanelModule({ renderFilesTab: render, renderStatusTab: render }) - const sections = createCoreStatusSectionManifest({ renderTokens: render, renderTokensSummary: summary, renderYoloModeSection: render, + const sections = createCoreStatusSectionManifest({ renderTokens: render, renderTokensSummary: summary, renderPermissions: render, + renderPermissionsSummary: summary, renderPermissionsInfo: render, renderProviderUsage: render, renderBackgroundProcesses: render, renderMcpStatus: render, renderPluginStatus: render }) assert.deepEqual(module.tabs?.map(entry => entry.id), ["files", "status"]) assert.equal(module.tabs?.find(entry => entry.id === "status")?.alwaysVisible, true) - assert.deepEqual(sections.statusSections?.map(entry => entry.id), ["tokens", "yolo-mode", "provider-usage", "background-processes", "mcp", "plugins"]) + assert.deepEqual(sections.statusSections?.map(entry => entry.id), ["tokens", "permissions", "provider-usage", "background-processes", "mcp", "plugins"]) assert.equal(module.tabs?.every(entry => entry.render === render), true) assert.equal(sections.statusSections?.every(entry => entry.render === render), true) assert.equal(sections.statusSections?.every(entry => typeof entry.renderInfo === "function"), true) assert.equal(sections.statusSections?.find(entry => entry.id === "tokens")?.renderStatus, summary) assert.equal(sections.statusSections?.filter(entry => entry.id !== "tokens").every(entry => !entry.renderStatus), true) + assert.equal(sections.statusSections?.find(entry => entry.id === "permissions")?.renderSummary, summary) } finally { hooks.deregister() } }) diff --git a/packages/ui/src/components/instance/shell/right-panel/core-plugin.tsx b/packages/ui/src/components/instance/shell/right-panel/core-plugin.tsx index b6ac242790..b50051367f 100644 --- a/packages/ui/src/components/instance/shell/right-panel/core-plugin.tsx +++ b/packages/ui/src/components/instance/shell/right-panel/core-plugin.tsx @@ -1,6 +1,6 @@ import type { JSX } from "solid-js" -import type { RightPanelModule } from "./registry" +import { CONVERSATION_PERMISSIONS_SECTION_ID, type RightPanelModule } from "./registry" import { CORE_STATUS_SECTION_ITEMS } from "./tabs/status-sections" import { SettingsInfoTip } from "../../../settings/settings-info-tip" import { tGlobal } from "../../../../lib/i18n" @@ -13,7 +13,9 @@ interface CoreRightPanelRenderers { interface CoreStatusSectionRenderers { renderTokens: () => JSX.Element renderTokensSummary?: () => JSX.Element - renderYoloModeSection: () => JSX.Element + renderPermissions: () => JSX.Element + renderPermissionsSummary: () => JSX.Element + renderPermissionsInfo: () => JSX.Element renderProviderUsage: () => JSX.Element renderBackgroundProcesses: () => JSX.Element renderMcpStatus: () => JSX.Element @@ -47,7 +49,7 @@ export function createCoreRightPanelModule(renderers: CoreRightPanelRenderers): export function createCoreStatusSectionManifest(renderers: CoreStatusSectionRenderers): RightPanelModule { const sectionRenderers: Record JSX.Element> = { tokens: renderers.renderTokens, - "yolo-mode": renderers.renderYoloModeSection, + [CONVERSATION_PERMISSIONS_SECTION_ID]: renderers.renderPermissions, "provider-usage": renderers.renderProviderUsage, "background-processes": renderers.renderBackgroundProcesses, mcp: renderers.renderMcpStatus, @@ -63,7 +65,10 @@ export function createCoreStatusSectionManifest(renderers: CoreStatusSectionRend const render = sectionRenderers[section.id] if (!render) throw new Error(`Missing core right panel section renderer: ${section.id}`) return { ...section, render, renderStatus: section.id === "tokens" ? renderers.renderTokensSummary : undefined, - renderInfo: () => } + renderSummary: section.id === CONVERSATION_PERMISSIONS_SECTION_ID ? renderers.renderPermissionsSummary : undefined, + renderInfo: section.id === CONVERSATION_PERMISSIONS_SECTION_ID + ? renderers.renderPermissionsInfo + : () => } }), } } diff --git a/packages/ui/src/components/instance/shell/right-panel/core-runtime.tsx b/packages/ui/src/components/instance/shell/right-panel/core-runtime.tsx index af88c2996d..5ed43d8928 100644 --- a/packages/ui/src/components/instance/shell/right-panel/core-runtime.tsx +++ b/packages/ui/src/components/instance/shell/right-panel/core-runtime.tsx @@ -15,6 +15,7 @@ import { useGitInit } from "./useGitInit" import { FILES_PANEL_MODE_KEY, type FilesPanelMode } from "./files-panel-state" import { readStoredEnum } from "../storage" import { writeClientLayoutValue } from "../../../../stores/client-state" +import { captureBackendOperation } from "../../../../lib/backend-operation" import { getTabViewState, updateTabViewState } from "../../../../stores/tab-view-state" const LazyFilesPanel = lazy(() => import("./tabs/FilesPanel")) @@ -69,11 +70,11 @@ export function createCoreRightPanelRuntime(options: CoreRightPanelRuntimeOption const gitAvailable = () => getGitRepoStatus(options.instanceId) !== false const directory = () => worktree()?.directory ?? options.instance.folder const gitInit = useGitInit({ instanceId: options.instanceId, directory, t: options.t }) - const tree = useWorkspaceTree(options.instanceId, directory, () => active() && mode() === "workspace") - const history = useGitHistory(options.instanceId, slug, () => active() && gitAvailable() && mode() === "history") + const tree = useWorkspaceTree(options.instanceId, directory, () => active() && mode() === "workspace", captureBackendOperation) + const history = useGitHistory(options.instanceId, slug, () => active() && gitAvailable() && mode() === "history", captureBackendOperation) const git = useGitChanges({ ...options, isActive: () => active() && gitAvailable() && mode() === "changes", rightPanelTab: () => "git-changes", - worktreeSlug: slug, closeGitList: () => {}, externalDiff: true, + worktreeSlug: slug, closeGitList: () => {}, externalDiff: true, captureOperation: captureBackendOperation, }) const openFile = (file: Pick) => { const sessionId = options.activeSessionId() diff --git a/packages/ui/src/components/instance/shell/right-panel/registry.test.ts b/packages/ui/src/components/instance/shell/right-panel/registry.test.ts index e5b5041a09..40cb4a43e2 100644 --- a/packages/ui/src/components/instance/shell/right-panel/registry.test.ts +++ b/packages/ui/src/components/instance/shell/right-panel/registry.test.ts @@ -60,14 +60,14 @@ describe("right panel registry", () => { }) it("moves only the source section and keeps unknown and hidden ids in place", () => { - const saved = ["plan", "tokens", "mcp", "integration:gone", "plugins", "yolo-mode"] - // `yolo-mode` is hidden: the drag sees only the shown sections. + const saved = ["plan", "tokens", "mcp", "integration:gone", "plugins", "permissions"] + // Permissions is hidden: the drag sees only the shown sections. assert.deepEqual(reorderStatusSections(saved, ["tokens", "mcp", "plugins"], "plugins", "tokens"), - ["plan", "plugins", "tokens", "mcp", "integration:gone", "yolo-mode"]) + ["plan", "plugins", "tokens", "mcp", "integration:gone", "permissions"]) assert.deepEqual(reorderStatusSections(saved, ["tokens", "mcp", "plugins"], "tokens", "plugins"), - ["plan", "mcp", "integration:gone", "plugins", "tokens", "yolo-mode"]) - assert.deepEqual(moveRightPanelItem(saved, ["tokens", "mcp", "plugins", "yolo-mode"], "plugins", 1), - ["plan", "tokens", "mcp", "integration:gone", "yolo-mode", "plugins"]) + ["plan", "mcp", "integration:gone", "plugins", "tokens", "permissions"]) + assert.deepEqual(moveRightPanelItem(saved, ["tokens", "mcp", "plugins", "permissions"], "plugins", 1), + ["plan", "tokens", "mcp", "integration:gone", "permissions", "plugins"]) }) it("materializes shown sections without a rank next to their shown predecessor", () => { diff --git a/packages/ui/src/components/instance/shell/right-panel/registry.ts b/packages/ui/src/components/instance/shell/right-panel/registry.ts index 92742169fc..334970d5c2 100644 --- a/packages/ui/src/components/instance/shell/right-panel/registry.ts +++ b/packages/ui/src/components/instance/shell/right-panel/registry.ts @@ -1,5 +1,7 @@ import type { JSX } from "solid-js" +export const CONVERSATION_PERMISSIONS_SECTION_ID = "permissions" + export interface RightPanelItem { id: string labelKey: string @@ -67,8 +69,8 @@ export function parseRightPanelCustomization(value: string | null): RightPanelCu return { tabOrder: readStringArray(parsed.tabOrder), hiddenTabIds: readStringArray(parsed.hiddenTabIds), - statusSectionOrder: readStringArray(parsed.statusSectionOrder), - hiddenStatusSectionIds: readStringArray(parsed.hiddenStatusSectionIds), + statusSectionOrder: readStatusSectionIds(parsed.statusSectionOrder), + hiddenStatusSectionIds: readStatusSectionIds(parsed.hiddenStatusSectionIds), } } catch { return { ...DEFAULT_RIGHT_PANEL_CUSTOMIZATION } @@ -159,3 +161,7 @@ function materializeOrder(orderedIds: readonly string[], displayedIds: readonly function readStringArray(value: unknown): string[] { return Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === "string") : [] } + +function readStatusSectionIds(value: unknown): string[] { + return [...new Set(readStringArray(value).map(id => id === "yolo-mode" ? CONVERSATION_PERMISSIONS_SECTION_ID : id))] +} diff --git a/packages/ui/src/components/instance/shell/right-panel/tabs/FilesPanel.tsx b/packages/ui/src/components/instance/shell/right-panel/tabs/FilesPanel.tsx index 1219b22d48..cd6387cdef 100644 --- a/packages/ui/src/components/instance/shell/right-panel/tabs/FilesPanel.tsx +++ b/packages/ui/src/components/instance/shell/right-panel/tabs/FilesPanel.tsx @@ -88,7 +88,7 @@ const FilesPanel: Component = props => { else if (!props.gitAvailable) void props.gitInit.recheck() else if (props.mode === "history") void props.history.refresh() else void props.git.refreshGitStatus() - }}> + }}> ') + await page.addScriptTag({ path: fileURLToPath(new URL("./page-probe.js", import.meta.url)) }) + await page.evaluate(() => { + window.__perf.arm() + const stream = document.querySelector("main") + stream.classList.add("fixture") + stream.setAttribute("aria-busy", "true") + stream.innerHTML = '

MKAA010001K

MKAA010003K

MKAA010004K

' + window.__perf.clearKey(document.querySelector("#composer")) + }) + await page.waitForFunction(() => window.__perf.collect().shown.MKAA010001K) + await page.locator("#other").press("x") + const shot = await page.evaluate(() => ({ ...window.__perf.collect(), keyAt: window.__perf.keyAt() })) + assert.deepEqual(Object.keys(shot.shown), ["MKAA010001K"]) + assert(shot.mutations >= 3, "Expected two attributes and one insertion") + assert.equal(shot.keyAt, undefined) + await page.locator("[hidden]").evaluate(element => { element.hidden = false }) + await page.waitForFunction(() => window.__perf.collect().shown.MKAA010002K) + await page.locator("#composer").press("a") + await page.waitForFunction(() => window.__perf.keyAt()) + await page.evaluate(() => { + window.__perf.arm(false) + const stream = document.querySelector("main") + stream.innerHTML = '

MKAA020001K

MKAA020002K

' + queueMicrotask(() => stream.lastElementChild.remove()) + }) + await page.waitForFunction(() => window.__perf.collect().shown.MKAA020001K) + assert.deepEqual(await page.evaluate(() => Object.keys(window.__perf.collect().shown)), ["MKAA020001K"]) + } finally { + try { await browser?.close() } finally { await rm(root, { recursive: true, force: true }) } + } +}) diff --git a/scripts/perf/perf-budgets.json b/scripts/perf/perf-budgets.json new file mode 100644 index 0000000000..17d0800de8 --- /dev/null +++ b/scripts/perf/perf-budgets.json @@ -0,0 +1,323 @@ +{ + "counters": { + "callsPerDaemonEvent": { + "baseline": 21273.386666666665, + "max": 24464.3947 + }, + "mutationsPerDaemonEvent": { + "baseline": 6.208888888888889, + "max": 7.1403 + }, + "pageFramesPerDaemonEvent": { + "baseline": 1, + "max": 1.15 + }, + "solid.updateComputation": { + "baseline": 236.18, + "max": 271.607 + }, + "solid.createComputation": { + "baseline": 146.37777777777777, + "max": 168.3345 + }, + "solid.cleanNode": { + "baseline": 398.2422222222222, + "max": 457.9786 + }, + "solid.writeSignal": { + "baseline": 63.004444444444445, + "max": 72.4552 + }, + "solid.setProperty": { + "baseline": 38.30210772833723, + "max": 44.0475 + } + }, + "latency": { + "8": { + "finalMarker": { + "baseline": 1, + "max": 1.15 + }, + "keysP95": { + "baseline": 1, + "max": 1.15 + } + }, + "32": { + "finalMarker": { + "baseline": 1, + "max": 1.15 + }, + "keysP95": { + "baseline": 1, + "max": 1.15 + } + } + }, + "callsByFile": { + "App.tsx": 109.92, + "components/action-overflow-menu.tsx": 50.27, + "components/agent-selector.tsx": 0.53, + "components/context-meter.tsx": 0.2, + "components/hidden-text.tsx": 0.63, + "components/instance-tab.tsx": 0.12, + "components/instance-tabs.tsx": 0.08, + "components/instance/instance-shell2.tsx": 111.8, + "components/instance/shell/SessionSidebar.tsx": 39.88, + "components/instance/shell/file-preview-lifetime.ts": 0.2, + "components/instance/shell/right-panel/core-runtime.tsx": 0.07, + "components/instance/shell/useInstanceSessionContext.ts": 0.38, + "components/interruption-dock-state.ts": 0.07, + "components/markdown-mermaid.tsx": 2.06, + "components/markdown-session-links.ts": 5.12, + "components/markdown.tsx": 16.72, + "components/measured-action-overflow.ts": 15.49, + "components/message-anchors.ts": 0.11, + "components/message-block.tsx": 62.28, + "components/message-content-icons.ts": 0.01, + "components/message-item.tsx": 42.32, + "components/message-part.tsx": 17.11, + "components/message-section.tsx": 220.89, + "components/message-timeline-projection.ts": 486.63, + "components/message-timeline.tsx": 434.98, + "components/model-selector.tsx": 0.2, + "components/part-duration.tsx": 0.04, + "components/permission-receipts.tsx": 0.78, + "components/prompt-input.tsx": 3.42, + "components/prompt-input/DictationNotice.tsx": 0.07, + "components/prompt-input/PromptContextControls.tsx": 0.98, + "components/prompt-input/api-recording-controller.ts": 0.26, + "components/prompt-input/height-state.ts": 0.1, + "components/prompt-input/submitPrompt.ts": 0.02, + "components/prompt-input/useDeviceAttachments.ts": 0.28, + "components/prompt-input/usePromptAttachments.ts": 0.03, + "components/prompt-input/usePromptViewport.ts": 0.06, + "components/prompt-input/usePromptVoiceInput.ts": 0.66, + "components/search-highlights.ts": 0.55, + "components/session-list-visibility.ts": 0.07, + "components/session-list.tsx": 401.68, + "components/session-outline-projection.ts": 569.51, + "components/session-row-overflow.ts": 15.2, + "components/session/session-idle-attention.ts": 0.07, + "components/session/session-view.tsx": 83.95, + "components/settings-screen.tsx": 0.2, + "components/settings/preferences-project-context.ts": 1.26, + "components/tab-scroll.tsx": 0, + "components/thinking-selector.tsx": 0.39, + "components/timeline-transcript-blocks.ts": 9.69, + "components/timeline-virtual-list.tsx": 117.58, + "components/tool-call.tsx": 1.2, + "components/tool-call/diagnostics.ts": 0.03, + "components/tool-call/renderers/read.tsx": 0.04, + "components/tool-call/tool-presentation.ts": 19.46, + "components/tool-call/tool-registry.ts": 0.01, + "components/tool-call/utils.ts": 0.3, + "components/tool-status-compaction.ts": 0.05, + "components/virtual-follow-behavior.ts": 12.53, + "components/virtual-follow-list.tsx": 49.47, + "components/virtual-follow-measurements.ts": 4.73, + "components/virtual-reader-settlement.ts": 0, + "components/virtual-scroll-trace.ts": 1.08, + "components/worktree-selector.tsx": 0.27, + "lib/api-client.ts": 0.35, + "lib/assistant-meta.ts": 0.78, + "lib/auth-recovery.ts": 0.11, + "lib/background-read-queue.ts": 0.3, + "lib/contexts/instance-metadata-context.tsx": 0.07, + "lib/event-source-handlers.ts": 1, + "lib/event-transport.ts": 1, + "lib/formatters.ts": 0.02, + "lib/frame-batch-schedule.ts": 55.2, + "lib/global-cache.ts": 4.25, + "lib/hooks/use-active-session-message-load.ts": 0.13, + "lib/hooks/use-app-session-capture.ts": 40.89, + "lib/hooks/use-global-cache.ts": 2.04, + "lib/hooks/use-instance-metadata.ts": 0.13, + "lib/hooks/use-live-voice-conversation.ts": 0.2, + "lib/hooks/use-speech.ts": 0.97, + "lib/hotkey-bindings.ts": 6.62, + "lib/hotkey-definitions.ts": 1.01, + "lib/hotkeys.ts": 0.96, + "lib/i18n/index.tsx": 184.38, + "lib/live-clock.ts": 0.02, + "lib/logger.ts": 3.17, + "lib/markdown-highlight-schedule.ts": 0.5, + "lib/markdown.ts": 29.1, + "lib/message-part-grouping.ts": 244.57, + "lib/message-render-cache.ts": 0.27, + "lib/message-timing.ts": 3.79, + "lib/microphone-lease.ts": 0.07, + "lib/native-execution-events.ts": 1, + "lib/native/client-state.ts": 0.08, + "lib/native/device-speech.ts": 0.26, + "lib/native/remote-api-microphone.ts": 0.13, + "lib/native/wake-lock.ts": 0.01, + "lib/notification-routing.ts": 0.01, + "lib/notifications.tsx": 0.04, + "lib/preserve-list-focus.ts": 0.07, + "lib/prompt-display-metadata.ts": 0.05, + "lib/render-text-window.ts": 0.16, + "lib/retained-size.ts": 181.89, + "lib/runtime-env.ts": 6.15, + "lib/sdk-manager.ts": 0.12, + "lib/server-events.ts": 14.45, + "lib/session-transcript-lru.ts": 0.15, + "lib/session-transcript-measurement.ts": 1.11, + "lib/sse-manager.ts": 4.01, + "lib/stream-staleness.ts": 1, + "lib/text-render-utils.ts": 2.61, + "lib/theme.tsx": 0.17, + "lib/thread-totals.ts": 0.04, + "lib/toggle-sweep.ts": 0.06, + "lib/web-session-client-state.ts": 0.08, + "server/src/missions/mission-schedule-carrier-identity.ts": 4.2, + "stores/app-session-reconciliation.ts": 0.02, + "stores/app-session-snapshot-merge.ts": 0.02, + "stores/app-tabs.ts": 108.94, + "stores/attachments.ts": 0.32, + "stores/client-state-attachments-codec.ts": 0.36, + "stores/client-state-codec.ts": 4.95, + "stores/client-state.ts": 0.25, + "stores/closed-workspace-drafts.ts": 0.2, + "stores/compaction-delta-buffer.ts": 2.04, + "stores/conversation-speech.ts": 0.13, + "stores/forms.ts": 0.12, + "stores/images-conversation.ts": 0.07, + "stores/instance-invalidation.ts": 1, + "stores/instance-metadata.ts": 0.07, + "stores/instances.ts": 7.38, + "stores/interruption-scope.ts": 0.07, + "stores/live-voice-agent.ts": 0.13, + "stores/message-prompt-display.ts": 5.98, + "stores/message-v2/bridge.ts": 3.82, + "stores/message-v2/bus.ts": 2.19, + "stores/message-v2/instance-store.ts": 341.85, + "stores/message-v2/message-status.ts": 1.85, + "stores/message-v2/message-window.ts": 0.25, + "stores/message-v2/normalizers.ts": 10.49, + "stores/message-v2/record-display-cache.ts": 273, + "stores/message-v2/session-info.ts": 0.22, + "stores/mission-content.ts": 1, + "stores/mission-store.ts": 0.07, + "stores/missions.ts": 5.07, + "stores/opencode-client.ts": 0.04, + "stores/opencode-data-divergence.ts": 0.02, + "stores/opencode-data-events.ts": 7, + "stores/opencode-data-fragments.ts": 4.22, + "stores/opencode-data-read-merge.ts": 0.52, + "stores/opencode-data.ts": 26.89, + "stores/opencode-projection-frame.ts": 0.91, + "stores/permission-receipt-cache.ts": 0.39, + "stores/preferences.tsx": 0.24, + "stores/prompt-transcripts.ts": 0.26, + "stores/request-locations.ts": 0.45, + "stores/session-api.ts": 0, + "stores/session-catalog-persistence.ts": 31.38, + "stores/session-events.ts": 10.12, + "stores/session-favorites.ts": 1, + "stores/session-generation-recovery.ts": 1.56, + "stores/session-interruption-seen.ts": 3.69, + "stores/session-list-options.ts": 9.55, + "stores/session-models.ts": 0.26, + "stores/session-outline-persistence.ts": 31.9, + "stores/session-outline.ts": 0.26, + "stores/session-prompt-ack.ts": 0.05, + "stores/session-pruning-events.ts": 1, + "stores/session-state.ts": 35.23, + "stores/session-status.ts": 35.45, + "stores/session-transcript-memory.ts": 0.51, + "stores/session-transcript-visibility.ts": 3.49, + "stores/session-tree.ts": 44.95, + "stores/speech.ts": 0.1, + "stores/tab-view-state-codec.ts": 0.25, + "stores/tab-view-state.ts": 0.06, + "stores/timeline-previews.ts": 0.96, + "stores/voice-conversation-engine.ts": 1.18, + "stores/wake-lock-eligibility.ts": 0.14, + "stores/workspace-session-scope.ts": 12.85, + "stores/worktrees.ts": 54.91, + "types/message.ts": 70.01, + "types/session.ts": 0.68, + "~/@corvu/utils/dist/chunk/U42ECMND.jsx": 0.41, + "~/@kobalte/core/dist/chunk/2CTBMVJ4.jsx": 0.61, + "~/@kobalte/core/dist/chunk/E4PLEADY.jsx": 1.25, + "~/@kobalte/core/dist/chunk/E53DB7BS.jsx": 0.72, + "~/@kobalte/core/dist/chunk/FBCYWU27.jsx": 0.2, + "~/@kobalte/core/dist/chunk/FINWO3A5.jsx": 0.07, + "~/@kobalte/core/dist/chunk/FLVHQV4A.jsx": 0.2, + "~/@kobalte/core/dist/chunk/FN6EICGO.jsx": 7.8, + "~/@kobalte/core/dist/chunk/JNCCF6MP.jsx": 0.41, + "~/@kobalte/core/dist/chunk/LEK3K6R3.jsx": 35.99, + "~/@kobalte/core/dist/chunk/LR7LBJN3.jsx": 1.03, + "~/@kobalte/core/dist/chunk/OYES4GOP.jsx": 0.61, + "~/@kobalte/core/dist/chunk/QZDH5R5B.jsx": 3.34, + "~/@kobalte/core/dist/chunk/SOM3K36D.jsx": 1.02, + "~/@kobalte/core/dist/chunk/UKTBL2JL.jsx": 21.51, + "~/@kobalte/core/dist/chunk/V6FPT6B6.jsx": 0.1, + "~/@kobalte/core/dist/chunk/YRH543JR.jsx": 0.71, + "~/@kobalte/utils/dist/index.js": 3.6, + "~/@opencode/client/dist/chunks/service-timing-d300ns9h.js": 0.16, + "~/@opencode/client/dist/chunks/service-timing-mqnb71k6.js": 13.11, + "~/@opencode/schema/dist/session-message.js": 0.02, + "~/@shikijs/core/dist/index.mjs": 13.31, + "~/@shikijs/engine-oniguruma/dist/index.mjs": 48.79, + "~/@shikijs/types/dist/index.mjs": 27.09, + "~/@shikijs/vscode-textmate/dist/index.js": 206.31, + "~/@solid-primitives/refs/dist/index.js": 0.2, + "~/@solid-primitives/utils/dist/index.js": 3.43, + "~/debug/src/common.js": 5.26, + "~/effect/dist/Function.js": 0, + "~/effect/dist/Predicate.js": 0.02, + "~/effect/dist/Schema.js": 0.02, + "~/effect/dist/SchemaAST.js": 0.06, + "~/effect/dist/SchemaIssue.js": 0.04, + "~/effect/dist/SchemaParser.js": 0.08, + "~/effect/dist/internal/core.js": 0.05, + "~/effect/dist/internal/effect.js": 0.07, + "~/effect/dist/internal/schema/compilerRegistry.js": 0.02, + "~/effect/dist/internal/schema/interpreter.js": 0.02, + "~/effect/dist/internal/schema/make.js": 0, + "~/hast-util-to-html/lib/handle/element.js": 3.99, + "~/hast-util-to-html/lib/handle/root.js": 0.15, + "~/hast-util-to-html/lib/handle/text.js": 0.84, + "~/hast-util-to-html/lib/index.js": 3.84, + "~/lucide-solid/dist/source/Icon.jsx": 76.63, + "~/lucide-solid/dist/source/icons/archive.jsx": 2.1, + "~/lucide-solid/dist/source/icons/arrow-down.jsx": 0.07, + "~/lucide-solid/dist/source/icons/arrow-right-square.jsx": 0.02, + "~/lucide-solid/dist/source/icons/arrow-up.jsx": 0.07, + "~/lucide-solid/dist/source/icons/book-open.jsx": 0.01, + "~/lucide-solid/dist/source/icons/bot.jsx": 0.11, + "~/lucide-solid/dist/source/icons/check.jsx": 0.01, + "~/lucide-solid/dist/source/icons/chevron-right.jsx": 0.02, + "~/lucide-solid/dist/source/icons/copy.jsx": 0.56, + "~/lucide-solid/dist/source/icons/eraser.jsx": 0.13, + "~/lucide-solid/dist/source/icons/hourglass.jsx": 0.01, + "~/lucide-solid/dist/source/icons/list-end.jsx": 0.07, + "~/lucide-solid/dist/source/icons/loader-2.jsx": 0.01, + "~/lucide-solid/dist/source/icons/mic.jsx": 0.07, + "~/lucide-solid/dist/source/icons/more-horizontal.jsx": 0.1, + "~/lucide-solid/dist/source/icons/paperclip.jsx": 0.07, + "~/lucide-solid/dist/source/icons/split.jsx": 0.73, + "~/lucide-solid/dist/source/icons/trash-2.jsx": 0.03, + "~/lucide-solid/dist/source/icons/undo.jsx": 0.36, + "~/lucide-solid/dist/source/icons/user.jsx": 0.05, + "~/lucide-solid/dist/source/icons/volume-2.jsx": 0.07, + "~/lucide-solid/dist/source/icons/x-circle.jsx": 0.01, + "~/lucide-solid/dist/source/icons/x.jsx": 0.07, + "~/marked-katex-extension/lib/index.esm.js": 11.1, + "~/marked/lib/marked.esm.js": 118.28, + "~/property-information/lib/find.js": 1.43, + "~/property-information/lib/normalize.js": 1.43, + "~/solid-js/dist/solid.js": 8536.77, + "~/solid-js/store/dist/store.js": 6351.47, + "~/solid-js/web/dist/web.js": 744.18, + "~/solid-presence/dist/index.jsx": 0.72, + "~/solid-toast/dist/source/types/toast.js": 2.17, + "~/stringify-entities/lib/core.js": 7.39, + "~/stringify-entities/lib/index.js": 3.69, + "~/virtua/lib/solid/index.jsx": 1.8, + "~/zwitch/index.js": 2.27 + } +} diff --git a/scripts/perf/perf-check.mjs b/scripts/perf/perf-check.mjs new file mode 100644 index 0000000000..ecd8b0dc8f --- /dev/null +++ b/scripts/perf/perf-check.mjs @@ -0,0 +1,98 @@ +// node scripts/perf/perf-check.mjs [--tree ] [--client cn0] [--summary ] +// Add --calibrate to print a budget candidate; never recalibrate on ordinary PR validation. +import assert from "node:assert/strict" +import { appendFileSync, readFileSync, readdirSync } from "node:fs" +import path from "node:path" +import { fileURLToPath } from "node:url" +import { parseArgs } from "node:util" +import { assertRatchet, budgetReport } from "./budget-report.mjs" +import { byFile, byFunction } from "./coverage-top.mjs" +import { solidCounters } from "./solid-counters.mjs" +import { assetsDirectory } from "./stacks.mjs" + +const { values, positionals: [directory] } = parseArgs({ + allowPositionals: true, options: { + tree: { type: "string", default: fileURLToPath(new URL("../..", import.meta.url)) }, + client: { type: "string", default: "cn0" }, summary: { type: "string" }, + base: { type: "string" }, + calibrate: { type: "boolean" }, measure: { type: "boolean" }, + }, +}) +assert(directory, "Pass the benchmark results directory") +const load = file => JSON.parse(readFileSync(file, "utf8")) +const median = values => { + assert(values.length && values.every(Number.isFinite), "Missing or invalid measurement") + return [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)] +} +const records = readdirSync(directory).filter(file => /-r\d+-L\d+\.json$/.test(file)).map(file => ({ ...load(path.join(directory, file)), file })) +const counters = records.filter(r => r.scenario === "counters" && r.label === values.client) +assert(counters.length, `Missing counter samples for ${values.client}`) +for (const record of records) { + assert(Number.isInteger(record.daemonFrames) && record.daemonFrames > 0 + && Number.isInteger(record.expectedMarkers) && Number.isInteger(record.markers) + && record.markers > 0 && record.markers <= record.expectedMarkers, `Invalid sample: ${record.file}`) +} +const assets = assetsDirectory(values.tree) +const solidDir = path.join(values.tree, "node_modules/solid-js") +const byLevel = {} +for (const level of new Set(counters.map(r => r.level))) { + const samples = counters.filter(r => r.level === level) + const functions = samples.map(r => byFunction(path.join(directory, r.file.replace(/\.json$/, "-coverage.json")), assets, r.daemonFrames)) + const metrics = samples.map((r, i) => ({ ...r.counters, ...solidCounters(functions[i], solidDir) })) + const files = functions.map(byFile) + byLevel[level] = { + rounds: samples.length, + metrics: Object.fromEntries(Object.keys(metrics[0]).map(key => [key, median(metrics.map(row => row[key]))])), + files: Object.fromEntries([...new Set(files.flatMap(m => [...m.keys()]))].sort().map(key => [key, median(files.map(m => m.get(key) ?? 0))])), + } +} +if (values.measure) { + console.log(JSON.stringify(Object.fromEntries(Object.entries(byLevel).map(([level, { rounds, metrics }]) => [level, { rounds, metrics }])), null, 2)) + process.exit(0) +} +function latency(level, selector) { + const rows = records.filter(r => r.scenario === "latency" && r.level === level) + const read = kind => { + const matches = rows.filter(r => r.label === kind) + checkRounds(matches, `${kind} latency at L${level}`) + const timings = matches.map(selector) + assert(timings.every(value => Number.isFinite(value) && value >= 0), `Missing or negative ${kind} latency at L${level}`) + return median(timings) + } + const cn = read(values.client), tui = read("tui") + return { cn, tui, ratio: Math.max(cn, 50) / Math.max(tui, 50) } +} +function checkRounds(samples, name) { + assert.deepEqual(samples.map(row => row.round).sort(), [0, 1, 2], `Expected distinct rounds 0–2 for ${name}`) +} +const counter = byLevel[8] +checkRounds(counters.filter(row => row.level === 8), "counters at L8") +const ratios = Object.fromEntries([8, 32].map(level => [level, { + finalMarker: latency(level, r => r.stages.finalMarkerMs), + keysP95: latency(level, r => r.keys.p95), +}])) +const roundUp = value => Math.ceil(value * 10_000) / 10_000 +if (values.calibrate) { + const limits = metrics => Object.fromEntries(Object.entries(metrics).map(([key, baseline]) => [key, { baseline, max: roundUp(baseline * 1.15) }])) + console.log(JSON.stringify({ + counters: limits(counter.metrics), + latency: Object.fromEntries(Object.entries(ratios).map(([level, metrics]) => [level, limits(Object.fromEntries(Object.entries(metrics).map(([key, v]) => [key, v.ratio])))])), + callsByFile: Object.fromEntries(Object.entries(counter.files).filter(([, calls]) => calls > 0).map(([file, calls]) => [file, +calls.toFixed(2)])), + }, null, 2)) + process.exit(0) +} + +const budgets = load(new URL("./perf-budgets.json", import.meta.url)) +if (values.base) { + const base = load(values.base) + try { assertRatchet(base, budgets) } catch (error) { + if (values.summary) appendFileSync(values.summary, `### Performance guard\n\n${error.message}\n`) + throw error + } + budgets.callsByFile = base.callsByFile +} +const { report, failures } = budgetReport(budgets, counter, ratios) +console.log(report) +if (values.summary) appendFileSync(values.summary, report) +for (const failure of failures) console.error(`::error title=Performance budget exceeded::${failure}`) +if (failures.length) process.exitCode = 1 diff --git a/scripts/perf/seed.mjs b/scripts/perf/seed.mjs new file mode 100644 index 0000000000..5ad6cc473c --- /dev/null +++ b/scripts/perf/seed.mjs @@ -0,0 +1,56 @@ +import assert from "node:assert/strict" +import { sleep } from "./lib.mjs" + +export async function waitIdle(daemon, id) { + const deadline = Date.now() + 60_000 + for (;;) { + const { data } = await daemon.call("GET", "/api/session/active") + const active = Array.isArray(data) ? data.map(x => x.id ?? x.sessionID ?? x) : Object.keys(data ?? {}) + if (!(id ? active.includes(id) : active.length)) return + if (Date.now() >= deadline) throw Error("Seed session did not settle") + await sleep(40) + } +} + +export async function seed(daemon, turns, count) { + const create = async title => (await daemon.call("POST", "/api/session", { title, location: { directory: daemon.project } })).data.id + const foreground = await create("Seed foreground history") + const background = [] + for (let i = 1; i < count; i++) background.push(await create(`Background ${String(i).padStart(2, "0")}`)) + const prompt = async (id, text) => { + await daemon.call("POST", `/api/session/${id}/prompt`, { text }) + await waitIdle(daemon, id) + const { data } = await daemon.call("GET", `/api/session/${id}`) + assert.equal(data.outcome, "succeeded", `Seed turn failed: ${text}`) + } + await Promise.all(background.map(async id => { + for (let i = 1; i <= 3; i++) await prompt(id, `SEED${i} background`) + })) + for (let i = 1; i <= turns; i++) { + await prompt(foreground, `SEED${i} history turn ${i}: explain the fixture module`) + if (i % 50 === 0) console.log(`Seeded ${i} of ${turns} history turns`) + } + return [foreground, ...background] +} + +export async function withSampleSessions(daemon, templates, run) { + const sessions = [] + let failure + try { + for (let i = 0; i < templates.length; i++) { + const { data: { id } } = await daemon.call("POST", `/api/session/${templates[i]}/fork`, {}) + sessions.push(id) + if (i === 0) await daemon.call("PATCH", `/api/session/${id}`, { title: "Foreground history" }) + } + await run(sessions) + } catch (error) { + failure = error + } finally { + const cleanup = [] + for (const id of sessions) { + try { await daemon.call("DELETE", `/api/session/${id}`) } catch (error) { cleanup.push(error) } + } + if (cleanup.length) throw new AggregateError(failure ? [failure, ...cleanup] : cleanup, "Could not remove benchmark sessions", { cause: failure }) + } + if (failure) throw failure +} diff --git a/scripts/perf/seed.test.mjs b/scripts/perf/seed.test.mjs new file mode 100644 index 0000000000..dd0c2c57fd --- /dev/null +++ b/scripts/perf/seed.test.mjs @@ -0,0 +1,46 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import { seed, withSampleSessions } from "./seed.mjs" + +test("a seed execution that became idle after failure cannot qualify an empty history", async () => { + const daemon = { + async call(method, route) { + if (route === "/api/session") return { data: { id: "foreground" } } + if (route === "/api/session/active") return { data: {} } + if (method === "POST") return { data: { type: "user" } } + return { data: { outcome: "failed" } } + }, + } + await assert.rejects(() => seed(daemon, 1, 1), /Seed turn failed/) +}) + +test("each sample forks the same inputs and removes only its own output sessions", async () => { + let next = 0 + const requests = [] + const daemon = { async call(method, route, body) { + requests.push([method, route, body]) + return method === "POST" ? { data: { id: `fork-${++next}` } } : undefined + } } + const sample = async () => withSampleSessions(daemon, ["seed-a", "seed-b"], async ids => ids) + await sample() + await sample() + assert.deepEqual(requests.filter(([method]) => method === "POST").map(([, route]) => route), + ["/api/session/seed-a/fork", "/api/session/seed-b/fork", "/api/session/seed-a/fork", "/api/session/seed-b/fork"]) + assert.deepEqual(requests.filter(([method]) => method === "DELETE").map(([, route]) => route), + ["/api/session/fork-1", "/api/session/fork-2", "/api/session/fork-3", "/api/session/fork-4"]) +}) + +test("sample cleanup attempts every removal and preserves the measurement failure", async () => { + const attempts = [] + const primary = Error("measurement failed") + let next = 0 + const daemon = { async call(method, route) { + if (method === "POST") return { data: { id: `fork-${++next}` } } + if (method === "DELETE") { + attempts.push(route) + if (attempts.length === 1) throw Error("cleanup failed") + } + } } + await assert.rejects(() => withSampleSessions(daemon, ["a", "b"], async () => { throw primary }), error => error.cause === primary) + assert.deepEqual(attempts, ["/api/session/fork-1", "/api/session/fork-2"]) +}) diff --git a/scripts/perf/session-list-probes.mjs b/scripts/perf/session-list-probes.mjs new file mode 100644 index 0000000000..e975dd3cd2 --- /dev/null +++ b/scripts/perf/session-list-probes.mjs @@ -0,0 +1,59 @@ +const percentile = (numbers, fraction) => numbers.length + ? numbers.toSorted((a, b) => a - b)[Math.ceil(numbers.length * fraction) - 1] + : null + +/** Sample only the fixture tab, using Chromium's task boundaries (not the 50 ms Long Tasks API). */ +export async function sampleSessionList(context, page) { + const cdp = await context.newCDPSession(page) + await cdp.send("Performance.enable") + const metrics = async () => Object.fromEntries((await cdp.send("Performance.getMetrics")).metrics.map(({ name, value }) => [name, value])) + await page.evaluate(() => { + window.perfKeyEvents = [] + new PerformanceObserver(list => { + for (const event of list.getEntries()) { + if (/^key/.test(event.name) && event.target instanceof HTMLTextAreaElement) window.perfKeyEvents.push(event.duration) + } + }).observe({ type: "event", durationThreshold: 16 }) + }) + const threads = new Set(), taskCounts = new Map(), candidates = [], callbacks = [] + const thread = event => `${event.pid}:${event.tid}` + cdp.on("Tracing.dataCollected", ({ value }) => { + for (const event of value) { + if (event.name === "thread_name" && event.args.name === "CrRendererMain") threads.add(thread(event)) + if (event.ph !== "X") continue + if (event.name === "ThreadControllerImpl::RunTask") { + const key = thread(event) + taskCounts.set(key, (taskCounts.get(key) ?? 0) + 1) + if (event.dur >= 16_000) candidates.push(event) + } else if (["EventDispatch", "TimerFire", "FireAnimationFrame"].includes(event.name)) callbacks.push(event) + } + }) + await cdp.send("Tracing.start", { categories: "toplevel,devtools.timeline", transferMode: "ReportEvents" }) + const before = await metrics() + return async () => { + const after = await metrics() + const completed = new Promise(resolve => cdp.once("Tracing.tracingComplete", resolve)) + await cdp.send("Tracing.end") + const { dataLossOccurred } = await completed + const rendererTasks = [...threads].reduce((sum, key) => sum + (taskCounts.get(key) ?? 0), 0) + if (dataLossOccurred || rendererTasks === 0) throw new Error("Chromium trace did not retain renderer task boundaries") + const tasks = candidates.filter(event => threads.has(thread(event))).map(event => ({ + atMs: event.ts / 1000, + durationMs: event.dur / 1000, + callbacks: [...new Set(callbacks.filter(callback => thread(callback) === thread(event) + && callback.ts >= event.ts && callback.ts < event.ts + event.dur) + .map(callback => callback.args?.data?.type ?? callback.name))], + })) + const keyEvents = await page.evaluate(() => window.perfKeyEvents) + await cdp.detach() + return { + seconds: after.Timestamp - before.Timestamp, + mainThreadBusyPct: 100 * (after.TaskDuration - before.TaskDuration) / (after.Timestamp - before.Timestamp), + filteredKeyEventP95: percentile(keyEvents, 0.95), + rendererTasks, + tasksAtLeast16ms: tasks.length, + eventOrTimerTasksAtLeast16ms: tasks.filter(task => task.callbacks.length > 0).length, + tasks, + } + } +} diff --git a/scripts/perf/session-list-sse.mjs b/scripts/perf/session-list-sse.mjs new file mode 100644 index 0000000000..74b9c946be --- /dev/null +++ b/scripts/perf/session-list-sse.mjs @@ -0,0 +1,200 @@ +// Run against a sourcemapped production UI build, with no native app or daemon. +// node scripts/perf/session-list-sse.mjs [seconds] +import assert from "node:assert/strict" +import { createServer } from "node:http" +import { readFile, mkdtemp, mkdir, writeFile, rm } from "node:fs/promises" +import { resolve, join, extname, sep } from "node:path" +import { chromium } from "playwright" +import { sampleSessionList } from "./session-list-probes.mjs" + +const [dist, artifacts, seconds = "90"] = process.argv.slice(2) +const root = resolve(dist) +const output = resolve(artifacts) +await mkdir(output, { recursive: true }) +const profile = await mkdtemp(join(output, "chromium-")) +const folder = "/perf" +const tokens = { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } } +const workspace = { + id: "wrk_perf", path: folder, status: "ready", port: 1234, proxyPath: "/workspaces/wrk_perf/instance", + binaryId: "fixture", createdAt: new Date(0).toISOString(), updatedAt: new Date(0).toISOString(), +} +const rows = Array.from({ length: 6000 }, (_, i) => ({ + id: `ses_${i}`, parentID: i % 2 ? `ses_${i - 1}` : undefined, + title: `Conversation ${i}`, projectID: "perf", location: { directory: folder }, + time: { created: 1, updated: i + 1 }, cost: 0, tokens, +})) +const byId = new Map(rows.map(row => [row.id, row])) +for (let i = 0; i < 120; i++) { + const id = `ses_${6000 + i}` + byId.set(id, { ...rows[i], id, parentID: "ses_0", title: `Cold conversation ${i}` }) +} +const streams = new Set() +const requested = new Set() +const sessionReads = new Map() +let measuring = false +const mime = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".json": "application/json" } +const server = createServer(async (req, res) => { + const url = new URL(req.url, "http://localhost"), path = url.pathname + requested.add(path) + if (measuring && req.method === "GET" && /\/api\/session(?:\/ses_\d+)?$/.test(path)) { + const key = path + url.search + sessionReads.set(key, (sessionReads.get(key) ?? 0) + 1) + } + if (path === "/api/events") { + res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" }) + res.write(": connected\n\n") + streams.add(res) + res.on("close", () => streams.delete(res)) + return + } + let body + if (path === "/api/meta") body = { apiContract: 1, serverId: "local", localRequest: true } + else if (path === "/api/auth/status") body = { authenticated: true } + else if (path === "/api/workspaces") { + if (req.method === "POST") { + const chunks = [] + for await (const chunk of req) chunks.push(chunk) + body = { ...workspace, requestId: JSON.parse(Buffer.concat(chunks)).requestId } + } else body = [workspace] + } else if (path.includes("/api/opencode/")) body = { state: "ready", serviceState: "ready" } + else if (path.endsWith("/worktrees")) body = { isGitRepo: true, worktrees: [{ slug: "root", kind: "root", directory: folder }] } + else if (path.endsWith("/api/location")) body = { directory: folder, project: { id: "perf", directory: folder, canonical: folder } } + else if (path.endsWith("/api/project")) body = [{ id: "perf", canonical: folder, vcs: "git", time: { created: 1, updated: 1 }, sandboxes: [] }] + else if (path.endsWith("/api/mcp")) body = { location: { directory: folder }, data: [] } + else if (path.endsWith("/api/session")) { + if (!url.searchParams.has("project") && !url.searchParams.has("cursor")) { + body = { data: rows.filter(row => !row.parentID).slice(-200), cursor: {} } + } else { + const offset = Number(url.searchParams.get("cursor") ?? "0") + const next = offset + 200 + body = { data: rows.slice(offset, next), cursor: next < rows.length ? { next: String(next) } : {} } + } + } + else if (path.endsWith("/api/session/active")) body = { data: Object.fromEntries( + rows.slice(-20).filter(row => !row.parentID).map(row => [row.id, {}]), + ) } + else if (/\/api\/session\/ses_\d+$/.test(path)) { + const row = byId.get(path.split("/").at(-1)) + if (Number(row.id.slice(4)) >= 6000) await new Promise(resolve => setTimeout(resolve, 40)) + body = { data: row } + } + else if (path.includes("/instance/api/")) body = { data: [], cursor: {} } + else if (path.startsWith("/api/")) body = path.endsWith("/config/ui") ? { settings: { locale: "en" } } : {} + if (body !== undefined) { + res.writeHead(200, { "Content-Type": "application/json" }) + res.end(JSON.stringify(body)) + return + } + const asset = resolve(root, path === "/" ? "index.html" : `.${path}`) + try { + if (!asset.startsWith(root + sep)) throw new Error("Outside the fixture") + const file = await readFile(asset) + res.writeHead(200, { "Content-Type": mime[extname(asset)] ?? "application/octet-stream" }) + res.end(file) + } catch { + res.writeHead(404) + res.end() + } +}) +await new Promise(ok => server.listen(0, "127.0.0.1", ok)) +let context, activity +try { + context = await chromium.launchPersistentContext(profile, { + headless: true, serviceWorkers: "block", + viewport: { width: 1400, height: 950 }, + }) + await context.addInitScript(({ folder, catalog }) => { + window.__CODENOMAD_RUNTIME_HOST__ = "electron" + window.__CODENOMAD_WINDOW_CONTEXT__ = "local" + window.perfCommits = 0 + const snapshot = { version: 1, revision: 1, savedAt: 1, layout: {}, session: { activeTabIndex: 0, tabs: [{ + kind: "workspace", folder, occurrence: 0, activeSessionId: "ses_5998", activeParentSessionId: "ses_5998", + drafts: {}, attachments: {}, unseenIdleSince: {}, generationRecovery: {}, scrollSnapshots: {}, sessionCatalog: catalog, + }] } } + window.electronAPI = { + claimClientStateAccess: async () => true, + loadClientState: async () => ({ snapshot, isPrimary: true, restoreEnabled: true, partitionProtocolVersion: 1 }), + loadClientStatePartition: async () => null, + commitClientStatePartitions: async () => { window.perfCommits++; return true }, + } + }, { folder, catalog: rows.map(row => ({ ...row, parentId: row.parentID ?? null, agent: "build", model: { providerId: "p", modelId: "m" } })) }) + const page = context.pages()[0] + page.on("pageerror", e => console.error(e)) + page.on("console", message => { if (message.type() === "error") console.error(message.text()) }) + await page.goto(`http://127.0.0.1:${server.address().port}/`, { waitUntil: "domcontentloaded" }) + await page.locator(".session-item-base").first().waitFor({ timeout: 12000 }).catch(async error => { + console.error(page.url(), [...requested]) + throw error + }) + const editor = page.locator("textarea:visible").first() + await editor.focus({ timeout: 12000 }) + const emit = event => { + const payload = JSON.stringify({ type: "instance.event", instanceId: workspace.id, event }) + for (const stream of streams) stream.write(`data: ${payload}\n\n`) + } + const rename = (sessionID, ordinal, title) => ({ + type: "session.renamed", id: `event-${ordinal}`, created: Date.now(), location: { directory: folder }, + durable: { aggregateID: sessionID, seq: ordinal, version: 1 }, data: { sessionID, title }, + }) + emit(rename("ses_5998", 1, "Fixture ready")) + await page.locator(".session-item-base").getByText("Fixture ready", { exact: true }).waitFor({ timeout: 12000 }) + assert.equal(await editor.inputValue(), "", "the production composer starts empty") + await editor.evaluate(input => { + window.perfKeys = [] + window.perfInputs = [] + input.addEventListener("input", event => window.perfInputs.push([event.inputType, input.value])) + document.addEventListener("keydown", event => { + if (event.target !== input || !["a", "Backspace"].includes(event.key)) return + // Include input, synchronous reactive work and microtasks before the next + // render opportunity; use every key, unlike Event Timing's 16 ms floor. + requestAnimationFrame(() => window.perfKeys.push(performance.now() - event.timeStamp)) + }, { capture: true }) + }) + const commitsBefore = await page.evaluate(() => window.perfCommits) + const finishSample = await sampleSessionList(context, page) + measuring = true + let seq = 0 + let presses = Promise.resolve() + const keyboardErrors = [] + activity = setInterval(() => { + const ordinal = ++seq + const sessionID = ordinal % 12 === 0 ? `ses_${6000 + Math.floor(ordinal / 12) % 120}` : `ses_${(ordinal * 283) % 5900}` + emit(rename(sessionID, ordinal * 2, `Renamed ${ordinal}`)) + if (ordinal % 12 === 0) emit(rename(sessionID, ordinal * 2 + 1, `Renamed twice ${ordinal}`)) + if (ordinal % 3 === 0) presses = presses + .then(() => page.keyboard.press(ordinal % 6 === 0 ? "Backspace" : "a")) + .catch(error => { keyboardErrors.push(error) }) + }, 83) + await new Promise(resolve => setTimeout(resolve, Number(seconds) * 1000)) + clearInterval(activity) + await presses + if (keyboardErrors.length) throw new AggregateError(keyboardErrors, "Production composer keyboard presses failed") + await page.evaluate(() => new Promise(resolve => requestAnimationFrame(resolve))) + measuring = false + const { tasks, ...report } = await finishSample() + await writeFile(join(output, "report.json"), JSON.stringify(report, null, 2)) + await writeFile(join(output, "longtasks.json"), JSON.stringify(tasks, null, 2)) + const counters = { eventTicks: seq, streams: streams.size, + mockPartitionCommits: await page.evaluate(start => window.perfCommits - start, commitsBefore) } + const keys = await page.evaluate(() => window.perfKeys.sort((a, b) => a - b)) + const inputs = await page.evaluate(() => window.perfInputs) + assert.ok(keys.length > 0, "the production composer received keyboard input") + assert.equal(keys.length, Math.floor(seq / 3), "every scheduled press reached the production composer") + assert.deepEqual(inputs, Array.from({ length: keys.length }, (_, i) => i % 2 + ? ["deleteContentBackward", ""] : ["insertText", "a"]), "every press changed the composer value as intended") + assert.equal(await editor.inputValue(), keys.length % 2 ? "a" : "") + counters.inputCount = inputs.length + counters.keyToFrame = { count: keys.length, p50: keys[Math.ceil(keys.length * 0.5) - 1], + p95: keys[Math.ceil(keys.length * 0.95) - 1], max: keys.at(-1) } + await writeFile(join(output, "fixture.json"), JSON.stringify(counters, null, 2)) + await writeFile(join(output, "session-reads.json"), JSON.stringify(Object.fromEntries(sessionReads), null, 2)) + console.log({ ...counters, ...report, sessionPointReads: [...sessionReads].reduce( + (count, [url, reads]) => /\/api\/session\/ses_\d+/.test(url) ? count + reads : count, 0) }) +} finally { + clearInterval(activity) + await context?.close() + for (const stream of streams) stream.end() + server.closeAllConnections() + await new Promise(ok => server.close(ok)) + await rm(profile, { recursive: true, force: true }) +} diff --git a/scripts/perf/solid-counters.mjs b/scripts/perf/solid-counters.mjs new file mode 100644 index 0000000000..aaff0e451a --- /dev/null +++ b/scripts/perf/solid-counters.mjs @@ -0,0 +1,25 @@ +import assert from "node:assert/strict" +import { readFileSync } from "node:fs" +import path from "node:path" + +const files = { + "dist/solid.js": ["updateComputation", "createComputation", "cleanNode", "writeSignal"], + "store/dist/store.js": ["setProperty"], +} + +export function solidCounters(functions, solidDir) { + const result = {} + for (const [file, names] of Object.entries(files)) { + const source = readFileSync(path.join(solidDir, file), "utf8").split("\n") + for (const name of names) { + const line = source.findIndex(text => text.startsWith(`function ${name}(`)) + 1 + assert(line, `Unknown Solid counter ${name}`) + const prefix = `~/solid-js/${file}:${line} ` + let calls + for (const [key, count] of functions) if (key.startsWith(prefix)) calls = (calls ?? 0) + count + assert(Number.isFinite(calls), `Missing coverage for Solid counter ${name}`) + result[`solid.${name}`] = calls + } + } + return result +} diff --git a/scripts/perf/stacks.mjs b/scripts/perf/stacks.mjs new file mode 100644 index 0000000000..24d651ded5 --- /dev/null +++ b/scripts/perf/stacks.mjs @@ -0,0 +1,60 @@ +import { spawn } from "node:child_process" +import { randomUUID } from "node:crypto" +import { mkdir, writeFile } from "node:fs/promises" +import path from "node:path" +import { fileURLToPath } from "node:url" +import { stopFixtureChild } from "../native-fixture-guards.mjs" +import { privatePath } from "./isolation.mjs" +import { sleep } from "./lib.mjs" + +export const assetsDirectory = tree => path.join(tree, "packages/ui/src/renderer/dist/assets") + +export async function withBackend(daemon, tree, root, followLongReplies, run) { + root = privatePath(root) + await mkdir(root, { recursive: true }) + const password = randomUUID() + const config = path.join(root, "server.yaml") + await writeFile(config, JSON.stringify({ server: { opencodeBinary: daemon.cli } })) + const child = spawn(process.execPath, [ + fileURLToPath(new URL("./ts-wrapper.mjs", import.meta.url)), + "--http", "true", "--http-port", "0", "--https", "false", "--host", "127.0.0.1", "--ui-no-update", + "--ui-dir", path.dirname(assetsDirectory(tree)), "--config", config, "--workspace-root", daemon.project, + ], { env: { ...daemon.env, CLI_CONFIG: config, PERF_SERVER_DIST: fileURLToPath(new URL("../../packages/server/dist", import.meta.url)), + PERF_DAEMON_URL: daemon.url, PERF_DAEMON_PID: String(daemon.pid), CODENOMAD_SERVER_PASSWORD: password, + CODENOMAD_REMOTE_CONTROL: "disabled" }, cwd: root, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }) + const stopped = new Promise(resolve => child.once("close", resolve)) + let output = "", spawnError + child.on("error", error => { spawnError = error }) + for (const pipe of [child.stdout, child.stderr]) pipe.on("data", bytes => { output = (output + bytes).slice(-500_000) }) + try { + const deadline = Date.now() + 60_000 + let origin + while (!(origin = output.match(/Local Connection URL\s*:\s*(http:\/\/127\.0\.0\.1:\d+)/)?.[1])) { + if (spawnError) throw spawnError + if (child.exitCode !== null || child.signalCode !== null || Date.now() >= deadline) { + throw Error(`CodeNomad failed to start (${child.exitCode ?? child.signalCode ?? "timeout"}): ${output.slice(-3000)}`) + } + await sleep(50) + } + const request = (route, method, body, cookie) => fetch(`${origin}${route}`, { + method, headers: { origin, "content-type": "application/json", ...(cookie ? { cookie } : {}) }, + body: JSON.stringify(body), signal: AbortSignal.timeout(30_000), + }) + const response = await request("/api/auth/login", "POST", { username: "codenomad", password }) + const cookie = response.headers.get("set-cookie")?.split(";", 1)[0] + if (!response.ok || !cookie?.startsWith("codenomad_session=")) throw Error(`CodeNomad login failed (${response.status})`) + const patched = await request("/api/storage/state/ui", "PATCH", { + recentFolders: [{ path: daemon.project, projectName: "project", lastAccessed: Date.now() }], + }, cookie) + if (!patched.ok) throw Error(`Could not set recent folder (${patched.status})`) + if (followLongReplies) { + const setting = await request("/api/storage/config/ui", "PATCH", { settings: { holdLongAssistantReplies: false } }, cookie) + if (!setting.ok) throw Error(`Could not enable long-reply following (${setting.status})`) + } + await run(origin, cookie.slice(cookie.indexOf("=") + 1)) + } finally { + try { await stopFixtureChild(child, stopped) } finally { + await writeFile(path.join(root, "server.log"), output.replaceAll(password, "").replaceAll(daemon.password, "")) + } + } +} diff --git a/scripts/perf/ts-wrapper.mjs b/scripts/perf/ts-wrapper.mjs new file mode 100644 index 0000000000..5ee66d6b38 --- /dev/null +++ b/scripts/perf/ts-wrapper.mjs @@ -0,0 +1,26 @@ +// Attach the real backend to the owned fixture daemon; never start or stop a service. +import assert from "node:assert/strict" +import { register } from "node:module" +import { pathToFileURL, fileURLToPath } from "node:url" +import { privatePath } from "./isolation.mjs" + +const config = process.argv[process.argv.indexOf("--config") + 1] +assert.equal(config, process.env.CLI_CONFIG) +const dist = pathToFileURL(`${process.env.PERF_SERVER_DIST}/`) +const { resolveConfigLocation } = await import(new URL("config/location.js", dist)) +for (const p of Object.values(resolveConfigLocation(config))) privatePath(p) +register(new URL("loader.js", dist), import.meta.url) +const { OpenCodeCliService } = await import(new URL("workspaces/opencode-cli-service.js", dist)) +const { rememberRuntime } = await import(new URL("opencode/compatibility/runtime.js", dist)) +const url = new URL(process.env.PERF_DAEMON_URL) +assert.equal(url.hostname, "127.0.0.1") +const password = process.env.OPENCODE_SERVER_PASSWORD +const endpoint = { url: url.origin, auth: { type: "basic", username: "opencode", password } } +const info = await (await fetch(new URL("/api/info", url), { headers: { authorization: `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}` } })).json() +assert.equal(String(info.pid), process.env.PERF_DAEMON_PID) +rememberRuntime(endpoint, { version: info.version, pid: info.pid, discovery: "info" }) +OpenCodeCliService.prototype.discover = async () => endpoint +for (const action of ["ensure", "restart"]) OpenCodeCliService.prototype[action] = async () => { throw Error(`Bench forbids service ${action}`) } +const entry = new URL("index.js", dist) +process.argv[1] = fileURLToPath(entry) +await import(entry) diff --git a/scripts/perf/tui.mjs b/scripts/perf/tui.mjs new file mode 100644 index 0000000000..70556c937a --- /dev/null +++ b/scripts/perf/tui.mjs @@ -0,0 +1,76 @@ +import { createRequire } from "node:module" +import { MARKER, now } from "./lib.mjs" + +const require = createRequire(import.meta.url) + +export async function withTui(cli, daemon, session, run) { + const pty = require("./tools/node_modules/@lydell/node-pty") + const { Terminal } = require("./tools/node_modules/@xterm/headless") + const cols = 200, rows = 60 + const p = pty.spawn(cli, ["--server", daemon.url, "--session", session, daemon.project], { + name: "xterm-256color", cols, rows, cwd: daemon.project, + env: { ...daemon.env, TERM: "xterm-256color", COLORTERM: "truecolor" }, + }) + const exited = new Promise(resolve => p.onExit(resolve)) + const term = new Terminal({ cols, rows, allowProposedApi: true, scrollback: 0 }) + let screen = "", seen, waiter + const data = p.onData(raw => { + term.write(raw, () => { + const b = term.buffer.active + screen = "" + for (let y = 0; y < rows; y++) { + const line = b.getLine(b.viewportY + y) + if (y > 0 && !line?.isWrapped) screen += "\n" + screen += line?.translateToString(!b.getLine(b.viewportY + y + 1)?.isWrapped) ?? "" + } + const at = now() + if (seen) for (const marker of screen.match(MARKER) ?? []) seen[marker] ??= at + waiter?.(screen, at) + }) + }) + async function when(predicate, timeout = 10_000) { + let timer + try { + return await Promise.race([ + new Promise((resolve, reject) => { + timer = setTimeout(() => reject(Error("TUI screen wait timed out")), timeout) + waiter = (text, at) => { if (predicate(text)) resolve(at) } + waiter(screen, now()) + }), + exited.then(({ exitCode }) => { throw Error(`Fixture TUI exited (${exitCode})`) }), + ]) + } finally { + clearTimeout(timer) + waiter = undefined + } + } + try { + await when(text => text.includes("Foreground history") || /SEED\d+/.test(text), 60_000) + let typed = "" + await run({ + arm: () => { seen = {} }, + collect: () => ({ shown: seen }), + async typeKey(i) { + const char = "жщфывапролдэюбь"[i % 14] + typed += char + const at = now() + p.write(char) + return { at, elapsed: await when(text => text.includes(typed)) - at } + }, + async clear() { + p.write("\x7f".repeat(typed.length)) + if (typed) await when(text => !text.includes(typed)) + typed = "" + }, + }) + } finally { + data.dispose() + term.dispose() + // The PTY owns just this child. Refuse to leave it running after the sample. + p.kill() + let timer + try { + await Promise.race([exited, new Promise((_, reject) => { timer = setTimeout(() => reject(Error("Fixture TUI did not exit")), 5000) })]) + } finally { clearTimeout(timer) } + } +} diff --git a/scripts/precompress-ui.mjs b/scripts/precompress-ui.mjs new file mode 100644 index 0000000000..62e7cd6a2f --- /dev/null +++ b/scripts/precompress-ui.mjs @@ -0,0 +1,27 @@ +import { readFile, readdir, stat, unlink, writeFile } from "node:fs/promises" +import path from "node:path" +import { promisify } from "node:util" +import { brotliCompress, constants, gzip } from "node:zlib" + +const codecs = [ + [".br", promisify(brotliCompress), { params: { [constants.BROTLI_PARAM_QUALITY]: 5 } }], + [".gz", promisify(gzip), { level: 9 }], +] + +export async function precompressUi(directory, { includeHtml = true } = {}) { + for (const entry of await readdir(directory, { recursive: true, withFileTypes: true })) { + if (!entry.isFile()) continue + const file = path.join(entry.parentPath, entry.name) + if (!includeHtml && /\.html?\.(?:br|gz|deflate)(?:\.(?:br|gz|deflate))*$/i.test(entry.name)) { + await unlink(file) + continue + } + if (/\.(?:br|gz|deflate)$/i.test(entry.name) || !includeHtml && /\.html?$/i.test(entry.name)) continue + if ((await stat(file)).size < 1024) continue + const raw = await readFile(file) + await Promise.all(codecs.map(async ([suffix, compress, options]) => { + const compressed = await compress(raw, options) + if (compressed.length < raw.length) await writeFile(file + suffix, compressed) + })) + } +} diff --git a/scripts/precompress-ui.test.mjs b/scripts/precompress-ui.test.mjs new file mode 100644 index 0000000000..c965fec3e4 --- /dev/null +++ b/scripts/precompress-ui.test.mjs @@ -0,0 +1,34 @@ +import assert from "node:assert/strict" +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import test from "node:test" +import { brotliDecompressSync, gunzipSync } from "node:zlib" +import { precompressUi } from "./precompress-ui.mjs" + +test("precompresses a staged UI without changing original or small files", async t => { + const root = await mkdtemp(path.join(os.tmpdir(), "precompressed-ui-")) + t.after(() => rm(root, { recursive: true, force: true })) + const assets = path.join(root, "assets") + await mkdir(assets) + const asset = path.join(assets, "app.js") + const raw = Buffer.from("// static data\n".repeat(256)) + await writeFile(asset, raw) + await writeFile(path.join(assets, "tiny.js"), "let x=0") + await precompressUi(root) + assert.deepEqual((await readdir(assets)).sort(), ["app.js", "app.js.br", "app.js.gz", "tiny.js"]) + assert.deepEqual(await readFile(asset), raw) + assert.deepEqual(brotliDecompressSync(await readFile(`${asset}.br`)), raw) + assert.deepEqual(gunzipSync(await readFile(`${asset}.gz`)), raw) +}) + +test("a compatibility archive can keep HTML only at its protected original path", async t => { + const root = await mkdtemp(path.join(os.tmpdir(), "precompressed-compat-ui-")) + t.after(() => rm(root, { recursive: true, force: true })) + const text = "".repeat(256) + await writeFile(path.join(root, "INDEX.HTML"), text) + await writeFile(path.join(root, "INDEX.HTML.br"), "staged sidecar") + await writeFile(path.join(root, "books.js"), text) + await precompressUi(root, { includeHtml: false }) + assert.deepEqual((await readdir(root)).sort(), ["INDEX.HTML", "books.js", "books.js.br", "books.js.gz"]) +}) diff --git a/scripts/qualify-native-browser-app.mjs b/scripts/qualify-native-browser-app.mjs index bb43976f84..2d72dd5d8a 100644 --- a/scripts/qualify-native-browser-app.mjs +++ b/scripts/qualify-native-browser-app.mjs @@ -1,55 +1,83 @@ -// Real packaged app + backend + native parent, with a private OpenCode daemon and -// deterministic provider producing ordinary codenomad.browser agent tool calls. +// Real app + backend + native parent, with a private OpenCode daemon and a deterministic provider: +// the model opens the conversation through codenomad.inspect/act, then calls OpenCode's own +// `tools.browser.*` through Code Mode, served by CodeNomad's session preview. +// Usage: node scripts/qualify-native-browser-app.mjs import assert from "node:assert/strict" import { spawn, execFileSync } from "node:child_process" import { createServer } from "node:http" +import { createRequire } from "node:module" import { mkdir, readFile, writeFile, chmod, readdir } from "node:fs/promises" import { createHash, randomUUID } from "node:crypto" import os from "node:os" import path from "node:path" import { setTimeout as delay } from "node:timers/promises" +import { fileURLToPath } from "node:url" import { tsImport } from "tsx/esm/api" import Fastify from "fastify" import staticFiles from "@fastify/static" -import { fileURLToPath } from "node:url" -const [appPath, cli, outputPath] = process.argv.slice(2) -if (![appPath, cli, outputPath].every(value => value && path.isAbsolute(value))) throw Error("Usage: node scripts/qualify-native-browser-app.mjs ") -const output = outputPath, root = path.join(output, "private"), project = path.join(root, "project") +const [appPath, cli, output] = process.argv.slice(2) +const dev = appPath === "electron-dev" +if (!(dev || path.isAbsolute(appPath ?? "")) || ![cli, output].every(value => value && path.isAbsolute(value))) { + throw Error("Usage: node scripts/qualify-native-browser-app.mjs ") +} +const repo = fileURLToPath(new URL("..", import.meta.url)), root = path.join(output, "private"), project = path.join(root, "project") await mkdir(project, { recursive: true }) -const run = randomUUID().slice(0, 8), password = `p7-${randomUUID()}`, started = Date.now() -let desired, issued, providerError, app, daemon, daemonOutput = "", appOutput = "" -const tools = [], evidence = [] -const ui = Fastify() -await ui.register(staticFiles, { root: fileURLToPath(new URL("../packages/tauri-app/src-tauri/resources/server/public", import.meta.url)) }) -ui.setNotFoundHandler((_request, reply) => reply.sendFile("index.html")) -await ui.listen({ host: "127.0.0.1", port: 0 }) +const run = randomUUID().slice(0, 8), password = `p7-${randomUUID()}`, title = `Native browser qualification ${run}` +const { stopWindowsProcessTree } = await tsImport("../packages/server/src/process-tree.ts", import.meta.url) +let desired, issued, providerError, app, appStarted, ui, vite, viteStarted, daemon, daemonOutput = "", appOutput = "", viteOutput = "" +const evidence = [] + const fixtureHtml = await readFile(new URL("../packages/tauri-app/tests/browser-parent/app.html", import.meta.url), "utf8") const fixture = createServer((req, res) => { if (req.url === "/download") { res.setHeader("Content-Disposition", `attachment; filename="p7-${run}.txt"`) res.end(`native-download-${run}`) + } else if (req.url === "/api/count") { + res.setHeader("Content-Type", "application/json") + res.setHeader("Set-Cookie", `p7=${run}`) + res.end(JSON.stringify({ saved: true })) + } else if (req.url === "/frames") { + // A cross-site frame (localhost against 127.0.0.1) runs out of process; it and a worker start paused by diagnostics. + res.setHeader("Content-Type", "text/html") + res.end(`FramesFrame waiting Worker waiting +`) + } else if (req.url === "/child") { + res.setHeader("Content-Type", "text/html") + res.end(``) + } else if (req.url === "/frame-api") { + res.setHeader("Content-Type", "application/json") + res.end("{}") + } else if (req.url === "/worker.js") { + res.setHeader("Content-Type", "text/javascript") + res.end("postMessage('ran')") } else if (req.url === "/oauth") { res.setHeader("Content-Type", "text/html") res.end("OAuth fixture") + } else if (req.url === "/followed") { + res.setHeader("Content-Type", "text/html") + res.end("Followed

Link followed

") } else { res.setHeader("Content-Type", "text/html"); res.end(fixtureHtml) } }) const provider = createServer(async (req, res) => { try { let raw = ""; for await (const chunk of req) raw += chunk const body = JSON.parse(raw), catalog = (body.tools || []).map(tool => tool.function?.name) - const command = catalog.includes("codenomad_browser") ? desired : undefined - if (command) { desired = undefined; issued = true; tools.push(command) } + const call = desired && catalog.includes(desired.name) ? desired : undefined + if (call) { desired = undefined; issued = true } if (!body.stream) { res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify({ id: run, choices: [{ message: { role: "assistant", content: "Done" }, finish_reason: "stop" }] })); return } res.setHeader("Content-Type", "text/event-stream") const chunk = (delta, finish_reason = null) => res.write(`data: ${JSON.stringify({ id: run, object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta, finish_reason }] })}\n\n`) chunk({ role: "assistant" }) - if (command) chunk({ tool_calls: [{ index: 0, id: `p7-${tools.length}`, type: "function", function: { name: "codenomad_browser", arguments: JSON.stringify(command) } }] }) + if (call) chunk({ tool_calls: [{ index: 0, id: `p7-${evidence.length}`, type: "function", function: { name: call.name, arguments: JSON.stringify(call.args) } }] }) else chunk({ content: "Done" }) - chunk({}, command ? "tool_calls" : "stop"); res.end("data: [DONE]\n\n") + chunk({}, call ? "tool_calls" : "stop"); res.end("data: [DONE]\n\n") } catch (error) { providerError = error; res.destroy(error) } }) await Promise.all([fixture, provider].map(server => new Promise(done => server.listen(0, "127.0.0.1", done)))) + const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(OPENCODE_|CODENOMAD_)/.test(key))) for (const key of ["XDG_DATA_HOME", "XDG_CONFIG_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME"]) env[key] = path.join(root, key) Object.assign(env, { HOME: root, USERPROFILE: root, OPENCODE_TEST_HOME: root, @@ -60,20 +88,23 @@ await mkdir(env.OPENCODE_CONFIG_DIR, { recursive: true }) await writeFile(path.join(env.OPENCODE_CONFIG_DIR, "opencode.json"), "{}") env.OPENCODE_CONFIG_CONTENT = JSON.stringify({ model: "fixture/fixture", permissions: [{ action: "*", resource: "*", effect: "allow" }], providers: { fixture: { package: "@opencode/ai/providers/openai-compatible", settings: { baseURL: `http://127.0.0.1:${provider.address().port}/v1`, apiKey: "fixture" }, models: { fixture: {} } } } }) -async function until(check, timeout = 60000) { + +async function until(check, timeout = 60000, label = "condition") { const end = Date.now() + timeout - do { if (providerError) throw providerError; const value = await check(); if (value) return value; await delay(150) } while (Date.now() < end) - throw Error("Qualification condition timed out") + do { if (providerError) throw providerError; const value = await check(); if (value) return value; await delay(200) } while (Date.now() < end) + throw Error(`Qualification ${label} timed out`) } -function strings(value) { - if (typeof value === "string") return value - if (Array.isArray(value)) return value.map(strings).join("\n") - return value && typeof value === "object" ? Object.values(value).map(strings).join("\n") : "" +/** The ref of the first non-text outline line naming `label` (exactly when quoted). */ +function ref(content, label, exact = true) { + const line = content.split("\n").find(line => line.includes(exact ? `"${label}"` : label) && !line.trimStart().startsWith("- text ") && /\[[^\]\s]+\]/.test(line)) + assert.ok(line, `Missing ${label}: ${content}`) + return /\[([^\]\s]+)\]/.exec(line)[1] } + try { daemon = spawn(cli, ["serve", "--hostname", "127.0.0.1", "--port", "0", "--print-logs"], { cwd: root, env, windowsHide: true }) daemon.stdout.on("data", chunk => { daemonOutput += chunk }); daemon.stderr.on("data", chunk => { daemonOutput += chunk }) - await until(() => /http:\/\/127\.0\.0\.1:\d+/.test(daemonOutput)) + await until(() => /http:\/\/127\.0\.0\.1:\d+/.test(daemonOutput), 30000, "daemon") const baseUrl = daemonOutput.match(/http:\/\/127\.0\.0\.1:\d+/)[0] // The fixture CLI adapter pins lifecycle discovery to this retained private daemon. // All non-lifecycle commands run the real CLI under the same isolated environment. @@ -86,62 +117,112 @@ try { const lifecycle = new OpenCodeCliService({ label: "Private app qualification", timeoutMs: 10000, command: args => ({ command: cli, args, options: {} }) }, { execFile: async (_file, args) => ({ stdout: args.join(" ") === "service get password" ? password : baseUrl, stderr: "" }) }) const shared = new OpenCodeSharedService(), client = await shared.client({ kind: "lifecycle", identity: `p7-${run}`, lifecycle }) - const session = await client.session.create({ location: { directory: project }, title: "Native browser qualification" }) + const session = await client.session.create({ location: { directory: project }, title }) + + let uiUrl + if (dev) { + // The UI from source, served by Vite as in development. + const vitePort = 20000 + Math.floor(Math.random() * 20000) + viteStarted = new Date() + vite = spawn(process.execPath, [path.join(repo, "node_modules/vite/bin/vite.js"), "--host", "127.0.0.1", "--port", String(vitePort), "--strictPort"], + { cwd: path.join(repo, "packages/ui"), env: process.env, windowsHide: true }) + vite.stdout.on("data", chunk => { viteOutput += chunk }); vite.stderr.on("data", chunk => { viteOutput += chunk }) + await until(() => viteOutput.replace(/\x1b\[[0-9;]*m/g, "").includes(`127.0.0.1:${vitePort}`), 180000, "vite") + uiUrl = `http://127.0.0.1:${vitePort}/` + } else { + ui = Fastify() + await ui.register(staticFiles, { root: path.join(repo, "packages/tauri-app/src-tauri/resources/server/public") }) + ui.setNotFoundHandler((_request, reply) => reply.sendFile("index.html")) + await ui.listen({ host: "127.0.0.1", port: 0 }) + uiUrl = `http://127.0.0.1:${ui.server.address().port}` + } const config = path.join(root, "config.yaml") await writeFile(config, JSON.stringify({ server: { opencodeBinary: wrapper }, preferences: { lastUsedBinary: wrapper, locale: "en" }, opencodeBinaries: [{ path: wrapper, lastUsed: Date.now() }] })) - const appEnv = { ...process.env, CODENOMAD_PROFILE: `p7-${run}`, CLI_CONFIG: config, - VITE_DEV_SERVER_URL: `http://127.0.0.1:${ui.server.address().port}` } + const appEnv = { ...process.env, CODENOMAD_PROFILE: `p7-${run}`, CLI_CONFIG: config, VITE_DEV_SERVER_URL: uiUrl, ...(dev ? { NODE_ENV: "development" } : {}) } delete appEnv.ELECTRON_RUN_AS_NODE - app = spawn(appPath, [project], { cwd: path.dirname(appPath), env: appEnv, windowsHide: false }) + const electronApp = path.join(repo, "packages/electron-app") + const [command, args, cwd] = dev ? [createRequire(import.meta.url)("electron"), [electronApp, project], electronApp] : [appPath, [project], path.dirname(appPath)] + appStarted = new Date() + app = spawn(command, args, { cwd, env: appEnv, windowsHide: false }) app.stdout.on("data", chunk => { appOutput += chunk }); app.stderr.on("data", chunk => { appOutput += chunk }) await until(async () => { if (app.exitCode !== null) throw Error(`App exited ${app.exitCode}: ${appOutput.slice(-4000)}`) return (await client.plugin.list({ location: { directory: project } })).data.some(plugin => plugin.id === "codenomad.automation" && plugin.state.status === "active") - }, 90000) - async function call(command) { - issued = false; desired = command - await client.session.prompt({ sessionID: session.id, text: `Qualification step ${evidence.length + 1}. Use the browser tool.` }) - await client.session.wait({ sessionID: session.id }, { signal: AbortSignal.timeout(95000) }) - assert.ok(issued, "Native model tool catalog must invoke codenomad.browser") - const messages = await client.message.list({ sessionID: session.id, limit: 100, order: "asc" }) + }, 180000, "app backend") + + async function call(name, args, label = name) { + issued = false; desired = { name, args } + await client.session.prompt({ sessionID: session.id, text: `Qualification step ${evidence.length + 1}: ${label}.` }) + await client.session.wait({ sessionID: session.id }, { signal: AbortSignal.timeout(120000) }) + assert.ok(issued, `The model was offered ${name}`) + const messages = await client.message.list({ sessionID: session.id, limit: 200, order: "asc" }) const tool = messages.data.flatMap(message => message.type === "assistant" ? message.content : []) - .filter(part => part.type === "tool" && part.name.includes("browser")).at(-1) - assert.equal(tool?.state.status, "completed", JSON.stringify(tool?.state)) - const result = tool.state.content - evidence.push({ command, toolID: tool.id, status: tool.state.status, content: result }) + .filter(part => part.type === "tool" && [name, name.replace("_", ".")].includes(part.name)).at(-1) + const text = tool?.state.content?.filter(part => part.type === "text").map(part => part.text).join("\n") ?? "" + evidence.push({ label, name, args, status: tool?.state.status, text }) await writeFile(path.join(output, "tool-results.json"), JSON.stringify(evidence, null, 2)) - console.log(`PASS ${command.action}`) - return result + assert.equal(tool?.state.status, "completed", text) + console.log(`PASS ${label}`) + return text } + const step = async (label, code) => JSON.parse(await call("execute", { code }, label)) + + // The conversation is opened from the session list as a person does; its view then holds the browser. + // The session list can still be loading when the backend connects. + const outline = await until(async () => { + const text = await call("codenomad_inspect", { query: title }, "inspect session list") + return text.split("\n").some(line => line.includes(title) && /\[[^\]\s]+\]/.test(line)) && text + }, 120000, "session list") + await call("codenomad_act", { action: "click", ref: ref(outline, title, false) }, "open conversation") + await until(async () => (await client.session.get({ sessionID: session.id })).permissions?.some(rule => rule.action === "browser" && rule.effect === "allow"), 120000, "browser attachment") + console.log("PASS attached") + const url = `http://127.0.0.1:${fixture.address().port}/` - await call({ action: "open", url }) - let snapshot = strings(await call({ action: "snapshot" })) - const ref = label => { - const line = snapshot.split("\n").find(line => line.includes(`"${label}"`) && !line.trimStart().startsWith("- text ")) - assert.ok(line, `Missing ${label}: ${snapshot}`) - return /\[([^\]]+)\]/.exec(line)[1] - } - await call({ action: "click", ref: ref("Increment") }) - await call({ action: "type", ref: ref("Name"), text: "Native parity" }) - await call({ action: "select", ref: ref("Plan"), values: ["Pro"] }) - await call({ action: "press", ref: ref("Name"), key: "Enter" }) - await call({ action: "hover", ref: ref("Hover target") }) - await call({ action: "drag", ref: ref("Drag source"), to: ref("Drop target") }) - await call({ action: "scroll", ref: ref("Scroll box"), direction: "down", amount: 150 }) - for (const text of ["Count 1", "Pressed Enter", "Hovered", "Dragged", "Scrolled"]) await call({ action: "wait", text }) - await call({ action: "click", ref: ref("OAuth popup") }) - await call({ action: "wait", text: "OAuth complete" }) - await call({ action: "click", ref: ref("Download fixture") }) + const opened = await step("open and snapshot", `const tab = await tools.browser.tabs.open({ url: ${JSON.stringify(url)} }); const snap = await tools.browser.snapshot({ tabID: tab.id }); return { tab, content: snap.content }`) + const tabID = JSON.stringify(opened.tab.id), content = opened.content + const at = label => JSON.stringify(ref(content, label)) + const act = await step("page actions", `const tabID = ${tabID}; +await tools.browser.click({ tabID, ref: ${at("Increment")} }); +await tools.browser.fill({ tabID, ref: ${at("Name")}, text: "Native parity" }); +// press has no ref: the key goes to the focused field. +await tools.browser.click({ tabID, ref: ${at("Name")} }); +await tools.browser.press({ tabID, key: "Enter" }); +// Plan writes the same status as the key handler, so Enter is read first. +const waits = []; +for (const text of ["Count 1", "Pressed Enter"]) waits.push((await tools.browser.wait({ tabID, text, timeout: 5000 })).met); +await tools.browser.select({ tabID, ref: ${at("Plan")}, values: ["Pro"] }); +await tools.browser.hover({ tabID, ref: ${at("Hover target")} }); +await tools.browser.drag({ tabID, from: ${at("Drag source")}, to: ${at("Drop target")} }); +await tools.browser.scroll({ tabID, deltaY: 150 }); +for (const text of ["Plan Pro", "Hovered", "Dragged"]) waits.push((await tools.browser.wait({ tabID, text, timeout: 5000 })).met); +const found = (await tools.browser.find({ tabID, text: "Native parity" })).content.includes("Native parity"); +let refused, copyRefused; +try { await tools.browser.evaluate({ tabID, script: "document.title" }) } catch (error) { refused = String(error?.message ?? error) } +try { await tools.browser.press({ tabID, key: "Control+C" }) } catch (error) { copyRefused = String(error?.message ?? error) } +let pickerRefused; +try { await tools.browser.click({ tabID, ref: ${at("Upload")} }) } catch (error) { pickerRefused = String(error?.message ?? error) } +// A load state names the load condition; a bare timeout is a pause. +const loaded = (await tools.browser.wait({ tabID, state: "load", timeout: 5000 })).met; +await tools.browser.click({ tabID, ref: ${at("OAuth popup")} }); +const oauth = (await tools.browser.wait({ tabID, text: "OAuth complete", timeout: 10000 })).met; +await tools.browser.click({ tabID, ref: ${at("Download fixture")} }); +return { waits, found, refused, copyRefused, pickerRefused, loaded, oauth }`) + assert.deepEqual(act.waits, [true, true, true, true, true]) + assert.equal(act.found, true) + assert.match(act.refused ?? "", /not available in the CodeNomad browser/) + assert.match(act.copyRefused ?? "", /clipboard or context-menu shortcuts/) + assert.match(act.pickerRefused ?? "", /native file picker/) + assert.equal(act.loaded, true, "wait for load") + assert.equal(act.oauth, true, "OAuth opener/postMessage") const downloads = process.platform === "linux" ? execFileSync("xdg-user-dir", ["DOWNLOAD"], { encoding: "utf8" }).trim() : path.join(os.homedir(), "Downloads") const download = await until(async () => { const name = (await readdir(downloads)).find(name => name.includes(`p7-${run}.txt`)) return name && await readFile(path.join(downloads, name), "utf8").catch(() => "") === `native-download-${run}` ? name : undefined - }) - assert.equal(await readFile(path.join(downloads, download), "utf8"), `native-download-${run}`) + }, 60000, "download") if (!process.env.P7_SKIP_NATIVE_DIALOG) { - await call({ action: "click", ref: ref("Native dialog") }) + await step("native dialog", `await tools.browser.click({ tabID: ${tabID}, ref: ${at("Native dialog")} }); return {}`) await delay(1500) if (process.platform === "darwin") execFileSync("python3", [new URL("fixtures/accept-owned-browser-dialog.py", import.meta.url).pathname, String(app.pid)]) else if (process.platform === "linux") { @@ -149,23 +230,74 @@ try { execFileSync("xdotool", ["windowactivate", "--sync", windows.at(-1)]) execFileSync("xdotool", ["key", "Return"]) } else { - execFileSync("pwsh", ["-NoProfile", "-File", new URL("fixtures/accept-owned-browser-dialog.ps1", import.meta.url).pathname.replace(/^\/(\w:)/, "$1"), "-AppProcessId", String(app.pid)], { windowsHide: true, timeout: 20000 }) + execFileSync("pwsh", ["-NoProfile", "-File", fileURLToPath(new URL("fixtures/accept-owned-browser-dialog.ps1", import.meta.url)), "-AppProcessId", String(app.pid)], { encoding: "utf8", windowsHide: true, timeout: 20000 }) } - await call({ action: "wait", text: "Dialog accepted" }) + const accepted = await step("dialog accepted", `return { met: (await tools.browser.wait({ tabID: ${tabID}, text: "Dialog accepted", timeout: 10000 })).met }`) + assert.equal(accepted.met, true) + } + // WebKit previews (macOS and Linux Tauri) refuse diagnostics: there the qualification checks that refusal. + const support = await step("diagnostics support", `try { await tools.browser.console({ tabID: ${tabID} }); return { supported: true } } +catch (error) { return { supported: false, message: String(error?.message ?? error) } }`) + if (!support.supported) { + assert.ok(!dev && process.platform !== "win32" && /WebKit previews/.test(support.message), JSON.stringify(support)) + } else { + // Increment logged a warning and posted its count: OpenCode's console and network tools read them back. + const diagnostics = await step("console and network", `const tabID = ${tabID}; +const logged = await tools.browser.console({ tabID, level: "warning" }); +const listed = await tools.browser.network.list({ tabID, urlContains: "/api/count" }); +const got = listed.requests[0] && await tools.browser.network.get({ tabID, id: listed.requests[0].id, includeBody: true }); +return { warnings: logged.messages.map(entry => entry.text), requests: listed.requests.map(item => [item.method, item.statusCode, item.state]), + requestBody: got?.requestBody, responseBody: got?.responseBody, + cookie: got?.responseHeaders.find(header => header.name === "set-cookie")?.value }`) + assert.ok(diagnostics.warnings.includes("Count is 1"), JSON.stringify(diagnostics)) + assert.deepEqual(diagnostics.requests, [["POST", 200, "completed"]]) + assert.deepEqual(diagnostics.requestBody, { state: "text", text: "{\"count\":1}", truncated: false }) + assert.deepEqual(diagnostics.responseBody, { state: "text", text: "{\"saved\":true}", truncated: false }) + assert.equal(diagnostics.cookie, "") + // Out-of-process frames and workers start paused: they must run, and the frame's own startup is captured. + const frames = await step("frames and workers", `const tabID = ${tabID}; +await tools.browser.navigate({ tabID, url: ${JSON.stringify(`http://127.0.0.1:${fixture.address().port}/frames`)} }); +const waits = []; +for (const text of ["Frame loaded", "Worker ran"]) waits.push((await tools.browser.wait({ tabID, text, timeout: 10000 })).met); +// The page has its body; the network service reports the request finished a moment later. +let listed; +for (let attempt = 0; attempt < 20; attempt++) { + listed = await tools.browser.network.list({ tabID, urlContains: "/frame-api" }); + if (listed.requests.length && listed.requests.every(item => item.state !== "pending")) break; + await tools.browser.wait({ tabID, delayMs: 100 }); +} +const logged = await tools.browser.console({ tabID, level: "warning" }); +return { waits, requests: listed.requests.map(item => [item.method, item.statusCode, item.state]), warnings: logged.messages.map(entry => entry.text) }`) + assert.deepEqual(frames.waits, [true, true], JSON.stringify(frames)) + assert.deepEqual(frames.requests, [["GET", 200, "completed"]], JSON.stringify(frames)) + assert.ok(frames.warnings.includes(`frame warning ${run}`), JSON.stringify(frames)) } - snapshot = strings(await call({ action: "snapshot" })) - assert.match(snapshot, /Native parity/) - const image = strings(await call({ action: "screenshot" })) - const png = /data:image\/png;base64,([A-Za-z0-9+/=]+)/.exec(image) - assert.ok(png, "Browser agent tool must return PNG data") - await writeFile(path.join(output, "browser.png"), Buffer.from(png[1], "base64")) - await writeFile(path.join(output, "result.json"), JSON.stringify({ passed: true, run, sessionID: session.id, project, appPath, - appSHA256: createHash("sha256").update(await readFile(appPath)).digest("hex"), tools: tools.map(command => command.action), download, screenshot: !!png, - nativeDialog: !process.env.P7_SKIP_NATIVE_DIALOG }, null, 2)) - await shared.shutdown() + // The clicks above ran on a page scrolled by a wheel step; these aim far below the fold, then leave the page. + const reopened = await step("reopen and snapshot", `const tabID = ${tabID}; +await tools.browser.navigate({ tabID, url: ${JSON.stringify(url)} }); +return { content: (await tools.browser.snapshot({ tabID })).content }`) + const below = label => JSON.stringify(ref(reopened.content, label)) + const followed = await step("below the fold and a followed link", `const tabID = ${tabID}; +await tools.browser.click({ tabID, ref: ${below("Below the fold")} }); +const clicked = (await tools.browser.wait({ tabID, text: "Below clicked", timeout: 5000 })).met; +await tools.browser.click({ tabID, ref: ${below("Follow link")} }); +return { clicked, arrived: (await tools.browser.wait({ tabID, text: "Link followed", timeout: 5000 })).met }`) + assert.equal(followed.clicked, true, "a click on an element the page had to scroll to") + assert.equal(followed.arrived, true, "a click that follows a link succeeds") + const shot = await step("screenshot", `const shot = await tools.browser.screenshot({ tabID: ${tabID} }); return { files: shot.files }`) + assert.equal(shot.files?.[0]?.mime, "image/png") + await writeFile(path.join(output, "result.json"), JSON.stringify({ passed: true, run, sessionID: session.id, project, app: appPath, + appSHA256: dev ? undefined : createHash("sha256").update(await readFile(appPath)).digest("hex"), + steps: evidence.map(entry => entry.label), download, screenshot: shot.files[0].path, nativeDialog: !process.env.P7_SKIP_NATIVE_DIALOG }, null, 2)) + // The private daemon stops below; a pending shutdown read must not hold the run. + await Promise.race([shared.shutdown(), delay(10000)]) } finally { - app?.kill(); daemon?.kill() - if (process.platform !== "win32" && app) { + if (process.platform === "win32") { + for (const [child, started] of [[app, appStarted], [vite, viteStarted]]) { + if (child?.pid && child.exitCode === null) await stopWindowsProcessTree(child.pid, started).catch(error => console.error("stop", error)) + } + } else { + app?.kill(); vite?.kill() for (const [, pid] of appOutput.matchAll(/spawned pid=(\d+)/g)) { try { const args = execFileSync("ps", ["-ww", "-p", pid, "-o", "command="], { encoding: "utf8" }) @@ -173,8 +305,13 @@ try { } catch { /* The exact owned backend may already have stopped. */ } } } + daemon?.kill() await writeFile(path.join(output, "app.log"), appOutput) + await writeFile(path.join(output, "vite.log"), viteOutput) await writeFile(path.join(output, "opencode.log"), daemonOutput) await Promise.all([fixture, provider].map(server => new Promise(done => server.close(done)))) - await ui.close() + await ui?.close() } +console.log("PASS qualification") +// The shared service may keep handles open after its bounded shutdown. +process.exit(0) diff --git a/scripts/recurring-simple-native/journeys.mjs b/scripts/recurring-simple-native/journeys.mjs deleted file mode 100644 index 7181bcbaf7..0000000000 --- a/scripts/recurring-simple-native/journeys.mjs +++ /dev/null @@ -1,351 +0,0 @@ -// Native journeys E/F/W/Q for scripts/test-recurring-simple-native.mjs. The deterministic -// provider plays the model through ordinary native tools only; no journal/schedule shortcut. -import assert from "node:assert/strict" -import { randomUUID } from "node:crypto" -import { existsSync } from "node:fs" -import { readFile, writeFile } from "node:fs/promises" -import path from "node:path" -import { DatabaseSync } from "node:sqlite" -import { setTimeout as delay } from "node:timers/promises" -import { tsImport } from "tsx/esm/api" - -const OBSERVE = 10_000 // > 3 s settlement debounce: a pending passage must stay pending. -const id = prefix => `${prefix}_${randomUUID().replaceAll("-", "")}` -const toolResult = (turn, callID) => turn.messages.filter(m => m.role === "tool" && m.tool_call_id === callID) - .map(m => typeof m.content === "string" ? m.content : JSON.stringify(m.content)).join("") -const callOf = (turn, predicate) => turn.messages.flatMap(m => m.tool_calls ?? []).find(predicate) - -export async function runJourneys(c) { - const location = { directory: c.project } - const messages = async sessionID => (await c.client.message.list({ sessionID, limit: 100 })).data - const active = async () => Object.keys(await c.client.session.active()) - const calls = sessionID => c.evidence.providerCalls.filter(call => call.sessionID === sessionID) - // Read-only view of this fixture's own isolated database. - const db = query => { const d = new DatabaseSync(c.env.OPENCODE_DB, { readOnly: true }); try { return query(d) } finally { d.close() } } - // The product's own mark namespace, so a renamed prefix cannot make the mark checks vacuous. - const { HUMAN_MARK_STORAGE_PREFIX } = await tsImport("../../packages/server/src/missions/human-answer.ts", import.meta.url) - const markKeys = `%${HUMAN_MARK_STORAGE_PREFIX}/%` - const document = scheduleID => db(d => d.prepare("SELECT value FROM kv").all().map(row => { try { return JSON.parse(row.value) } catch { return undefined } }) - .find(value => value?.id === scheduleID && Array.isArray(value.cursors))) - const idles = sessionID => db(d => d.prepare("SELECT json_extract(data,'$.outcome') AS outcome FROM session_message WHERE session_id=? AND type='idle'").all(sessionID)).map(row => row.outcome) - const startText = async sessionID => (await messages(sessionID)).filter(m => m.type === "synthetic").map(m => m.text).join("\n") - async function manual(scheduleID, n) { - const { payload } = await c.runNow(scheduleID) - let pending - await c.until(async () => (pending = await c.snapshot(scheduleID)).pending?.conversationID) - return { requestID: payload.requestID, passageID: pending.pending.passageID, sessionID: pending.pending.conversationID, - messageID: pending.pending.messageID, n } - } - async function archived(scheduleID, count) { - let after - await c.until(async () => (after = await c.snapshot(scheduleID)).history.length === count, c.SETTLE, c.SLOW) - return { after, observedAt: Date.now() } - } - const far = () => c.nextMinute(6 * 3_600_000) - - if (c.journeys.includes("E")) { - c.setStage("E family quiescence") - const marker = path.join(c.project, "e-wait.mjs"), release = path.join(c.project, "e-shell-release") - await writeFile(marker, `import { existsSync, writeFileSync } from "node:fs" -writeFileSync("e-shell-started", String(Date.now())) -setTimeout(() => process.exit(2), 300000) // never outlive the fixture -const timer = setInterval(() => { if (!existsSync("e-shell-release")) return - clearInterval(timer); writeFileSync("e-shell-ended", String(Date.now())); console.log("E_SHELL_" + "DONE"); process.exit(0) }, 200) -`) - c.scenarios.push(turn => { - if (turn.first.includes("[E-CHILD]")) return { hold: "E-child", text: "E_CHILD_RESULT" } - if (!turn.first.includes("[JOURNEY-E]")) return undefined - if (!turn.calls.includes("subagent")) return { calls: [ - { name: "subagent", args: { agent: "fixture-worker", description: "Background child", prompt: "[E-CHILD] Produce the child result", background: true } }, - { name: "shell", args: { command: "node e-wait.mjs", description: "Background wait", background: true } }] } - if (turn.calls.includes("mission_report")) return { text: "Done" } - return turn.all.includes("E_CHILD_RESULT") && turn.all.includes("E_SHELL_DONE") - ? { calls: [{ name: "mission_report", args: { outcome: "completed", summary: "Background child and shell both finished", final: true } }] } - : { text: "Waiting for background work" } - }) - const scheduleID = await c.create("Native family quiescence", far(), { instructions: "[JOURNEY-E] Delegate a background child and a background shell; report only after both finish." }) - const E = c.evidence.journeys.E = { id: scheduleID } - try { - const passage = E.passage = await manual(scheduleID, 0) - const coordinator = passage.sessionID - await c.until(() => c.holds.has("E-child") && existsSync(path.join(c.project, "e-shell-started"))) - E.childID = (await c.sessions()).find(s => s.parentID === coordinator)?.id - assert.ok(E.childID, "real native subagent child") - const waits = () => calls(coordinator).filter(call => call.name === "Waiting for background work").length - await c.until(async () => waits() >= 1 && !(await active()).includes(coordinator)) - E.coordinatorIdleAt = Date.now() - await delay(OBSERVE) - E.whileChildAndShell = { at: Date.now(), active: await active(), snapshot: await c.snapshot(scheduleID) } - assert.ok(E.whileChildAndShell.snapshot.pending, "running child + shell keep the passage pending") - assert.equal(E.whileChildAndShell.snapshot.history.length, 0) - assert.ok(E.whileChildAndShell.active.includes(E.childID), "background child natively active") - E.childReleasedAt = Date.now(); c.holds.get("E-child")(); c.holds.delete("E-child") - await c.quiet(E.childID); E.childEndedAt = Date.now() - await c.until(async () => waits() >= 2 && !(await active()).includes(coordinator)) - await delay(OBSERVE) - E.whileShell = { at: Date.now(), active: await active(), snapshot: await c.snapshot(scheduleID) } - assert.ok(E.whileShell.snapshot.pending, "a running background shell keeps the passage pending") - assert.equal(E.whileShell.snapshot.history.length, 0) - assert.equal(calls(coordinator).some(call => call.name === "mission_report"), false, "no final report before both end") - E.shellReleasedAt = Date.now(); await writeFile(release, "go") - await c.until(() => calls(coordinator).some(call => call.name === "mission_report"), 120_000) - E.reportAt = calls(coordinator).find(call => call.name === "mission_report").at - E.shellEndedAt = Number(await readFile(path.join(c.project, "e-shell-ended"), "utf8")) - await c.quiet(coordinator); E.quiescentAt = Date.now() - const { after, observedAt } = await archived(scheduleID, 1) - E.archiveObservedAt = observedAt; E.archiveLatencyMs = observedAt - E.quiescentAt - assert.equal(after.latestResult.outcome, "completed"); assert.equal(after.latestResult.passageID, passage.passageID) - assert.ok(E.childEndedAt < E.shellEndedAt && E.shellEndedAt < E.reportAt && E.reportAt < E.archiveObservedAt, "child → shell → report → archive") - // Native background-completion notices are synthetic too; only one is a Mission start. - const synthetic = (await messages(coordinator)).filter(m => m.type === "synthetic" || m.type === "user") - E.starts = synthetic.filter(m => m.metadata?.["codenomad.mission"]).map(m => m.id) - E.nativeNotices = synthetic.filter(m => !m.metadata?.["codenomad.mission"]).map(m => ({ id: m.id, source: m.metadata?.source ?? m.metadata?.type ?? null })) - assert.deepEqual(E.starts, [passage.messageID ?? E.starts[0]]); assert.equal(E.starts.length, 1) - E.tools = calls(coordinator).map(call => call.name) - E.result = "passed" - } finally { if (!existsSync(release)) await writeFile(release, "cleanup"); c.holds.get("E-child")?.() } - await c.control(scheduleID, "stop") - } - - if (c.journeys.includes("L")) { - // Extended family: more native sessions than the former 32-session settlement bound. - c.setStage("L large family") - const CHILDREN = 34, held = `L-child-${CHILDREN - 1}` - c.scenarios.push(turn => { - const child = /\[L-CHILD-(\d+)\]/.exec(turn.first) - if (child) return { ...(Number(child[1]) === CHILDREN - 1 ? { hold: held } : {}), text: `L_CHILD_RESULT_${child[1]}_` } - if (!turn.first.includes("[JOURNEY-L]")) return undefined - // Batches: one burst of 34 concurrent launches exceeds the 2 s per-send profile - // environment read budget on a loaded host and fails some launches closed. - const next = Array.from({ length: CHILDREN }, (_, i) => i).filter(i => !turn.all.includes(`[L-CHILD-${i}]`)).slice(0, 6) - if (next.length) return { calls: next.map(i => ({ name: "subagent", - args: { agent: "fixture-worker", description: `Background child ${i}`, prompt: `[L-CHILD-${i}] Produce child result ${i}`, background: true } })) } - if (turn.calls.includes("mission_report")) return { text: "Done" } - return Array.from({ length: CHILDREN }, (_, i) => `L_CHILD_RESULT_${i}_`).every(text => turn.all.includes(text)) - ? { calls: [{ name: "mission_report", args: { outcome: "completed", summary: "Every background child finished", final: true } }] } - : { text: "Waiting for background work" } - }) - const scheduleID = await c.create("Native large family", far(), { instructions: "[JOURNEY-L] Delegate many background children; report only after all finish." }) - const L = c.evidence.journeys.L = { id: scheduleID, children: CHILDREN } - try { - const passage = L.passage = await manual(scheduleID, 0) - const coordinator = passage.sessionID - const family = async () => (await c.sessions()).filter(s => s.parentID === coordinator).map(s => s.id) - await c.until(async () => c.holds.has(held) && (await family()).length === CHILDREN, 120_000) - L.familySize = (await family()).length + 1 - assert.ok(L.familySize > 33, "family larger than the former settlement bound") - await c.until(async () => (await active()).filter(id => id !== coordinator).length === 1, 120_000) - L.heldChild = (await active()).find(id => id !== coordinator) - await delay(OBSERVE) - L.whileHeld = { at: Date.now(), active: await active(), snapshot: await c.snapshot(scheduleID) } - assert.ok(L.whileHeld.snapshot.pending, "one active descendant keeps a large family pending") - assert.equal(L.whileHeld.snapshot.history.length, 0) - c.holds.get(held)(); c.holds.delete(held) - await c.until(() => calls(coordinator).some(call => call.name === "mission_report"), 120_000) - await c.quiet(coordinator); L.quiescentAt = Date.now() - const { after, observedAt } = await archived(scheduleID, 1) - L.archiveLatencyMs = observedAt - L.quiescentAt - assert.equal(after.latestResult.outcome, "completed"); assert.equal(after.latestResult.passageID, passage.passageID) - assert.equal(after.pending, null) - L.result = "passed" - } finally { c.holds.get(held)?.() } - await c.control(scheduleID, "stop") - } - - if (c.journeys.includes("F")) { - c.setStage("F native provider failure") - c.scenarios.push(turn => turn.first.includes("[JOURNEY-F]") ? { fail: true } : undefined) - const scheduleID = await c.create("Native provider failure", far(), { instructions: "[JOURNEY-F] Attempt the work." }) - const F = c.evidence.journeys.F = { id: scheduleID } - const passage = F.passage = await manual(scheduleID, 0) - await c.until(() => calls(passage.sessionID).length > 0) - await c.quiet(passage.sessionID); F.quiescentAt = Date.now() - const { after, observedAt } = await archived(scheduleID, 1) - F.archiveLatencyMs = observedAt - F.quiescentAt - F.idleOutcomes = idles(passage.sessionID); F.eventRows = db(d => d.prepare("SELECT count(*) AS count FROM event").get().count) - assert.equal(after.latestResult.outcome, "failed"); assert.equal(after.latestResult.reason, undefined) - assert.ok(F.idleOutcomes.includes("failed"), "native projected the terminal failure") - F.providerCallsAtArchive = calls(passage.sessionID).length - await delay(OBSERVE) - F.providerCallsLater = calls(passage.sessionID).length - F.starts = await c.passageStarts(passage.sessionID) - assert.equal(F.starts.length, 1); assert.equal(F.providerCallsLater, F.providerCallsAtArchive, "Missions never retries or replays") - assert.equal((await c.snapshot(scheduleID)).pending, null) - F.result = "passed" - await c.control(scheduleID, "stop") - } - - if (c.journeys.includes("W")) { - c.setStage("W watched conversations") - let failW = false - c.scenarios.push(turn => { - // The coordinator's start text embeds the source prose, so match it first. - if (!turn.first.includes("[JOURNEY-W]")) return turn.first.includes("[W-SOURCE]") ? { text: "W-REPLY" } : undefined - if (failW) return { fail: true } - return turn.calls.includes("mission_report") ? { text: "Done" } - : { calls: [{ name: "mission_report", args: { outcome: "completed", summary: "Watched messages processed", final: true } }] } - }) - const source = await c.client.session.create({ location, title: "Watched ordinary conversation" }) - const say = async text => { await c.client.session.prompt({ sessionID: source.id, text }); await c.until(async () => (await messages(source.id)).some(m => m.type === "user" && m.text === text)); await c.quiet(source.id) } - await say("[W-SOURCE] W-MSG-1") - const scheduleID = await c.create("Native watched conversation", far(), { instructions: "[JOURNEY-W] Process new watched messages.", watched: [source.id] }) - const W = c.evidence.journeys.W = { id: scheduleID, sourceID: source.id, passages: [] } - const cursor = () => document(scheduleID)?.cursors.find(item => item.conversationID === source.id)?.messageID ?? null - const run = async (n, expectFailed) => { - failW = expectFailed - const before = cursor(), passage = await manual(scheduleID, n) - const text = await startText(passage.sessionID) - await c.quiet(passage.sessionID) - const { after } = await archived(scheduleID, n + 1) - failW = false - const item = { ...passage, cursorBefore: before, cursorAfter: cursor(), outcome: after.latestResult.outcome, - afterMessageID: text.match(/"afterMessageID":("[^"]*"|null)/)?.[1] ?? "absent", - includes: ["W-MSG-1", "W-MSG-2", "W-MSG-3", "W-REPLY"].filter(word => text.includes(word)), - starts: (await c.passageStarts(passage.sessionID)).length } - W.passages.push(item); return item - } - const sourceIDs = async () => (await messages(source.id)).map(m => m.id) - const p1 = await run(0, false) - assert.equal(p1.outcome, "completed"); assert.ok(p1.includes.includes("W-MSG-1")); assert.equal(p1.afterMessageID, "null") - assert.ok(p1.cursorAfter && (await sourceIDs()).includes(p1.cursorAfter), "completed advances the cursor to a real source message") - await say("W-MSG-2") - const p2 = await run(1, false) - assert.equal(p2.outcome, "completed"); assert.deepEqual(p2.includes.filter(w => w.startsWith("W-MSG")), ["W-MSG-2"], "only messages since the cursor") - assert.equal(p2.afterMessageID, JSON.stringify(p1.cursorAfter)); assert.notEqual(p2.cursorAfter, p1.cursorAfter) - await say("W-MSG-3") - const p3 = await run(2, true) - assert.equal(p3.outcome, "failed"); assert.ok(p3.includes.includes("W-MSG-3")) - assert.equal(p3.cursorAfter, p2.cursorAfter, "failed passage leaves the cursor unchanged") - const p4 = await run(3, false) - assert.equal(p4.outcome, "completed"); assert.ok(p4.includes.includes("W-MSG-3"), "unprocessed messages are offered again") - assert.equal(p4.afterMessageID, JSON.stringify(p2.cursorAfter)) - for (const p of W.passages) assert.equal(p.starts, 1) - W.result = "passed" - await c.control(scheduleID, "stop") - } - - if (c.journeys.includes("Q")) { - c.setStage("Q Wayfinder human Form") - const QUESTION = { question: "Choose the seam?", header: "Seam", options: [{ label: "Module", description: "Own the boundary" }] } - let q = {} - c.scenarios.push(async turn => { - // The decision worker returns a brief; only the passage coordinator asks the human. - if (turn.first.includes("# CodeNomad Mission Assignment") && turn.first.includes("[JOURNEY-Q]")) - return { text: "DECISION_BRIEF: Module owns the boundary and is cheap to undo. Recommendation: Module." } - if (!turn.first.includes("[JOURNEY-Q]")) return undefined - if (!turn.calls.includes("mission_delegate")) return { calls: [{ name: "mission_delegate", id: q.delegateCall = id("call_qdel"), - args: { taskKey: "decision", title: "Choose the seam", role: "decision", brief: "Return a decision brief for the seam." } }] } - if (!turn.calls.includes("subagent")) { - const raw = toolResult(turn, q.delegateCall), start = raw.indexOf("{") - q.delegated = JSON.parse(raw.slice(start, raw.lastIndexOf("}") + 1)) - return { calls: [{ name: "subagent", id: q.subagentCall = id("call_qsub"), args: { agent: "fixture-worker", description: "Decision worker", prompt: q.delegated.assignmentPrompt } }] } - } - // The question names the decision task it answers (its questionTag). - q.question ??= { ...QUESTION, question: `${QUESTION.question} ${q.delegated.questionTag}` } - if (!turn.calls.includes("question")) return { calls: [{ name: "question", id: q.questionCall = id("call_qask"), args: { questions: [q.question] } }] } - const decision = callOf(turn, call => call.function.name === "mission_report" && JSON.parse(call.function.arguments).taskKey === "decision") - if (!decision) { - // The UI run cites the answer artifact inspect lists; the ordinary run cites the same exact question without a mark. - if (q.mode === "ui" && !turn.calls.includes("mission_inspect")) - return { calls: [{ name: "mission_inspect", id: q.inspectCall = id("call_qins"), args: { taskKey: "decision" } }] } - let artifact - if (q.mode === "ui") { - const raw = toolResult(turn, q.inspectCall) - artifact = JSON.parse(raw.slice(raw.indexOf("{"), raw.lastIndexOf("}") + 1)).humanAnswers?.candidates?.find(item => item.askedBy === "coordinator")?.artifact - } else { - const asked = (await messages(turn.sessionID)).find(m => m.type === "assistant" && m.content?.some(p => p.type === "tool" && p.id === q.questionCall)) - const contract = q.delegated.contract - artifact = { kind: "decision", decidedBy: "human", question: q.question.question, answer: "Module", provenance: { kind: "coordinator-form-answer", - contract: { missionID: contract.missionID, taskKey: contract.taskKey, generation: contract.generation }, - sessionID: turn.sessionID, formID: q.formID, messageID: asked.id, toolCallID: q.questionCall, fieldKey: "q0" } } - } - q.provenance = artifact?.provenance - return { calls: [{ name: "mission_report", id: q.decisionCall = id("call_qrep"), args: { taskKey: "decision", outcome: "completed", - summary: "The human chose Module", evidence: [], next: [], artifact } }] } - } - q.decisionResult ??= toolResult(turn, decision.id) - if (!/"disposition"\s*:\s*"reported"/.test(q.decisionResult)) return { text: "Gate refused; no human decision recorded" } - return turn.calls.filter(name => name === "mission_report").length >= 2 ? { text: "Done" } - : { calls: [{ name: "mission_report", args: { outcome: "completed", summary: "Human decision recorded", final: true } }] } - }) - const scheduleID = await c.create("Native Wayfinder decision", far(), { template: "wayfinder", instructions: "[JOURNEY-Q] Decide the seam with the human through a native Form." }) - const Q = c.evidence.journeys.Q = { id: scheduleID, runs: {} } - for (const [n, mode] of [[0, "ui"], [1, "ordinary"]]) { - q = { mode } - const R = Q.runs[mode] = { passage: await manual(scheduleID, n) } - let forms = [] - await c.until(async () => (forms = (await c.client.form.list({ location })).data).length === 1, 120_000) - const form = R.form = { id: forms[0].id, sessionID: forms[0].sessionID, kind: forms[0].metadata?.kind } - assert.equal(form.sessionID, R.passage.sessionID, "the passage coordinator asks from its own conversation, never the decision worker") - q.formID = form.id - await delay(OBSERVE) - R.whileForm = await c.snapshot(scheduleID) - assert.ok(R.whileForm.pending, "a pending Form keeps the passage pending"); assert.equal(R.whileForm.history.length, n) - const reply = await c.bridge().inject({ method: "POST", url: `/workspaces/${c.workspace().id}/instance/api/session/${form.sessionID}/form/${form.id}/reply`, - headers: { cookie: "session=isolated-human", "content-type": "application/json", ...(mode === "ui" ? { "x-codenomad-human-answer": "1" } : {}) }, - payload: JSON.stringify({ answer: { q0: "Module" } }) }) - R.reply = { status: reply.statusCode, body: reply.body.slice(0, 300) } - // Both the marked dock route and the ordinary proxy answer native's 204 No Content, - // the only success status the generated client accepts for form replies. - assert.equal(reply.statusCode, 204, reply.body) - await c.quiet(R.passage.sessionID) - const { after } = await archived(scheduleID, n + 1) - R.outcome = after.latestResult.outcome; R.decisionResult = q.decisionResult?.slice(0, 600); R.provenance = q.provenance - R.mark = db(d => d.prepare("SELECT key,value FROM kv WHERE key LIKE ?").all(`${markKeys}/${form.sessionID}/${form.id}`)) - .map(row => ({ state: JSON.parse(row.value).state, via: JSON.parse(row.value).via })) - R.starts = (await c.passageStarts(R.passage.sessionID)).length - assert.equal(R.starts, 1) - if (mode === "ui") { - assert.deepEqual(R.mark, [{ state: "confirmed", via: "ui" }]) - assert.match(R.decisionResult ?? "", /"disposition"\s*:\s*"reported"/, "Wayfinder gate accepts the confirmed UI mark") - assert.equal(R.outcome, "completed") - } else { - assert.deepEqual(R.mark, [], "an ordinary answer leaves no UI mark") - assert.doesNotMatch(R.decisionResult ?? "", /"disposition"\s*:\s*"reported"/, "gate refuses without the mark") - // The model gets an actionable refusal, not the opaque Effect wrapper. - assert.match(R.decisionResult ?? "", /Human decision required: the user must answer this question from the CodeNomad interface/) - assert.doesNotMatch(R.decisionResult ?? "", /Effect\.tryPromise/) - assert.equal(R.outcome, "ended-without-report", "no human decision, no final report") - } - } - Q.result = "passed" - await c.control(scheduleID, "stop") - } - - if (c.journeys.includes("N")) { - c.setStage("N ordinary question Form through the dock") - const QUESTION = { question: "Pick a color?", header: "Color", options: [{ label: "Blue", description: "Calm" }] } - c.scenarios.push(turn => { - if (!turn.first.includes("[JOURNEY-N]")) return undefined - if (!turn.calls.includes("question")) return { calls: [{ name: "question", args: { questions: [QUESTION] } }] } - const answered = turn.messages.filter(m => m.role === "tool").map(m => typeof m.content === "string" ? m.content : JSON.stringify(m.content)).join("") - return { text: answered.includes("Blue") ? "N-ANSWER-RECEIVED Blue" : "N-ANSWER-MISSING" } - }) - const N = c.evidence.journeys.N = {} - const session = await c.client.session.create({ location, title: "Ordinary conversation with a question" }) - N.sessionID = session.id - N.missionMetadata = Boolean(session.metadata?.["codenomad.mission"]) - assert.equal(N.missionMetadata, false, "ordinary non-Mission session") - await c.client.session.prompt({ sessionID: session.id, text: "[JOURNEY-N] Ask me a question." }) - let forms = [] - await c.until(async () => (forms = (await c.client.form.list({ location })).data.filter(f => f.sessionID === session.id)).length === 1, 120_000) - const form = N.form = { id: forms[0].id, sessionID: forms[0].sessionID } - const marksBefore = db(d => d.prepare("SELECT count(*) AS count FROM kv WHERE key LIKE ?").get(markKeys).count) - // Exactly what the InterruptionDock sends: authenticated cookie plus the human-answer hint. - const reply = await c.bridge().inject({ method: "POST", url: `/workspaces/${c.workspace().id}/instance/api/session/${form.sessionID}/form/${form.id}/reply`, - headers: { cookie: "session=isolated-human", "content-type": "application/json", "x-codenomad-human-answer": "1" }, - payload: JSON.stringify({ answer: { q0: "Blue" } }) }) - N.reply = { status: reply.statusCode, body: reply.body.slice(0, 300) } - assert.equal(reply.statusCode, 204, `ordinary reply succeeds with native 204: ${reply.statusCode} ${reply.body}`) - await c.until(() => calls(session.id).some(call => call.name.startsWith("N-ANSWER")), 120_000) - await c.quiet(session.id) - N.modelSaw = calls(session.id).map(call => call.name) - assert.ok(N.modelSaw.includes("N-ANSWER-RECEIVED Blue"), "the native question received the dock answer") - N.pendingForms = (await c.client.form.list({ location })).data.filter(f => f.sessionID === session.id).length - assert.equal(N.pendingForms, 0) - N.marks = db(d => d.prepare("SELECT key FROM kv WHERE key LIKE ?").all(markKeys)).map(row => row.key) - assert.equal(N.marks.length, marksBefore, "no UI mark is written for a non-Mission Form") - assert.equal(N.marks.some(key => key.includes(session.id)), false) - N.result = "passed" - } -} diff --git a/scripts/test-automation-native.mjs b/scripts/test-automation-native.mjs index 2e30dfe3fd..ebd183e962 100644 --- a/scripts/test-automation-native.mjs +++ b/scripts/test-automation-native.mjs @@ -45,9 +45,8 @@ process.env.XDG_DATA_HOME = path.join(root, "next-start-data") const configFile = path.join(env.OPENCODE_CONFIG_DIR, "opencode.json") await writeFile(configFile, "{}\n") -let client, developer = false, callBrowser = false, providerError +let client, developer = false, providerError let observedTools = [] -const nativeCalls = [] const bridge = Fastify() let registration = createAutomationBridgeRegistration("http://127.0.0.1") registerAutomationPluginRoute(bridge, { @@ -56,19 +55,15 @@ registerAutomationPluginRoute(bridge, { workspaceManager: { getSharedServiceClient: async () => client, list: () => [{ id: "unrelated" }, { id: "fixture" }], - ownsLocation: async (id, location) => { - if (id === "unrelated") throw new Error("Synthetic unavailable unrelated native inventory") - return path.resolve(location.directory).toLowerCase() === project.toLowerCase() - }, + ownsLocation: async (id, location) => id !== "unrelated" && path.resolve(location.directory).toLowerCase() === project.toLowerCase(), }, nativeParent: { available: true, - request: async (method, params) => { + request: async method => { if (method === "developer.status") return { status: developer ? { state: "ready", cdpUrl: "http://127.0.0.1:1", runId: "fixture", nativeIdentity: "fixture", windowId: "fixture" } : { state: "stopped" } } - nativeCalls.push({ method, params }) - return method === "browser.probe" ? { available: true } : { text: "NATIVE_BROWSER_FIXTURE" } + throw new Error(`Unexpected native request ${method}`) }, }, }) @@ -79,11 +74,6 @@ const provider = createServer(async (request, response) => { const body = JSON.parse(raw) const primary = request.headers["x-automation-kind"] === "primary" if (primary) observedTools = (body.tools ?? []).map(tool => tool.function?.name).filter(Boolean) - const invoke = primary && callBrowser - if (invoke) { - assert(observedTools.includes("codenomad_browser"), "Native model catalog must contain the browser tool") - callBrowser = false - } if (!body.stream) { response.setHeader("content-type", "application/json") response.end(JSON.stringify({ id: "fixture", choices: [{ message: { role: "assistant", content: "Fixture" }, finish_reason: "stop" }] })) @@ -94,11 +84,8 @@ const provider = createServer(async (request, response) => { id: "fixture", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta, finish_reason }], })}\n\n`) chunk({ role: "assistant" }) - if (invoke) chunk({ tool_calls: [{ index: 0, id: `fixture-${Date.now()}`, type: "function", function: { - name: "codenomad_browser", arguments: JSON.stringify({ action: "open", url: "https://example.com" }), - } }] }) - else chunk({ content: "Done" }) - chunk({}, invoke ? "tool_calls" : "stop") + chunk({ content: "Done" }) + chunk({}, "stop") response.end("data: [DONE]\n\n") } catch (error) { providerError = error; response.destroy(error) } }) @@ -179,9 +166,9 @@ try { } await until(async () => (await client.plugin.list({ location })).data.some(plugin => plugin.id === "codenomad.automation" && plugin.state.status === "active")) await until(async () => (await client.plugin.list({ location })).data.some(plugin => plugin.id === "codenomad-session-pruning" && plugin.state.status === "active")) - await until(async () => (await sample()).includes("codenomad_browser")) - const allTools = ["codenomad_act", "codenomad_browser", "codenomad_inspect", "codenomad_screenshot"] - assert.deepEqual(await sample(), allTools, "Backend presence exposes all tools independently of Developer Mode") + await until(async () => (await sample()).includes("codenomad_inspect")) + const allTools = ["codenomad_act", "codenomad_inspect", "codenomad_screenshot"] + assert.deepEqual(await sample(), allTools, "Backend presence exposes developer automation tools independently of Developer Mode") // Keep project discovery disabled to exclude real ancestor configuration. // That also disables OpenCode's config watcher, so explicitly observe the // same directory with an OS watcher rather than accept a false-positive test. @@ -196,13 +183,6 @@ try { configWatcher.close() } assert.equal(await readFile(setupLog, "utf8"), setupBeforeHeartbeat, "Backend heartbeats must not reload native configuration/plugins") - const skills = await client.skill.list({ location }) - assert(JSON.stringify(skills).includes("codenomad-browser"), "Bundled skill is visible in an arbitrary project") - callBrowser = true - await sample() - assert.equal(nativeCalls.length, 1) - assert.equal(nativeCalls[0].method, "browser.execute") - assert.equal(nativeCalls[0].params.sessionID, session.id) const denied = await bridge.inject({ method: "POST", url: "/api/opencode-plugin/automation", headers: { "x-codenomad-automation-token": registration.token }, payload: { mode: "developer-execute", sessionID: session.id, command: { action: "inspect" } }, @@ -214,11 +194,10 @@ try { assert.deepEqual(await sample(), allTools) await second(); second = undefined await until(async () => (await sample()).length === 0) - assert(!JSON.stringify(await client.skill.list({ location })).includes("codenomad-browser")) first = await openPresence() - await until(async () => (await sample()).length === 4) + await until(async () => (await sample()).length === 3) assert.deepEqual(await sample(), allTools) - console.log(`PASS ${version}: connected-daemon discovery despite backend environment mismatch, automation and pruning provisioning, stable native plugins across heartbeats, late native discovery, arbitrary project, all definitions without Developer Mode, browser execution, native target fences, independent leases, clean shutdown and reopening`) + console.log(`PASS ${version}: connected-daemon discovery despite backend environment mismatch, automation and pruning provisioning, stable native plugins across heartbeats, late native discovery, arbitrary project, developer definitions without Developer Mode, native target fences, independent leases, clean shutdown and reopening`) } finally { await first?.(); await second?.(); await removeBridge?.() child?.kill() diff --git a/scripts/test-blank-session-cleanup-native.mjs b/scripts/test-blank-session-cleanup-native.mjs index 0725e0c5ee..790936bd6d 100644 --- a/scripts/test-blank-session-cleanup-native.mjs +++ b/scripts/test-blank-session-cleanup-native.mjs @@ -7,9 +7,14 @@ import os from "node:os" import path from "node:path" import { setTimeout as delay } from "node:timers/promises" import { OpenCode } from "@opencode/client" +import Fastify from "fastify" import toast from "solid-toast" import { stopFixtureChild } from "./native-fixture-guards.mjs" +import { registerSessionCleanupRoute } from "../packages/server/src/server/routes/session-cleanup.ts" +import { SessionCleanupFence } from "../packages/server/src/server/session-cleanup-fence.ts" +import { WorktreeDeletionFence } from "../packages/server/src/workspaces/worktree-session-evacuation.ts" import { createClientSession } from "../packages/ui/src/types/session.ts" +import { serverApi } from "../packages/ui/src/lib/api-client.ts" import { sdkManager } from "../packages/ui/src/lib/sdk-manager.ts" import { addInstance, removeInstance } from "../packages/ui/src/stores/instances.ts" import { createSession } from "../packages/ui/src/stores/session-api.ts" @@ -63,6 +68,8 @@ child.stdout.on("data", data => { output += data }) child.stderr.on("data", data => { output += data }) const instanceId = "blank-native" const originalToast = toast.custom +const originalCleanup = serverApi.cleanupSession +const app = Fastify() toast.custom = () => "fixture-toast" try { const deadline = Date.now() + 30_000 @@ -84,6 +91,28 @@ try { assert(before.data.some(message => message.type === "user")) assert(before.data.some(message => message.type === "assistant")) + const directory = blank.location.directory + const workspace = { path: directory } + const connection = { client, assertCurrent() {} } + registerSessionCleanupRoute(app, { + workspaceManager: { + get: id => id === instanceId ? workspace : undefined, + getExistingSharedServiceConnection: id => id === instanceId ? connection : undefined, + ownsLocation: async (id, location) => id === instanceId && location.directory === directory, + getWorktreeIdentityForPath: async (id, value) => id === instanceId && value === directory ? directory : undefined, + }, + worktreeDeletionFence: new WorktreeDeletionFence(), + cleanup: new SessionCleanupFence(), + isProtected: () => false, + }) + const endpoint = await app.listen({ host: "127.0.0.1", port: 0 }) + const cleanupAttempts = [] + serverApi.cleanupSession = async (id, sessionId, signal) => { + cleanupAttempts.push(sessionId) + const response = await fetch(`${endpoint}/api/workspaces/${id}/session-cleanup/${sessionId}`, { method: "POST", signal }) + assert.equal(response.status, 200) + return response.json() + } sdkManager.clients.set(`${instanceId}:/workspaces/${instanceId}/instance`, client) addInstance({ id: instanceId, folder: root, port: 0, pid: 0, proxyPath: "", status: "ready", client }) // Reproduce the UI's unchanged creation snapshot, without loading its transcript. @@ -91,6 +120,7 @@ try { setSessions(new Map([[instanceId, new Map([used, blank].map(info => [info.id, createClientSession(info, instanceId)]))]])) const created = await createSession(instanceId) await cleanupBlankSessions(instanceId, created.id) + assert.deepEqual(cleanupAttempts, [blank.id], "Only the blank session reaches the backend cleanup route") const remaining = await client.session.list({ directory: root, limit: 100 }) assert(remaining.data.some(info => info.id === used.id), "Used session must remain in native storage") assert.ok(sessions().get(instanceId)?.has(used.id), "Used session must stay in the UI") @@ -103,8 +133,10 @@ try { process.exitCode = 1 } finally { toast.custom = originalToast + serverApi.cleanupSession = originalCleanup removeInstance(instanceId, { authoritative: false }) sdkManager.destroyClientsForInstance(instanceId) + await app.close() try { await stopFixtureChild(child, stopped) } catch (error) { console.error(error) process.exitCode = 1 diff --git a/scripts/test-design-activation-native.mjs b/scripts/test-design-activation-native.mjs index e84bd75490..ac22a16184 100644 --- a/scripts/test-design-activation-native.mjs +++ b/scripts/test-design-activation-native.mjs @@ -168,7 +168,11 @@ try { const located = route => async directory => (await api("GET", `${route}?location[directory]=${encodeURIComponent(directory)}`)).json?.data ?? [] const agents = located("/api/agent"), skills = located("/api/skill"), plugins = located("/api/plugin") // Discovery sees only the fixture's loopback providers, whatever the caller's environment holds. - results.models = (await located("/api/model")(project("p1"))).map(model => `${model.providerID}/${model.id}`) + const models = located("/api/model") + results.models = await until("fixture chat catalog", async () => { + const names = (await models(project("p1"))).map(model => `${model.providerID}/${model.id}`) + return names.includes("fixture/vision") && names + }) assert(results.models.every(ref => /^(fixture|fiximg)\//.test(ref)), `only fixture models are discovered: ${results.models}`) const designSkills = async directory => (await skills(directory)).filter(skill => skill.id.startsWith("design-")) const hasDesign = async directory => (await agents(directory)).some(agent => agent.id === "design") @@ -234,8 +238,8 @@ try { await api("POST", `/api/session/${sessionID}/permission/${request.id}/reply`, { decision: "reject" }) } } - // A rejected call ends the turn with the native declined error. - await turn(sessionID, prompt, "declined this tool call", reject) + // A rejected call ends with either the direct declined text or Code Mode's Permission.DeclinedError. + await turn(sessionID, prompt, "declined this tool call|Permission\\.DeclinedError", reject) await delay(2_000) await reject() return asked.length @@ -304,10 +308,17 @@ try { "design-core loads by identifier") // AC-4: the user's ask rule on the image tool applies to Design exactly as to Build. - for (const entry of [...designRequests, ...buildRequests]) - assert(entry.tools.includes("experimental_image_generate"), `The image tool is offered by default: ${entry.tools}`) - const generate = JSON.stringify([{ tool: "experimental_image_generate", - args: { prompt: "Flat blue app icon", path: ".codenomad/design/icon/app-icon-minimal-a.png" } }]) + const directImageTool = designRequests[0].tools.find(name => name === "generate_image" || name === "experimental_image_generate") + const imageTool = directImageTool ?? (designRequests[0].tools.includes("execute") && designRequests[0].all.includes("generate_image") ? "generate_image" : undefined) + assert(imageTool, "Design offers the native image tool by default") + for (const entry of [...designRequests, ...buildRequests]) { + if (directImageTool) assert(entry.tools.includes(directImageTool), `The image tool is offered by default: ${entry.tools}`) + else assert(entry.tools.includes("execute") && entry.all.includes("generate_image"), `The Code Mode image tool is offered by default: ${entry.tools}`) + } + const imageArgs = { prompt: "Flat blue app icon", path: ".codenomad/design/icon/app-icon-minimal-a.png" } + const generate = JSON.stringify(directImageTool + ? [{ tool: directImageTool, args: imageArgs }] + : [{ tool: "execute", args: { code: `return await tools.generate_image(${JSON.stringify(imageArgs)})` } }]) const askedFor = async () => ({ design: await permissionRequests(await imagesSession(project("p2-ask")), `RUN ${generate}`), build: await permissionRequests(await session(project("p2-ask")), `RUN ${generate}`), diff --git a/scripts/test-design-companion-native.mjs b/scripts/test-design-companion-native.mjs index b329b3369e..4d6e0b19fa 100644 --- a/scripts/test-design-companion-native.mjs +++ b/scripts/test-design-companion-native.mjs @@ -82,6 +82,7 @@ const sha = bytes => createHash("sha256").update(bytes).digest("hex") // Markdown image of it. const PAD = 34 const state = { readBack: true, imageCalls: [], chat: 0, providerError: undefined } +let imageTool const text = content => typeof content === "string" ? content : Array.isArray(content) ? content.map(part => part.text ?? "").join("\n") : "" const carriesImage = message => message.role === "user" && Array.isArray(message.content) && message.content.some(part => part.type === "image_url") const sse = (res, delta, finish) => { @@ -107,7 +108,27 @@ function respond(res, body) { const instruction = text(messages[trigger]?.content) const calls = messages.flatMap(message => message.tool_calls ?? []).map(entry => ({ name: entry.function?.name, args: JSON.parse(entry.function?.arguments || "{}") })) const run = /RUN (\[.*\])/s.exec(instruction) - if (run) return steps ? say(res, "Started.") : call(res, JSON.parse(run[1])) + if (run) { + if (steps) return say(res, "Started.") + const planned = JSON.parse(run[1]) + const imageSpecs = planned.filter(entry => entry.tool === "generate_image") + const otherCalls = planned.filter(entry => entry.tool !== "generate_image") + if (!imageSpecs.length) return call(res, otherCalls) + const offered = body.tools.map(tool => tool.function?.name) + const direct = offered.find(name => name === "generate_image" || name === "experimental_image_generate") + if (direct) { + imageTool = direct + return call(res, planned.map(entry => entry.tool === "generate_image" ? { ...entry, tool: direct } : entry)) + } + assert(offered.includes("execute"), "Design offers execute for Code Mode image generation") + const instructions = messages.filter(m => m.role === "system" || m.role === "developer").map(m => text(m.content)).join("\n") + assert(instructions.includes("generate_image"), "Design Code Mode catalog lists generate_image") + imageTool = "generate_image" + const code = imageSpecs.length === 1 + ? `return await tools.generate_image(${JSON.stringify(imageSpecs[0].args)})` + : `return await Promise.all([${imageSpecs.map(entry => `tools.generate_image(${JSON.stringify(entry.args)})`).join(", ")}])` + return call(res, [...otherCalls, { tool: "execute", args: { code } }]) + } // Reads name the absolute file, as the notice does; answers cite it as relative Markdown. const markdown = file => `![${path.posix.basename(relative(file))}](${relative(file)})` const show = /Read the generated image `([^`]+)`/.exec(instruction) @@ -122,7 +143,7 @@ function respond(res, body) { const saved = [...messages.filter(message => message.role === "user").map(message => text(message.content)).join("\n").matchAll(/Saved image: (.+?) \(/g)].map(match => match[1]) const read = new Set(calls.filter(entry => entry.name === "read").map(entry => path.resolve(project, Object.values(entry.args)[0] ?? ""))) const unread = [...new Set(saved)].filter(file => !read.has(path.resolve(project, file))) - const generations = calls.filter(entry => entry.name === "experimental_image_generate").length + const generations = calls.filter(entry => entry.name === imageTool).length if (!state.readBack || saved.length < generations || !unread.length) return say(res, "Noted.") return call(res, unread.map(file => ({ tool: "read", args: { [pathKey("read")]: file } }))) } @@ -189,6 +210,7 @@ try { // Discovery sees only the fixture's loopback providers, whatever the caller's environment holds. const models = async types => (await (await fetch(`${url}/api/model?${types ? `types=${types}&` : ""}location[directory]=${encodeURIComponent(project)}`, { headers: { authorization }, signal: AbortSignal.timeout(30_000) })).json()).data.map(model => `${model.providerID}/${model.id}`) + await until("fixture image catalog", async () => (await models("image")).includes("fiximg/image")) results.models = await models() assert(results.models.every(ref => /^(fixture|fiximg)\//.test(ref)), `only fixture models are discovered: ${results.models}`) assert.deepEqual(await models("image"), ["fiximg/image"]) @@ -206,13 +228,13 @@ try { assert(data.length < 200, "the whole fixture conversation fits one native page") return data } - const notices = list => list.filter(message => message.type === "synthetic" && message.metadata?.source === "experimental_image_generate") + const notices = list => list.filter(message => message.type === "synthetic" && message.metadata?.source === imageTool) const readParts = list => list.flatMap(message => message.type === "assistant" ? message.content.filter(part => part.type === "tool" && part.name === "read" && part.state?.status === "completed").map(part => ({ message: message.id, part })) : []) const idle = async () => { await client.session.wait({ sessionID }, { signal: AbortSignal.timeout(60_000) }); await delay(300) } - async function turn(prompt, settled, label) { + async function turn(prompt, settled, label, timeout) { await client.session.prompt({ sessionID, text: prompt }) - await until(label, async () => settled(await messages())) + await until(label, async () => settled(await messages()), timeout) await idle() } // Every page, as the panel reads them; each answer is checked against the published contract. @@ -235,7 +257,7 @@ try { } const design = path.join(project, ".codenomad", "design", "icon") const file = name => path.join(design, name) - const gen = (prompt, name, extra = {}) => ({ tool: "experimental_image_generate", args: { prompt, path: `.codenomad/design/icon/${name}`, ...extra } }) + const gen = (prompt, name, extra = {}) => ({ tool: "generate_image", args: { prompt, path: `.codenomad/design/icon/${name}`, ...extra } }) // AC-16, series 1: two generations, both read back in one answer once both are saved. await turn(`RUN ${JSON.stringify([gen("Flat blue app icon", "icon-minimal-a.png"), gen("Bold orange app icon", "icon-bold-a.png")])}`, @@ -298,13 +320,14 @@ try { assert.equal(entries.filter(entry => entry.kind === "image").length, 3) const reference = await rpc("imageReference", { sessionID, target: unread.target }) assert.deepEqual(reference, { status: "path", path: ".codenomad/design/icon/icon-mono-a.png" }) - const generatedAt = (await messages()).findLastIndex(message => message.type === "assistant" && message.content.some(part => part.type === "tool" && part.name === "experimental_image_generate")) + const generatedAt = (await messages()).findLastIndex(message => message.type === "assistant" && message.content.some(part => + part.type === "tool" && (part.name === imageTool || (part.name === "execute" && part.state?.metadata?.toolCalls?.some(c => c.tool === imageTool))))) if (companionUI) await companionUI.testDesignCompanionUI({ cli, client, url, password, root, location, sessionID, designZip, until, idle }) else { // The Design extension's English request, as `composer.prefill` substitutes its reference. await turn(`Read the generated image \`${reference.path}\` and show it here with your critique.`, - list => readParts(list).length >= 4 && answered(list, "Here it is"), "late read-back") + list => readParts(list).length >= 4 && answered(list, "Here it is"), "late read-back", 120_000) } const after = await messages() diff --git a/scripts/test-mission-calendar-run-e2e.mjs b/scripts/test-mission-calendar-run-e2e.mjs new file mode 100644 index 0000000000..33de27291e --- /dev/null +++ b/scripts/test-mission-calendar-run-e2e.mjs @@ -0,0 +1,316 @@ +// End-to-end isolated OpenCode test of a Mission calendar with the REAL bundled +// `codenomad.missions` plugin and no CodeNomad at all (no presence lease, no bridge): +// 1. Without CodeNomad and without work, Missions stays unregistered. +// 2. A native Automation whose whole program is the calendar tool launches an ordinary +// one-time Mission: created, started, coordinator `/goal` armed. +// 3. While that Mission is active, later runs launch nothing. +// 4. The coordinator delegates an independent task: the plugin creates the root, +// prompts it and delivers its report by its own session API; the Mission completes. +// 5. The next run launches again: the new Mission replaces the first one, in the same +// conversation. OpenCode restarts in the middle of it and Missions registers again +// by itself, so the coordinator can finish. +// 6. A calendar waiting for commits on a local branch launches nothing until one lands, +// then coordinates in the conversation it names. +// 7. A programming saved with a prepared Mission launches by starting that Mission. +// 8. A schedule the recurring engine left in the plugin's storage is read without that engine +// and left deleted the way the engine deletes one. +// 9. A conversation chosen to coordinate, on another agent, model and thinking than the coordinator's, +// is put on the coordinator's and coordinates the launch. +// Usage: node --import tsx scripts/test-mission-calendar-run-e2e.mjs +import assert from "node:assert/strict" +import { execFileSync, spawn } from "node:child_process" +import { randomUUID } from "node:crypto" +import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises" +import { createServer } from "node:http" +import path from "node:path" +import { DatabaseSync } from "node:sqlite" +import { pathToFileURL } from "node:url" +import { setTimeout as delay } from "node:timers/promises" +import { OpenCode } from "@opencode/client" +import { Service } from "@opencode/client/service" +import { CODENOMAD_MISSIONS_RPC } from "../packages/server/src/missions/rpc.ts" +import { MISSION_CALENDAR_CODE } from "../packages/server/src/missions/calendar-run.ts" +import { missionCalendars } from "../packages/server/src/opencode/mission-calendars.ts" +import { fixtureEnvironment, fixtureParent } from "./native-product-fixture.mjs" +import { stopFixtureChild } from "./native-fixture-guards.mjs" + +const cli = process.argv[2] +assert(cli && path.isAbsolute(cli), "Pass absolute OpenCode CLI path") + +const bundlePath = path.resolve("packages/server/dist/plugins/missions/plugin.mjs") +const root = await mkdtemp(path.join(await fixtureParent(), "mission-calendar-run-e2e-")) +// CodeNomad never runs here: the presence directory stays empty. +const presenceDir = path.join(root, "presence") +await mkdir(presenceDir, { recursive: true }) +const git = (...args) => execFileSync("git", ["-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", ...args], { cwd: root, stdio: "pipe" }) +git("init", "-q", "-b", "main"); git("commit", "-q", "--allow-empty", "-m", "first") + +const password = randomUUID() +const env = await fixtureEnvironment(root, { + OPENCODE_CONFIG_DIR: path.join(root, "config"), + OPENCODE_DB: path.join(root, "fixture.db"), + OPENCODE_CONFIG_PROJECT_DISABLE: "1", + OPENCODE_DISABLE_MODELS_FETCH: "1", + OPENCODE_DISABLE_FFF: "1", + OPENCODE_SERVER_PASSWORD: password, +}) +const pluginDir = path.join(env.OPENCODE_CONFIG_DIR, "plugins", "codenomad-missions") +await mkdir(pluginDir, { recursive: true }) +await writeFile(path.join(pluginDir, "package.json"), JSON.stringify({ + name: "codenomad-missions-e2e-shim", type: "module", exports: { ".": "./index.mjs" }, opencode: { server: "./index.mjs" }, +}), "utf8") +await writeFile(path.join(pluginDir, "index.mjs"), ` +import { desktopPlugin } from ${JSON.stringify(pathToFileURL(bundlePath).href)} +export default desktopPlugin(${JSON.stringify(presenceDir)}) +`, "utf8") + +// A scripted model. A tool result ends the turn. The coordinator delegates one independent +// task and reports once that task's report reaches it, or (held) reports after `holdMs`; +// the task's root reports after `rootHoldMs`. +const OBJECTIVE = "CALENDAR-OBJECTIVE review what changed", BRIEF = "ROOT-TASK inspect the change", DONE = "ROOT-DONE" +// `service` counts OpenCode starts: a turn held across a restart answers a service that is gone. +const script = { mode: "delegate", holdMs: 0, rootHoldMs: 25_000, service: 1 } +const seen = { delegated: new Set(), rootReports: 0, finals: 0, coordinatorTurns: 0, heldTurns: 0, rootTurns: 0 } +const provider = createServer(async (req, res) => { + try { + let raw = "" + for await (const chunk of req) raw += chunk + const body = JSON.parse(raw), tools = (Array.isArray(body.tools) ? body.tools : []).map(tool => tool?.function?.name) + const text = JSON.stringify(body.messages ?? body.input ?? "") + res.setHeader("Content-Type", "text/event-stream") + const chunk = (delta, finish_reason) => res.write(`data: ${JSON.stringify({ id: "r", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta, finish_reason }] })}\n\n`) + const say = content => { chunk({ role: "assistant", content }, null); chunk({}, "stop"); res.end("data: [DONE]\n\n") } + const call = (name, input) => { + chunk({ role: "assistant", tool_calls: [{ index: 0, id: "call_" + randomUUID().slice(0, 8), type: "function", function: { name, arguments: JSON.stringify(input) } }] }, null) + chunk({}, "tool_calls"); res.end("data: [DONE]\n\n") + } + if (!tools.length) return say("Fixture title") + if (body.messages?.at(-1)?.role === "tool") return say("Noted.") + const report = tools.find(name => /mission[_.]report$/.test(name ?? "")), delegate = tools.find(name => /mission[_.]delegate$/.test(name ?? "")) + // Every launch shares one conversation: the latest start names the current Mission. + const mission = [...text.matchAll(/Start or resume existing mission (msn_[A-Za-z0-9]+)/g)].at(-1)?.[1] ?? "unknown" + if (text.includes("Start or resume existing mission")) { + seen.coordinatorTurns++ + if (!report || !delegate) return say("Mission tools missing.") + if (script.mode === "held") { + seen.heldTurns++ + const service = script.service + await delay(script.holdMs) + if (service === script.service) seen.finals++ + return call(report, { outcome: "completed", summary: "Held Mission finished.", final: true }) + } + if (text.includes(DONE)) { + // The next launch arrives in this same conversation as soon as this one completes: script it now. + seen.finals++; script.mode = "held"; script.holdMs = 25_000 + return call(report, { outcome: "completed", summary: "Delegated work returned.", final: true }) + } + if (!seen.delegated.has(mission)) { + seen.delegated.add(mission) + return call(delegate, { taskKey: "probe", title: "Probe", brief: BRIEF, role: "specialist", delivery: "queue", + executionMode: { kind: "independent", reason: "lifetime", explanation: "The probe outlives this turn." } }) + } + await delay(2_000) + return say("Waiting for the probe.") + } + if (text.includes("ROOT-TASK")) { + seen.rootTurns++ + if (!report) return say("Mission tools missing.") + await delay(script.rootHoldMs) + seen.rootReports++ + return call(report, { outcome: "completed", summary: DONE }) + } + return say("Nothing to do.") + } catch (error) { res.destroy(error) } +}) +await new Promise(resolve => provider.listen(0, "127.0.0.1", resolve)) + +env.OPENCODE_CONFIG_CONTENT = JSON.stringify({ + automations: true, plugins: [pluginDir], model: "fixture/fixture", + providers: { fixture: { package: "@opencode/ai/providers/openai-compatible", + settings: { baseURL: `http://127.0.0.1:${provider.address().port}/v1`, apiKey: "fixture-only" }, models: { fixture: {}, other: { variants: [{ id: "high" }] } } } }, +}) + +const location = { directory: root }, callOpts = { location, headers: { "x-opencode-directory": root } } +async function startDaemon(label) { + let output = "", spawnError + const child = spawn(cli, ["serve", "--service", "--hostname", "127.0.0.1", "--port", "0", "--print-logs"], { cwd: root, env, windowsHide: true }) + const stopped = new Promise(resolve => child.once("close", resolve)) + child.on("error", error => { spawnError = error }) + child.stdout.on("data", data => { output += data }) + child.stderr.on("data", data => { output += data }) + const deadline = Date.now() + 30_000 + while (!/http:\/\/127\.0\.0\.1:\d+/.test(output)) { + if (spawnError) throw spawnError + if (child.exitCode !== null || Date.now() > deadline) throw new Error(`${label} failed:\n${output.slice(-2000)}`) + await delay(25) + } + const file = path.join(env.XDG_STATE_HOME, "opencode/service.json") + let endpoint + while (!endpoint && Date.now() < deadline) { + try { if (JSON.parse(await readFile(file, "utf8")).pid === child.pid) endpoint = await Service.discover({ file }) } catch {} + if (!endpoint) await delay(25) + } + assert(endpoint, `${label} did not register isolated service.json`) + const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }) + return { client, + snapshot: () => client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, callOpts), + goal: async sessionID => (await client.rpc.call({ rpcID: "opencode.goal", method: "get", input: { sessionID }, location }, { headers: callOpts.headers })).output, + stop: async () => { await stopFixtureChild(child, stopped); await writeFile(path.join(root, `daemon-${label}.log`), output) } } +} +const until = async (label, read, done, ms = 60_000) => { + const end = Date.now() + ms + let last + while (Date.now() < end) { + try { last = await read(); if (done(last)) return last } catch (error) { last = { error: String(error?.message ?? error) } } + await delay(250) + } + throw new Error(`${label} timed out: ${JSON.stringify(last)?.slice(0, 1500)}`) +} +const missions = async daemon => (await daemon.snapshot()).missions + +let daemon +try { + daemon = await startDaemon("1") + await delay(3_000) + await assert.rejects(daemon.snapshot(), "Missions is unregistered without CodeNomad and without work") + console.log("PASS 1 (no CodeNomad, no work: Missions unregistered)") + + // The server's own adapter creates the carrier conversation and the Automations. + const projectID = (await daemon.client.location.get({ location })).project.id + const calendars = () => missionCalendars(daemon.client, location, projectID) + // A project that never had a programmed Mission has no carrier conversation yet: its list is empty, not an error. + assert.deepEqual(await calendars().list(), []) + const rule = (calendar, args) => ({ name: args.title, trigger: { type: "every", every: "15 seconds" }, action: { type: "code", code: MISSION_CALENDAR_CODE, args: { calendar, ...args } } }) + await calendars().save("cal_e2e", [rule("cal_e2e", { objective: OBJECTIVE, title: "Calendar E2E", template: "custom", coordinatorGoal: true })]) + const automation = { id: (await calendars().list())[0].rules[0].automationID } + const row = () => daemon.client.experimental.automation.get({ automationID: automation.id }) + + const first = (await until("first Mission", () => missions(daemon), list => list.length === 1, 60_000).catch(async error => { + throw new Error(`${error.message}\nautomation: ${JSON.stringify(await row().catch(() => null))?.slice(0, 1500)}`) + }))[0] + assert.equal(first.title, "Calendar E2E") + assert.equal(first.status, "active") + await until("coordinator /goal", () => daemon.goal(first.coordinatorSessionId), goal => goal?.status === "active", 20_000) + console.log("PASS 2 (the Automation launched and started a one-time Mission, /goal armed)") + + const launchedAt = (await row()).runCount + const later = await until("a later run", row, info => info.runCount >= launchedAt + 1, 45_000) + assert.notEqual(later.lastOutcome, "failed", later.lastOutput) + const listed = (await calendars().list())[0] + assert.deepEqual([listed.id, listed.title, listed.paused, listed.last?.outcome, listed.last?.missionID, listed.last?.coordinatorSessionID], + ["cal_e2e", "Calendar E2E", false, "waiting", first.id, first.coordinatorSessionId], "the list tells what the programmed Mission last did") + assert.deepEqual((await missions(daemon)).map(mission => [mission.id, mission.status]), [[first.id, "active"]], "a run launches nothing while the previous Mission is active") + console.log("PASS 3 (later runs wait for the active Mission)") + + // Read while the launch is active: the next one removes its Mission. + const working = (await until("independent task", () => missions(daemon), list => list.find(mission => mission.id === first.id)?.actors.some(actor => actor.kind !== "coordinator"), 60_000)) + .find(mission => mission.id === first.id) + assert.equal(working.tasks[0]?.key, "probe") + const actor = working.actors.find(actor => actor.kind !== "coordinator") + assert.ok(actor?.managed, "the independent root is a managed actor") + assert.equal((await daemon.client.session.get({ sessionID: actor.sessionId })).parentID, undefined) + // The plugin admits the report at once; under `/goal` OpenCode took 20 to 60 seconds to hand it to the coordinator. + await until("the final report", async () => seen.finals, count => count >= 1, 180_000) + assert.ok(seen.rootReports >= 1) + console.log("PASS 4 (independent task: root created, prompted and reported without CodeNomad)") + + const replaced = await until("the next launch", () => missions(daemon), list => list.some(mission => mission.id !== first.id), 90_000) + const second = replaced.find(mission => mission.id !== first.id) + assert.deepEqual([replaced.length, second.coordinatorSessionId], [1, first.coordinatorSessionId], "the new launch replaces the first Mission, in the same conversation") + // The run publishes its result once its program returns, after the Mission it launched is already there. + const published = await until("the launch's result", () => calendars().list(), list => list[0]?.last?.missionID === second.id, 30_000) + assert.deepEqual(published[0].last.history.map(item => item.outcome), ["completed"]) + await until("held coordinator turn", async () => seen.heldTurns, count => count > 0, 120_000) + await calendars().pause("cal_e2e") + await daemon.stop() + { + // What the recurring engine stored for a schedule, beside this project's other Missions keys. + const db = new DatabaseSync(env.OPENCODE_DB) + try { + const slot = db.prepare("SELECT key FROM kv WHERE key LIKE '%codenomad-missions/calendar-v1/%/cal_e2e'").get().key + const [, namespace, token] = /^(.*)codenomad-missions\/calendar-v1\/([a-f0-9]{24})\/cal_e2e$/.exec(slot) + const created = JSON.parse(db.prepare("SELECT value FROM kv WHERE value LIKE '%\"type\":\"mission.created\"%' LIMIT 1").get().value) + db.prepare("INSERT INTO kv (key, value, time_created, time_updated) VALUES (?, ?, ?, ?)").run( + `${namespace}codenomad-missions/documents-v1/project/${token}/missions/msn_legacy_e2e`, + JSON.stringify({ id: "msn_legacy_e2e", projectID: created.projectID, projectCanonical: created.projectCanonical, revision: 3, timeGeneration: 1, + state: "stopped", configuration: { title: "Legacy E2E" }, calendars: [{ scheduleID: "aut_legacy", sessionID: "ses_cn_schedule_legacy" }] }), Date.now(), Date.now()) + } finally { db.close() } + } + script.holdMs = 0; script.service++ + daemon = await startDaemon("2") + const restored = await until("Missions after restart", () => missions(daemon), list => list.some(mission => mission.id === second.id), 30_000) + assert.equal(restored.find(mission => mission.id === second.id).status, "active") + // Once it completes nothing is left to do, and Missions unregisters within two seconds: either reading proves the end. + const finals = seen.finals + await until("second Mission ends after restart", () => missions(daemon).then(list => list.find(mission => mission.id === second.id)?.status, () => "unregistered"), + status => status === "completed" || status === "unregistered", 120_000) + assert.ok(seen.finals > finals, "the coordinator sent its final report after the restart") + console.log("PASS 5 (after an OpenCode restart Missions registers again and the Mission finishes)") + assert.equal((await calendars().list())[0].paused, true) + await calendars().delete("cal_e2e") + + // Held long enough to be read: once its Mission completes, Missions unregisters again. + script.holdMs = 10_000 + await calendars().save("cal_commits", [rule("cal_commits", { objective: OBJECTIVE, title: "Commits E2E", template: "custom", coordinatorSessionID: first.coordinatorSessionId, + when: [{ kind: "branch-commits", directory: root, ref: "refs/heads/main" }] })]) + const watching = { id: (await calendars().list())[0].rules[0].automationID } + const watch = () => daemon.client.experimental.automation.get({ automationID: watching.id }) + // Beside an Automation that existed at startup, OpenCode can take a minute to run a new one for the first time. + const quiet = await until("two runs without a commit", watch, info => info.runCount >= 2 || info.lastOutcome === "failed", 150_000) + assert.notEqual(quiet.lastOutcome, "failed", quiet.lastOutput) + assert.equal((await missions(daemon).catch(() => [])).filter(mission => mission.title === "Commits E2E").length, 0, "no commit, no Mission") + git("commit", "-q", "--allow-empty", "-m", "second") + const reused = (await until("the commit's Mission", () => missions(daemon), list => list.some(mission => mission.title === "Commits E2E"), 60_000).catch(async error => { + throw new Error(`${error.message}\nautomation: ${JSON.stringify(await watch().catch(() => null))?.slice(0, 1500)}`) + })).find(mission => mission.title === "Commits E2E") + assert.equal(reused.coordinatorSessionId, first.coordinatorSessionId, "the calendar's Missions share the conversation it names") + console.log("PASS 6 (a calendar waiting for commits launches only once one lands, in the conversation it names)") + await calendars().delete("cal_commits") + assert.deepEqual(await calendars().list(), []) + + // A person programs a Mission with CodeNomad open: its backend lease registers Missions, and the Mission is prepared at once. + const lease = path.join(presenceDir, `${randomUUID()}.lease`) + await writeFile(lease, "") + const prepared = (await until("the prepared Mission", () => daemon.client.rpc(CODENOMAD_MISSIONS_RPC).create({ requestID: "req_prepared_e2e", objective: OBJECTIVE, + title: "Prepared E2E", template: "custom", prepared: true }, callOpts), created => !!created?.mission?.id, 30_000)).mission + const native = daemon.client.rpc(CODENOMAD_MISSIONS_RPC) + assert.deepEqual((await native.legacySchedules({}, callOpts)).schedules.map(item => [item.id, item.configuration.title, item.running, item.busy, item.automations]), + [["msn_legacy_e2e", "Legacy E2E", false, false, ["aut_legacy"]]]) + await native.retireLegacySchedule({ id: "msn_legacy_e2e" }, callOpts) + assert.deepEqual((await native.legacySchedules({}, callOpts)).schedules, []) + console.log("PASS 8 (a schedule the recurring engine left is read and deleted)") + await rm(lease) + await calendars().save("cal_prepared", [rule("cal_prepared", { objective: OBJECTIVE, title: "Prepared E2E", template: "custom", prepared: prepared.id, + when: [{ kind: "branch-commits", directory: root, ref: "refs/heads/main" }] })]) + const programmed = () => daemon.client.experimental.automation.get({ automationID: watchingPrepared.id }) + const watchingPrepared = { id: (await calendars().list())[0].rules[0].automationID } + const still = await until("two runs without a commit", programmed, info => info.runCount >= 2 || info.lastOutcome === "failed", 150_000) + assert.notEqual(still.lastOutcome, "failed", still.lastOutput) + assert.equal((await calendars().list())[0].missionID, prepared.id, "the programmed Mission is the prepared one") + assert.equal((await missions(daemon)).find(mission => mission.id === prepared.id).runState, "prepared") + git("commit", "-q", "--allow-empty", "-m", "third") + await until("the prepared Mission starts", () => missions(daemon).then(list => list.find(mission => mission.id === prepared.id)?.runState, () => "unregistered"), + state => state === "running" || state === "unregistered", 60_000) + assert.deepEqual([(await calendars().list())[0].last?.outcome, (await calendars().list())[0].last?.missionID], ["launched", prepared.id]) + console.log("PASS 7 (a programming saved with a prepared Mission launches by starting that Mission)") + await calendars().delete("cal_prepared") + + const named = await daemon.client.session.create({ title: "Named conversation", location, agent: "plan", model: { providerID: "fixture", id: "other", variant: "high" } }) + assert.deepEqual([named.agent, named.model], ["plan", { providerID: "fixture", id: "other", variant: "high" }]) + await calendars().save("cal_named", [rule("cal_named", { objective: OBJECTIVE, title: "Named E2E", template: "custom", coordinatorSessionID: named.id, + profiles: { coordinator: { agent: "build", model: { providerID: "fixture", id: "fixture" } } } })]) + const chosen = { id: (await calendars().list())[0].rules[0].automationID } + const inNamed = (await until("the named conversation's Mission", () => missions(daemon), list => list.some(mission => mission.title === "Named E2E"), 150_000).catch(async error => { + throw new Error(`${error.message}\nautomation: ${JSON.stringify(await daemon.client.experimental.automation.get({ automationID: chosen.id }).catch(() => null))?.slice(0, 1500)}`) + })).find(mission => mission.title === "Named E2E") + assert.equal(inNamed.coordinatorSessionId, named.id, "the launch coordinates in the conversation it names") + const adopted = await daemon.client.session.get({ sessionID: named.id }) + assert.deepEqual([adopted.agent, adopted.model.providerID, adopted.model.id, adopted.model.variant ?? "default"], ["build", "fixture", "fixture", "default"]) + console.log("PASS 9 (a named conversation on another agent, model and thinking takes the coordinator's and coordinates)") + await calendars().delete("cal_named") +} finally { + console.log("seen:", JSON.stringify({ ...seen, delegated: [...seen.delegated] })) + if (daemon) await daemon.stop().catch(() => {}) + provider.closeAllConnections() + await new Promise(resolve => provider.close(resolve)) +} diff --git a/scripts/test-mission-coordinator-goal-e2e.mjs b/scripts/test-mission-coordinator-goal-e2e.mjs new file mode 100644 index 0000000000..411213ae64 --- /dev/null +++ b/scripts/test-mission-coordinator-goal-e2e.mjs @@ -0,0 +1,320 @@ +// End-to-end isolated OpenCode 2.4.1 test for the REAL bundled `codenomad.missions` plugin +// coordinator `/goal` lifecycle and unattended restart recovery: +// 1. Prepared mission with `coordinatorGoal: true` does NOT arm `/goal` or create watchdog. +// 2. Play (`lifecycle: start`) arms `/goal` on the coordinator and creates the project-level +// Code Mode watchdog automation (`codenomad-mission-goal-watchdog`). +// 3. Graceful Pause (`lifecycle: pause, graceful: true`) pauses the owned `/goal`; +// Resume (`lifecycle: start`) resumes it. +// 4. Closing CodeNomad (removing presence + stopping bridge) + restarting OpenCode `--service` cold: +// the persistent Code Mode watchdog fires unattended inside OpenCode and resumes the +// restart-paused `/goal` (adopting the new daemon's `boot`). +// 5. Restoring presence and deleting the mission clears `/goal` and removes the watchdog cleanly. +// Usage: node --import tsx scripts/test-mission-coordinator-goal-e2e.mjs +import assert from "node:assert/strict" +import { spawn } from "node:child_process" +import { randomUUID } from "node:crypto" +import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises" +import { createServer } from "node:http" +import { DatabaseSync } from "node:sqlite" +import path from "node:path" +import { pathToFileURL } from "node:url" +import { setTimeout as delay } from "node:timers/promises" +import { OpenCode } from "@opencode/client" +import { Service } from "@opencode/client/service" +import { CODENOMAD_MISSIONS_RPC } from "../packages/server/src/missions/rpc.ts" +import { controlResumeAdmissionID } from "../packages/server/src/missions/receipt-identity.ts" +import { COORDINATOR_GOAL_WATCHDOG_NAME } from "../packages/server/src/opencode/missions/native-coordinator-goal.ts" +import { fixtureEnvironment, fixtureParent } from "./native-product-fixture.mjs" +import { stopFixtureChild } from "./native-fixture-guards.mjs" + +const cli = process.argv[2] +assert(cli && path.isAbsolute(cli), "Pass absolute OpenCode CLI path") + +const bundlePath = path.resolve("packages/server/dist/plugins/missions/plugin.mjs") +const root = await mkdtemp(path.join(await fixtureParent(), "mission-coord-goal-e2e-")) +const presenceDir = path.join(root, "presence") +const presenceFile = path.join(presenceDir, `${randomUUID()}.lease`) +await mkdir(presenceDir, { recursive: true }) +await writeFile(presenceFile, "{}", "utf8") + +const password = randomUUID() +const env = await fixtureEnvironment(root, { + OPENCODE_CONFIG_DIR: path.join(root, "config"), + OPENCODE_DB: path.join(root, "fixture.db"), + OPENCODE_CONFIG_PROJECT_DISABLE: "1", + OPENCODE_DISABLE_MODELS_FETCH: "1", + OPENCODE_DISABLE_FFF: "1", + OPENCODE_SERVER_PASSWORD: password, +}) + +const pluginDir = path.join(env.OPENCODE_CONFIG_DIR, "plugins", "codenomad-missions") +await mkdir(pluginDir, { recursive: true }) +await writeFile(path.join(pluginDir, "package.json"), JSON.stringify({ + name: "codenomad-missions-e2e-shim", + type: "module", + exports: { ".": "./index.mjs" }, + opencode: { server: "./index.mjs" }, +}), "utf8") +await writeFile(path.join(pluginDir, "index.mjs"), ` +import { desktopPlugin } from ${JSON.stringify(pathToFileURL(bundlePath).href)} +export default desktopPlugin(${JSON.stringify(presenceDir)}) +`, "utf8") + +let holdTurn = false +const provider = createServer(async (req, res) => { + try { + let raw = "" + for await (const chunk of req) raw += chunk + const body = JSON.parse(raw) + const tools = Array.isArray(body.tools) ? body.tools : [] + res.setHeader("Content-Type", "text/event-stream") + if (tools.length === 0) { + for (const [delta, finish_reason] of [[{ role: "assistant", content: "Fixture Title" }, null], [{}, "stop"]]) { + res.write(`data: ${JSON.stringify({ id: "t", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta, finish_reason }] })}\n\n`) + } + res.end("data: [DONE]\n\n") + return + } + if (holdTurn) await delay(20_000) + for (const [delta, finish_reason] of [[{ role: "assistant", content: "E2E_TURN_REPLY" }, null], [{}, "stop"]]) { + res.write(`data: ${JSON.stringify({ id: "r", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta, finish_reason }] })}\n\n`) + } + res.end("data: [DONE]\n\n") + } catch (err) { + res.destroy(err) + } +}) +await new Promise(resolve => provider.listen(0, "127.0.0.1", resolve)) + +// Minimal isolated automation bridge for `lifecycle` (`Play` / `Resume`) in this E2E test. +let activeClient = null +const bridgeToken = randomUUID() +const bridge = createServer(async (req, res) => { + try { + let raw = "" + for await (const chunk of req) raw += chunk + const body = JSON.parse(raw) + res.setHeader("Content-Type", "application/json") + if (body.mode === "browser-claim") { + res.end(JSON.stringify({ ok: true, result: { available: true } })) + return + } + if (body.mode === "mission-input" && body.command?.kind === "lifecycle") { + const { missionID, operationID, sessionID, startText } = body.command.input + const admission = await activeClient.session.synthetic({ + sessionID, + id: controlResumeAdmissionID(operationID, sessionID), + text: startText ?? "Begin the mission.", + description: "Mission start", + metadata: { "codenomad.mission": { version: 1, missionID, operationID, kind: "lifecycle" } }, + delivery: "queue", + resume: true, + }) + res.end(JSON.stringify({ ok: true, result: { nativeAcknowledgement: { missionID, operationID, sessionID, action: "start", disposition: "start-admitted", admission } } })) + return + } + res.statusCode = 404 + res.end(JSON.stringify({ ok: false, error: "Unsupported mock bridge mode" })) + } catch (err) { + res.statusCode = 500 + res.end(JSON.stringify({ ok: false, error: err instanceof Error ? err.message : String(err) })) + } +}) +await new Promise(resolve => bridge.listen(0, "127.0.0.1", resolve)) + +const bridgeDir = path.join(env.LOCALAPPDATA, "CodeNomad", "automation-bridges") +await mkdir(bridgeDir, { recursive: true }) +const bridgeStartedAt = Date.now() +const bridgeFile = path.join(bridgeDir, `${bridgeStartedAt}-${process.pid}-e2e.json`) +await writeFile(bridgeFile, JSON.stringify({ + version: 1, + pid: process.pid, + startedAt: bridgeStartedAt, + url: `http://127.0.0.1:${bridge.address().port}/api/opencode-plugin/automation`, + token: bridgeToken, +}), "utf8") + +env.OPENCODE_CONFIG_CONTENT = JSON.stringify({ + automations: true, + plugins: [pluginDir], + model: "fixture/fixture", + providers: { + fixture: { + package: "@opencode/ai/providers/openai-compatible", + settings: { baseURL: `http://127.0.0.1:${provider.address().port}/v1`, apiKey: "fixture-only" }, + models: { fixture: {} }, + }, + }, +}) + +async function startDaemon(label) { + let output = "", spawnError + const child = spawn(cli, ["serve", "--service", "--hostname", "127.0.0.1", "--port", "0", "--print-logs"], { cwd: root, env, windowsHide: true }) + const stopped = new Promise(resolve => child.once("close", resolve)) + child.on("error", err => { spawnError = err }) + child.stdout.on("data", d => { output += d }) + child.stderr.on("data", d => { output += d }) + const deadline = Date.now() + 30_000 + while (!/http:\/\/127\.0\.0\.1:\d+/.test(output)) { + if (spawnError) throw spawnError + if (child.exitCode !== null || Date.now() > deadline) throw new Error(`${label} failed:\n${output.slice(-2000)}`) + await delay(25) + } + const file = path.join(env.XDG_STATE_HOME, "opencode/service.json") + let endpoint + while (!endpoint && Date.now() < deadline) { + try { + if (JSON.parse(await readFile(file, "utf8")).pid === child.pid) endpoint = await Service.discover({ file }) + } catch {} + if (!endpoint) await delay(25) + } + assert(endpoint, `${label} did not register isolated service.json`) + const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }) + activeClient = client + const callOpts = { location: { directory: root }, headers: { "x-opencode-directory": root } } + const getGoal = async sessionID => { + const end = Date.now() + 15_000 + while (true) { + try { + return (await client.rpc.call({ rpcID: "opencode.goal", method: "get", input: { sessionID }, location: { directory: root } }, { headers: { "x-opencode-directory": root } })).output + } catch (error) { + if (error?._tag === "RpcError" && error?.type === "rpc.unavailable" && Date.now() < end) { await delay(100); continue } + throw error + } + } + } + return { + child, stopped, client, callOpts, getGoal, + missionsRpc: () => client.rpc(CODENOMAD_MISSIONS_RPC), + stop: async () => { await stopFixtureChild(child, stopped); await writeFile(path.join(root, `daemon-${label}.log`), output) }, + } +} + +const readWatchdogs = () => { + const db = new DatabaseSync(env.OPENCODE_DB, { open: true, readOnly: true }) + try { + return db.prepare("SELECT id, name, status, run_count, last_outcome, last_output FROM automation WHERE name = ?").all(COORDINATOR_GOAL_WATCHDOG_NAME) + } finally { + db.close() + } +} + +let d1, d2 +try { + d1 = await startDaemon("1") + const readyEnd = Date.now() + 20_000 + while (Date.now() < readyEnd) { + try { await d1.missionsRpc().snapshot({}, d1.callOpts); break } + catch { await delay(150) } + } + + // 1. Prepared mission does NOT arm `/goal` or create watchdog. + const created = await d1.missionsRpc().create({ + requestID: "req_goal_e2e_1", + objective: "Keep working across restart", + title: "Restart E2E", + template: "custom", + prepared: true, + coordinatorGoal: true, + }, d1.callOpts) + const missionID = created.mission.id + const coordSessionID = created.mission.coordinatorSessionId + assert.equal(created.mission.coordinatorGoal, true) + await delay(300) + assert.equal(await d1.getGoal(coordSessionID), null, "Prepared mission must NOT arm /goal before Play") + assert.equal(readWatchdogs().length, 0, "Prepared mission must NOT create watchdog before Play") + console.log("PASS E2E 1 (prepared mission does not arm /goal or watchdog)") + + // 2. Play (`lifecycle: start`) arms `/goal` and creates the persistent Code Mode watchdog. + holdTurn = true + const played = await d1.missionsRpc().lifecycle({ + missionID, + requestID: "play_1", + expectedRevision: created.mission.revision, + action: "start", + }, d1.callOpts) + let armedGoal = null + const armEnd = Date.now() + 15_000 + while (Date.now() < armEnd) { + armedGoal = await d1.getGoal(coordSessionID) + if (armedGoal?.status === "active") break + await delay(150) + } + assert.equal(armedGoal?.status, "active", "Play automatically armed /goal on coordinator") + assert.ok(armedGoal.objective.includes("Restart E2E") && armedGoal.objective.includes("mission.report")) + const watchdogsBefore = readWatchdogs() + assert.equal(watchdogsBefore.length, 1, "Watchdog automation created after Play") + assert.equal(watchdogsBefore[0].status, "active") + console.log("PASS E2E 2 (Play auto-armed /goal + created Code Mode watchdog, boot=", armedGoal.boot, ")") + + // 3. Graceful Pause pauses owned `/goal`; Resume resumes it. + const paused = await d1.missionsRpc().lifecycle({ + missionID, + requestID: "pause_1", + expectedRevision: played.mission.revision, + action: "pause", + graceful: true, + }, d1.callOpts) + const goalAfterPause = await d1.getGoal(coordSessionID) + assert.equal(goalAfterPause?.status, "paused", "Graceful Pause paused owned /goal") + + const resumed = await d1.missionsRpc().lifecycle({ + missionID, + requestID: "resume_1", + expectedRevision: paused.mission.revision, + action: "start", + }, d1.callOpts) + const goalAfterResume = await d1.getGoal(coordSessionID) + assert.equal(goalAfterResume?.status, "active", "Mission Resume resumed owned /goal") + console.log("PASS E2E 3 (Graceful Pause paused /goal and Resume resumed it)") + + // 4. Close CodeNomad (remove presence + bridge registration) and restart OpenCode `--service` cold! + await rm(presenceFile, { force: true }) + await rm(bridgeFile, { force: true }) + await d1.stop(); d1 = null + holdTurn = false + d2 = await startDaemon("2") + + const pausedAfterRestart = await d2.getGoal(coordSessionID) + assert.equal(pausedAfterRestart?.status, "paused") + assert.equal(pausedAfterRestart?.boot, armedGoal.boot) + assert.equal(pausedAfterRestart?.reason, "The server restarted while the goal was active") + + let recovered = null + const watchStart = Date.now() + const watchDeadline = watchStart + 85_000 + while (Date.now() < watchDeadline) { + recovered = await d2.getGoal(coordSessionID) + if (recovered && recovered.boot !== armedGoal.boot) break + await delay(500) + } + console.log(`[E2E 4] unattended recovery took ${Date.now() - watchStart}ms:`, recovered) + assert.ok(recovered && recovered.boot !== armedGoal.boot, "Bundled codenomad.missions watchdog resumed /goal unattended across restart!") + console.log("PASS E2E 4 (unattended real plugin watchdog resumed /goal with CodeNomad closed!)") + + // 5. Restore presence, delete mission, and verify watchdog automation is removed cleanly. + await writeFile(presenceFile, "{}", "utf8") + const snapEnd = Date.now() + 20_000 + let snap + while (Date.now() < snapEnd) { + try { snap = await d2.missionsRpc().snapshot({}, d2.callOpts); break } + catch { await delay(150) } + } + const live = snap.missions.find(m => m.id === missionID) + await d2.missionsRpc().delete({ + missionID: live.id, + requestID: "del_1", + expectedRevision: live.revision, + deleteManagedSessions: false, + }, d2.callOpts) + await delay(500) + assert.equal(readWatchdogs().length, 0, "Watchdog automation removed automatically once no active goal missions remain") + console.log("PASS E2E 5 (watchdog automation cleaned up automatically after mission deletion!)") +} finally { + if (d1) await d1.stop().catch(() => {}) + if (d2) await d2.stop().catch(() => {}) + bridge.closeAllConnections() + await new Promise(resolve => bridge.close(resolve)) + provider.closeAllConnections() + await new Promise(resolve => provider.close(resolve)) +} diff --git a/scripts/test-mission-document-native.mjs b/scripts/test-mission-document-native.mjs index 7edd54ef40..a8697ea410 100644 --- a/scripts/test-mission-document-native.mjs +++ b/scripts/test-mission-document-native.mjs @@ -70,10 +70,6 @@ await withProductRuntime(process.argv[2], async ({ root, configDirectory }) => { assert.equal(created.document.launchedCount, 0) assert.deepEqual(created.document.launch.timing, { kind: "immediate" }) assert.equal(created.document.scheduleActivation, null) - const activationIdentity = { missionID: created.id, requestID: "activation-is-not-immediate", expectedRevision: created.document.revision } - const activationRead = await rpc.documentActivation({ ...activationIdentity, action: "read" }, { location }) - assert.equal(activationRead.document.scheduleActivation, null) - await assert.rejects(rpc.documentActivation({ ...activationIdentity, action: "prepare", authority: "a".repeat(64), targets: [] }, { location })) await delay(250) assert.equal(requests.length, 0, "Creation causes zero provider requests") const db = new DatabaseSync(path.join(root, "fixture.db"), { readOnly: true }) diff --git a/scripts/test-mission-experimental-settings-native.mjs b/scripts/test-mission-experimental-settings-native.mjs deleted file mode 100644 index 31a0ba4f45..0000000000 --- a/scripts/test-mission-experimental-settings-native.mjs +++ /dev/null @@ -1,190 +0,0 @@ -// Real native config discovery/watcher, no schedule creation or model request. -import assert from "node:assert/strict" -import { mkdir, readFile, rm, writeFile } from "node:fs/promises" -import path from "node:path" -import { setTimeout as delay } from "node:timers/promises" -import { parse } from "jsonc-parser" -import { withProductRuntime } from "./native-product-fixture.mjs" -import { PluginControls } from "../packages/server/src/opencode/plugin-controls.ts" -import { SubagentDepthSettings } from "../packages/server/src/opencode/subagent-depth-settings.ts" -import { NativeScheduleCapabilityReader } from "../packages/server/src/opencode/native-schedule-capability.ts" -import { editMissionExperimental, inheritedMissionExperimental, nativeSettingExpectation } from "../packages/server/src/opencode/native-experimental-settings.ts" -import { NativeScheduleSettingsActivation } from "../packages/server/src/opencode/native-schedule-settings-activation.ts" -import { DesktopPluginLifecycle } from "../packages/server/src/opencode/desktop-plugin-lifecycle.ts" -import { resolveDesktopPluginPaths } from "../packages/server/src/opencode/desktop-plugin-paths.ts" -import { CODENOMAD_MISSIONS_RPC } from "../packages/server/src/missions/rpc.ts" - -await withProductRuntime(process.argv[2], async ({ configDirectory }) => { - await writeFile(path.join(configDirectory, "opencode.jsonc"), '{"experimental":{"subagent_depth":2,"schedules":true}}\n') -}, async ({ root, connection, requests }) => { - assert.equal((await connection.client.server.info()).version, "2.3.0") - const plugin = new DesktopPluginLifecycle("missions") - const paths = await resolveDesktopPluginPaths(connection, { kind: "host", platform: process.platform, binary: process.argv[2] }) - assert.ok(paths.config.startsWith(root)) - await plugin.start(paths) - try { - const manager = { - get: () => ({}), getSharedServiceConnection: async () => connection, - getServiceDirectoryForPath: async (_id, directory) => directory === root ? root : undefined, - ownsLocation: async (_id, location) => location.directory === root, - getWorktreeIdentityForPath: async () => "private-fixture-root", - getServicePathStyle: () => process.platform === "win32" ? "win32" : "posix", - getServiceWslDistro: () => undefined, getHostPathForServicePath: async (_id, value) => value, - } - const controls = new PluginControls({ workspaceManager: manager, - worktreeDeletionFence: { enter: () => () => {} }, logger: {} }) - const depths = new SubagentDepthSettings(controls, manager) - const schedules = new NativeScheduleCapabilityReader(controls, manager) - const location = { directory: root } - const until = async (check, description) => { - const deadline = Date.now() + 10_000 - do { if (await check()) return; await delay(100) } while (Date.now() < deadline) - throw Error(`Native watcher did not acknowledge ${description}`) - } - await until(async () => (await connection.client.plugin.list({ location })).data.some(entry => - entry.id === "codenomad.missions" && entry.state.status === "active"), "private Missions plugin") - assert.deepEqual(await connection.client.rpc(CODENOMAD_MISSIONS_RPC).scheduleFlag({}, { location }), - { enabled: true, provenance: "experimental-block" }) - const initial = await depths.read("fixture", location) - assert.equal(initial.effectiveDepth, 2) - assert.deepEqual((await schedules.read("fixture", location)).api, { available: true }) - await depths.update("fixture", location, 8, initial.project.expectation) - const file = initial.project.path - assert.deepEqual(parse(await readFile(file, "utf8")).experimental, { schedules: true, subagent_depth: 8 }) - await until(async () => (await schedules.read("fixture", location)).enabled && (await depths.read("fixture", location)).effectiveDepth === 8, "inherited schedules + depth 8") - assert.equal((await schedules.read("fixture", location)).origin, file) - await depths.update("fixture", location, 0, (await depths.read("fixture", location)).project.expectation) - await depths.update("fixture", location, null, (await depths.read("fixture", location)).project.expectation) - assert.deepEqual(parse(await readFile(file, "utf8")).experimental, { schedules: true }) - await until(async () => (await depths.read("fixture", location)).effectiveDepth === null && (await schedules.read("fixture", location)).enabled, "depth removal preserving schedules") - // Depth-only project created before activation; prepare expectation before editing. - await writeFile(file, '\uFEFF{\r\n\t// keep\r\n\t"experimental":{"subagent_depth":8,"todo":true}\r\n}\r\n') - await until(async () => !(await schedules.read("fixture", location)).enabled, "project depth-only masking global") - const acquired = await controls.readConfigDocuments("fixture", location) - const project = acquired.documents.find(document => document.scope === "project") - const expected = nativeSettingExpectation(project.document) - await controls.editConfigDocument("fixture", location, "project", (document, current) => { - assert.equal(nativeSettingExpectation(document), expected) - return editMissionExperimental(document, "schedules", true, - inheritedMissionExperimental(current.entries, current.path, current.location.directory)) - }) - const saved = await readFile(file, "utf8") - assert.match(saved, /^\uFEFF/); assert.match(saved, /\r\n\t\/\/ keep/) - assert.deepEqual(parse(saved.slice(1)).experimental, { subagent_depth: 8, todo: true, schedules: true }) - await until(async () => (await schedules.read("fixture", location)).enabled, "project activation") - await writeFile(file, '{"experimental":{"schedules":false,"subagent_depth":0}}') - await assert.rejects(controls.editConfigDocument("fixture", location, "project", document => - editMissionExperimental(document, "schedules", true, {})), /explicitly disabled/) - const competing = path.join(path.dirname(file), "opencode.json") - await writeFile(competing, "{}") - await assert.rejects(depths.read("fixture", location), /JSON and JSONC/) - await rm(competing) - const globalFile = (await controls.readConfigDocuments("fixture", location)).documents.find(item => item.scope === "global").path - await writeFile(globalFile, '{"experimental":{"schedules":false,"subagent_depth":2}}\n') - await writeFile(file, '{"experimental":{"subagent_depth":8}}\n') - await until(async () => (await connection.client.config.get({ location })).some(entry => - entry.type === "document" && entry.path === globalFile && entry.info.experimental?.schedules === false), "global OFF before activation") - const activate = () => new NativeScheduleSettingsActivation(controls, manager) - await assert.rejects(activate().prepare("fixture", location), error => - error.code === "schedule-activation-refused" && error.refusal.path === globalFile) - await writeFile(globalFile, '{"experimental":{"subagent_depth":2}}\n') - await until(async () => (await connection.client.config.get({ location })).some(entry => - entry.type === "document" && entry.path === globalFile && entry.info.experimental?.schedules === undefined), "global OFF cleared") - const globalBefore = await readFile(globalFile, "utf8") - const plan = await activate().prepare("fixture", location) - assert.deepEqual(plan.targets.map(item => item.scope), ["project"]) - const intent = { ...plan, targets: plan.targets.map(target => ({ ...target, attempted: false, acknowledged: false })) } - const intentFile = path.join(root, "activation-intent.json") - const save = () => writeFile(intentFile, JSON.stringify(intent)) - await save() - let ready = false, lose = true - const journal = { - prepared: async () => { await save() }, - attempting: async scope => { intent.targets.find(item => item.scope === scope).attempted = true; await save() }, - acknowledged: async scope => { - if (scope === "project" && lose) { lose = false; throw Error("lost activation ACK") } - intent.targets.find(item => item.scope === scope).acknowledged = true; await save() - }, - ready: async origin => { assert.equal(origin, file); ready = true }, - } - await assert.rejects(activate().apply("fixture", location, structuredClone(intent), journal), /lost activation ACK/) - assert.equal(ready, false) - assert.equal(await readFile(globalFile, "utf8"), globalBefore) - assert.equal(parse(await readFile(file, "utf8")).experimental.schedules, true) - await activate().apply("fixture", location, JSON.parse(await readFile(intentFile, "utf8")), journal) - assert.equal(ready, true) - assert.ok(intent.targets.every(target => target.acknowledged)) - assert.equal((await schedules.read("fixture", location)).enabled, true) - // An existing project block already selects its own native depth default. - // Enabling schedules in that block must not materialize the hidden global depth. - await writeFile(file, '{"experimental":{"todo":true}}\n') - await until(async () => !(await schedules.read("fixture", location)).enabled - && (await depths.read("fixture", location)).effectiveDepth === null, "existing project block before schedule activation") - const depthBefore = (await depths.read("fixture", location)).effectiveDepth - await controls.editConfigDocument("fixture", location, "project", (document, current) => - editMissionExperimental(document, "schedules", true, - inheritedMissionExperimental(current.entries, current.path, current.location.directory))) - assert.deepEqual(parse(await readFile(file, "utf8")).experimental, { todo: true, schedules: true }) - await until(async () => (await schedules.read("fixture", location)).enabled, "schedule activation preserving existing depth default") - assert.equal((await depths.read("fixture", location)).effectiveDepth, depthBefore) - assert.equal(requests.length, 0) - const enabledPlan = await activate().prepare("fixture", location) - assert.deepEqual(enabledPlan.targets, []) - assert.equal(await readFile(globalFile, "utf8"), globalBefore) - console.log("PASS native 2.3.0 Flag RPC, whole-block precedence, both writer orders, depth 0/removal, effective watcher read, explicit global/project OFF, BOM/EOL/comments, ambiguous JSON/JSONC; zero provider HTTP") - console.log("PASS project-only activation, durable intent/attempts, lost project ACK observation, positive native acknowledgement and zero-target already-ON plan") - console.log("PASS schedule activation preserves the effective native depth of an existing project experimental block") - } finally { await plugin.stop() } -}, { projectConfig: true }) - -// Each case owns a fresh daemon: its environment is independent of the backend's. -for (const scenario of [ - { name: "environment OFF over configured ON", flags: "fixture,-schedules", global: { schedules: true }, - enabled: false, provenance: "environment", refused: true }, - { name: "environment ON", flags: "fixture,schedules", global: {}, - enabled: true, provenance: "environment" }, - { name: "all-flags below a project block", global: { all_flags: true }, project: { todo: true }, - enabled: true, provenance: "all-flags" }, - { name: "all-flags false falls through to the channel default", global: { all_flags: false }, project: {}, - enabled: false, provenance: "channel-default" }, -]) { - await withProductRuntime(process.argv[2], async ({ root, configDirectory }) => { - await writeFile(path.join(configDirectory, "opencode.jsonc"), JSON.stringify({ experimental: scenario.global })) - if (scenario.project) { - await mkdir(path.join(root, ".opencode")) - await writeFile(path.join(root, ".opencode", "opencode.jsonc"), JSON.stringify({ experimental: scenario.project })) - } - }, async ({ root, connection, requests }) => { - const plugin = new DesktopPluginLifecycle("missions"), location = { directory: root } - const paths = await resolveDesktopPluginPaths(connection, { kind: "host", platform: process.platform, binary: process.argv[2] }) - assert.ok(paths.config.startsWith(root)) - await plugin.start(paths) - try { - const deadline = Date.now() + 15_000 - while (!(await connection.client.plugin.list({ location })).data.some(entry => - entry.id === "codenomad.missions" && entry.state.status === "active")) { - assert.ok(Date.now() < deadline, "Private flag plugin unavailable") - await delay(100) - } - assert.deepEqual(await connection.client.rpc(CODENOMAD_MISSIONS_RPC).scheduleFlag({}, { location }), - { enabled: scenario.enabled, provenance: scenario.provenance }) - const manager = { get: () => ({}), getSharedServiceConnection: async () => connection, - getServiceDirectoryForPath: async (_id, directory) => directory === root ? root : undefined, - ownsLocation: async (_id, selected) => selected.directory === root, getWorktreeIdentityForPath: async () => "flag-fixture", - getServicePathStyle: () => process.platform === "win32" ? "win32" : "posix", - getServiceWslDistro: () => undefined, getHostPathForServicePath: async (_id, value) => value } - const controls = new PluginControls({ workspaceManager: manager, worktreeDeletionFence: { enter: () => () => {} }, logger: {} }) - const activate = new NativeScheduleSettingsActivation(controls, manager) - const globalFile = path.join(paths.config, "opencode.jsonc"), original = await readFile(globalFile, "utf8") - if (scenario.refused) await assert.rejects(activate.prepare("fixture", location), error => - error.code === "schedule-activation-refused" && error.refusal.layer === "environment") - else { - const plan = await activate.prepare("fixture", location) - assert.deepEqual(plan.targets.map(target => target.scope), scenario.enabled ? [] : ["project"]) - } - assert.equal(await readFile(globalFile, "utf8"), original) - assert.equal(requests.length, 0) - console.log(`PASS native ${scenario.name}: exact provenance, correct plan/refusal, zero configuration writes/provider HTTP`) - } finally { await plugin.stop() } - }, { projectConfig: true, flags: scenario.flags }) -} diff --git a/scripts/test-mission-goal-restart-native.mjs b/scripts/test-mission-goal-restart-native.mjs new file mode 100644 index 0000000000..7741fdfeb0 --- /dev/null +++ b/scripts/test-mission-goal-restart-native.mjs @@ -0,0 +1,350 @@ +// Isolated OpenCode 2.4.1 qualification probe for Mission coordinator `/goal`: +// 1. Restart behavior: exact pause reason, boot lifecycle, /goal resume +// 2. Background subagent interaction: /goal waits while a background child subagent runs +// 3. Pending `question` tool interaction: /goal stays quiet while waiting on a human +// 4. Unattended restart recovery: a Code Mode automation surviving daemon restart calls +// a plugin RPC that reads `opencode.goal.get` and resumes the restart-paused `/goal`. +// Usage: node --import tsx scripts/test-mission-goal-restart-native.mjs +import assert from "node:assert/strict" +import { spawn } from "node:child_process" +import { randomUUID } from "node:crypto" +import { mkdtemp, mkdir, readFile, writeFile } from "node:fs/promises" +import { createServer } from "node:http" +import path from "node:path" +import { pathToFileURL } from "node:url" +import { setTimeout as delay } from "node:timers/promises" +import { OpenCode } from "@opencode/client" +import { Service } from "@opencode/client/service" +import { fixtureEnvironment, fixtureParent } from "./native-product-fixture.mjs" +import { stopFixtureChild } from "./native-fixture-guards.mjs" + +const cli = process.argv[2] +assert(cli && path.isAbsolute(cli), "Pass absolute OpenCode CLI path") + +const root = await mkdtemp(path.join(await fixtureParent(), "mission-goal-probe-")) +const password = randomUUID() +const env = await fixtureEnvironment(root, { + OPENCODE_CONFIG_DIR: path.join(root, "config"), + OPENCODE_DB: path.join(root, "fixture.db"), + OPENCODE_CONFIG_PROJECT_DISABLE: "1", + OPENCODE_DISABLE_MODELS_FETCH: "1", + OPENCODE_DISABLE_FFF: "1", + OPENCODE_SERVER_PASSWORD: password, +}) +const pluginDir = path.join(env.OPENCODE_CONFIG_DIR, "plugins", "goal-watchdog-probe") +await mkdir(pluginDir, { recursive: true }) + +// Minimal native plugin registered in the isolated config dir that exposes a Code Mode tool +// calling `opencode.goal.get` and `session.command({ name: "goal", text: "resume" })`. +await writeFile(path.join(pluginDir, "package.json"), JSON.stringify({ + name: "probe-goal-watchdog", + type: "module", + exports: { ".": "./index.mjs" }, + opencode: { server: "./index.mjs" }, +}), "utf8") +await writeFile(path.join(pluginDir, "index.mjs"), ` +const pass = { "~standard": { version: 1, vendor: "probe", validate: value => ({ value }) } } +const GoalRpcDef = { + id: "opencode.goal", + methods: { get: { input: pass, output: pass } }, + events: { changed: { schema: pass } }, +} +export default { + id: "probe.goal.watchdog", + setup: async ctx => { + const goalRpc = ctx.rpc(GoalRpcDef) + await ctx.tool.transform(editor => editor.add({ + name: "probe_goal_reconcile", + description: "Read a session's goal and resume it if paused by an OpenCode restart.", + input: { + type: "object", + properties: { sessionID: { type: "string" } }, + required: ["sessionID"], + additionalProperties: false, + }, + options: { namespace: "probe", codemode: true, permission: "probe_goal_reconcile" }, + execute: async input => { + const goal = await goalRpc.get({ sessionID: input.sessionID }) + if (goal && goal.status === "paused" && goal.reason === "The server restarted while the goal was active") { + await ctx.session.command({ sessionID: input.sessionID, name: "goal", text: "resume" }) + const after = await goalRpc.get({ sessionID: input.sessionID }) + return { content: JSON.stringify({ action: "resumed", beforeBoot: goal.boot, afterStatus: after?.status, afterBoot: after?.boot }) } + } + return { content: JSON.stringify({ action: "noop", status: goal?.status ?? null, reason: goal?.reason ?? null }) } + }, + })) + }, +} +`, "utf8") + +let scenario = "restart" +let childHoldRelease = null +let childStartedAt = 0 +let childFinishedAt = 0 +let rootTurnCount = 0 +const turnsDuringChild = [] + +const provider = createServer(async (req, res) => { + try { + let raw = "" + for await (const chunk of req) raw += chunk + const body = JSON.parse(raw) + const messages = Array.isArray(body.messages) ? body.messages : [] + const allText = messages.map(m => typeof m.content === "string" ? m.content : JSON.stringify(m.content)).join("\n") + const tools = Array.isArray(body.tools) ? body.tools.map(t => t?.function?.name).filter(Boolean) : [] + const isChild = allText.includes("PROBE_CHILD_PROMPT") + + if (isChild) { + childStartedAt = Date.now() + await new Promise(resolve => { + const timer = setTimeout(resolve, 3500) + childHoldRelease = () => { clearTimeout(timer); resolve() } + }) + childFinishedAt = Date.now() + res.setHeader("Content-Type", "text/event-stream") + for (const [delta, finish_reason] of [[{ role: "assistant", content: "CHILD_DONE" }, null], [{}, "stop"]]) { + res.write(`data: ${JSON.stringify({ id: "child", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta, finish_reason }] })}\n\n`) + } + res.end("data: [DONE]\n\n") + return + } + + // Ignore auxiliary tool-less LLM calls (title generation) when counting root turns. + if (tools.length === 0) { + res.setHeader("Content-Type", "text/event-stream") + const auxReply = allText.includes("GOAL_REVIEW") || allText.toLowerCase().includes("goal") ? JSON.stringify({ done: false, reason: "Still waiting on child" }) : "Fixture Title" + for (const [delta, finish_reason] of [[{ role: "assistant", content: auxReply }, null], [{}, "stop"]]) { + res.write(`data: ${JSON.stringify({ id: "aux", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta, finish_reason }] })}\n\n`) + } + res.end("data: [DONE]\n\n") + return + } + + rootTurnCount++ + if (scenario === "subagent" && childStartedAt > 0 && childFinishedAt === 0 && rootTurnCount > 2) { + turnsDuringChild.push({ rootTurnCount, at: Date.now() }) + } + res.setHeader("Content-Type", "text/event-stream") + + if ((scenario === "restart" || scenario === "watchdog-restart") && rootTurnCount === 1) { + await delay(15_000) + for (const [delta, finish_reason] of [[{ role: "assistant", content: "TURN1_LATE" }, null], [{}, "stop"]]) { + res.write(`data: ${JSON.stringify({ id: "r1", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta, finish_reason }] })}\n\n`) + } + res.end("data: [DONE]\n\n") + return + } + + if (scenario === "subagent" && rootTurnCount === 1) { + const subTool = tools.find(t => t === "subagent") + assert(subTool, "subagent tool must be available") + const args = JSON.stringify({ agent: "explore", description: "Probe slow child", prompt: "PROBE_CHILD_PROMPT" }) + res.write(`data: ${JSON.stringify({ id: "s1", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta: { role: "assistant", tool_calls: [{ index: 0, id: "call_sub_1", type: "function", function: { name: subTool, arguments: args } }] }, finish_reason: null }] })}\n\n`) + res.write(`data: ${JSON.stringify({ id: "s1", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] })}\n\n`) + res.end("data: [DONE]\n\n") + return + } + + if (scenario === "question" && rootTurnCount === 1) { + const qTool = tools.find(t => t === "question") + assert(qTool, "question tool must be available") + const args = JSON.stringify({ questions: [{ header: "Probe", question: "Proceed?", options: [{ label: "Yes", description: "Continue" }] }] }) + res.write(`data: ${JSON.stringify({ id: "q1", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta: { role: "assistant", tool_calls: [{ index: 0, id: "call_q_1", type: "function", function: { name: qTool, arguments: args } }] }, finish_reason: null }] })}\n\n`) + res.write(`data: ${JSON.stringify({ id: "q1", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] })}\n\n`) + res.end("data: [DONE]\n\n") + return + } + + if (scenario === "watchdog-arm" && rootTurnCount === 1) { + // Root invokes Code Mode `execute` to create a persistent Code Mode automation that will survive daemon restart + const execTool = tools.find(t => t === "execute") + assert(execTool, `execute tool must be available; saw: ${tools.join(",")}`) + const targetSessionID = globalThis.__watchdogTargetSessionID + const code = ` +const created = await tools.automation.create({ + name: "goal-watchdog-probe", + trigger: { type: "every", every: "15 seconds" }, + action: { + type: "code", + code: \` + const res = await tools.probe.probe_goal_reconcile({ sessionID: ${JSON.stringify(targetSessionID)} }); + const parsed = JSON.parse(typeof res === "string" ? res : JSON.stringify(res)); + if (parsed.action === "resumed") return { done: true, state: parsed }; + return { state: parsed }; + \` + } +}); +return created; +` + res.write(`data: ${JSON.stringify({ id: "a1", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta: { role: "assistant", tool_calls: [{ index: 0, id: "call_exec_1", type: "function", function: { name: execTool, arguments: JSON.stringify({ code }) } }] }, finish_reason: null }] })}\n\n`) + res.write(`data: ${JSON.stringify({ id: "a1", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] })}\n\n`) + res.end("data: [DONE]\n\n") + return + } + + if (scenario === "watchdog-arm" && rootTurnCount === 2) { + console.log("[PROBE 4] execute result message:", JSON.stringify(messages.at(-1)).slice(0, 400)) + } + + for (const [delta, finish_reason] of [[{ role: "assistant", content: `ROOT_REPLY_${scenario}_${rootTurnCount}` }, null], [{}, "stop"]]) { + res.write(`data: ${JSON.stringify({ id: "rx", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta, finish_reason }] })}\n\n`) + } + res.end("data: [DONE]\n\n") + } catch (err) { + console.error("[provider] error:", err) + res.destroy(err) + } +}) + +await new Promise(resolve => provider.listen(0, "127.0.0.1", resolve)) +env.OPENCODE_CONFIG_CONTENT = JSON.stringify({ + automations: true, + plugins: [pluginDir], + model: "fixture/fixture", + providers: { + fixture: { + package: "@opencode/ai/providers/openai-compatible", + settings: { baseURL: `http://127.0.0.1:${provider.address().port}/v1`, apiKey: "fixture-only" }, + models: { fixture: {} }, + }, + }, +}) + +async function startDaemon(label) { + let output = "", spawnError + const child = spawn(cli, ["serve", "--service", "--hostname", "127.0.0.1", "--port", "0", "--print-logs"], { cwd: root, env, windowsHide: true }) + const stopped = new Promise(resolve => child.once("close", resolve)) + child.on("error", err => { spawnError = err }) + child.stdout.on("data", d => { output += d }) + child.stderr.on("data", d => { output += d }) + const deadline = Date.now() + 30_000 + while (!/http:\/\/127\.0\.0\.1:\d+/.test(output)) { + if (spawnError) throw spawnError + if (child.exitCode !== null || Date.now() > deadline) throw new Error(`${label} failed:\n${output.slice(-2000)}`) + await delay(25) + } + const file = path.join(env.XDG_STATE_HOME, "opencode/service.json") + let endpoint + while (!endpoint && Date.now() < deadline) { + if (spawnError) throw spawnError + if (child.exitCode !== null) throw new Error(`${label} exited before registration:\n${output.slice(-2000)}`) + try { + if (JSON.parse(await readFile(file, "utf8")).pid === child.pid) endpoint = await Service.discover({ file }) + } catch {} + if (!endpoint) await delay(25) + } + assert(endpoint, `${label} did not register isolated service.json`) + const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }) + const getGoal = async sessionID => { + const deadline = Date.now() + 15_000 + while (true) { + try { + return (await client.rpc.call({ + rpcID: "opencode.goal", method: "get", input: { sessionID }, location: { directory: root }, + }, { headers: { "x-opencode-directory": root } })).output + } catch (error) { + if (error?._tag === "RpcError" && error?.type === "rpc.unavailable" && Date.now() < deadline) { + await delay(100) + continue + } + throw error + } + } + } + return { + child, stopped, client, getGoal, + stop: async () => { await stopFixtureChild(child, stopped); await writeFile(path.join(root, `daemon-${label}.log`), output) }, + } +} + +let d1, d2, d3 +try { + // === PROBE 1: RESTART === + d1 = await startDaemon("1") + const ses1 = await d1.client.session.create({ location: { directory: root } }) + await d1.client.session.command({ sessionID: ses1.id, name: "goal", text: "Probe restart resilience", delivery: "steer" }) + let g1 = null + for (let i = 0; i < 60 && g1?.status !== "active"; i++) { await delay(100); g1 = await d1.getGoal(ses1.id) } + assert.equal(g1?.status, "active") + + await d1.stop(); d1 = null + d2 = await startDaemon("2") + const g2 = await d2.getGoal(ses1.id) + assert.equal(g2?.id, g1.id) + assert.equal(g2?.status, "paused") + assert.equal(g2?.reason, "The server restarted while the goal was active") + assert.equal(g2?.boot, g1.boot, "paused goal keeps the dead boot until resumed") + + scenario = "resumed"; rootTurnCount = 0 + await d2.client.session.command({ sessionID: ses1.id, name: "goal", text: "resume", delivery: "steer" }) + await delay(600) + const g2Resumed = await d2.getGoal(ses1.id) + assert.equal(g2Resumed?.id, g1.id) + assert.notEqual(g2Resumed?.boot, g1.boot, "resumed goal adopts the new daemon boot") + await d2.client.session.command({ sessionID: ses1.id, name: "goal", text: "clear", delivery: "steer" }) + console.log("PASS PROBE 1 (restart pause + dead boot preserved + resume updates boot)") + + // === PROBE 2: BACKGROUND SUBAGENT === + scenario = "subagent"; rootTurnCount = 0; childStartedAt = 0; childFinishedAt = 0; turnsDuringChild.length = 0 + const ses2 = await d2.client.session.create({ location: { directory: root } }) + await d2.client.session.command({ sessionID: ses2.id, name: "goal", text: "Wait for child subagent before finishing", delivery: "steer" }) + const subDeadline = Date.now() + 15_000 + while (childFinishedAt === 0 && Date.now() < subDeadline) await delay(100) + assert.ok(childStartedAt > 0 && childFinishedAt > childStartedAt, "child ran and finished") + assert.deepEqual(turnsDuringChild, [], "goal reviewer must NOT fire while background child subagent is running") + await delay(800) + await d2.client.session.command({ sessionID: ses2.id, name: "goal", text: "clear", delivery: "steer" }).catch(() => {}) + console.log("PASS PROBE 2 (/goal waits cleanly while background subagent runs; 0 premature turns)") + + // === PROBE 3: PENDING QUESTION === + scenario = "question"; rootTurnCount = 0 + const ses3 = await d2.client.session.create({ location: { directory: root } }) + await d2.client.session.command({ sessionID: ses3.id, name: "goal", text: "Ask user before continuing", delivery: "steer" }) + await delay(2500) + const gQ = await d2.getGoal(ses3.id) + assert.equal(gQ?.status, "active") + assert.equal(rootTurnCount, 1, "goal reviewer stays quiet while question tool is pending") + await d2.client.session.interrupt({ sessionID: ses3.id }).catch(() => {}) + await delay(200) + await d2.client.session.command({ sessionID: ses3.id, name: "goal", text: "clear", delivery: "steer" }).catch(() => {}) + console.log("PASS PROBE 3 (/goal stays quiet while question tool is pending)") + + // === PROBE 4: UNATTENDED CODE MODE AUTOMATION WATCHDOG ACROSS RESTART === + const ses4 = await d2.client.session.create({ location: { directory: root } }) + globalThis.__watchdogTargetSessionID = ses4.id + // First arm the Code Mode watchdog automation from an auxiliary session + const sesWatch = await d2.client.session.create({ location: { directory: root } }) + scenario = "watchdog-arm"; rootTurnCount = 0 + await d2.client.session.prompt({ sessionID: sesWatch.id, text: "Arm watchdog" }) + await delay(1500) + // Now arm `/goal` on ses4 and kill daemon #2 while ses4's goal is active! + scenario = "watchdog-restart"; rootTurnCount = 0 + await d2.client.session.command({ sessionID: ses4.id, name: "goal", text: "Probe watchdog restart recovery", delivery: "steer" }) + let g4Before = null + for (let i = 0; i < 60 && g4Before?.status !== "active"; i++) { await delay(100); g4Before = await d2.getGoal(ses4.id) } + assert.equal(g4Before?.status, "active") + console.log("[PROBE 4] armed ses4 goal before restart, boot=", g4Before.boot) + + await d2.stop(); d2 = null + // Start daemon #3 WITHOUT calling any manual /goal resume — wait for the persistent Code Mode watchdog to resume it! + scenario = "watchdog-recovered"; rootTurnCount = 0 + d3 = await startDaemon("3") + let g4After = null + const watchStart = Date.now() + const watchDeadline = watchStart + 75_000 + while (Date.now() < watchDeadline) { + g4After = await d3.getGoal(ses4.id) + if (g4After && g4After.boot !== g4Before.boot) break + await delay(500) + } + console.log(`[PROBE 4] after unattended restart (${Date.now() - watchStart}ms):`, g4After) + assert.ok(g4After && g4After.boot !== g4Before.boot, "Code Mode watchdog automatically resumed /goal on daemon #3!") + console.log("PASS PROBE 4 (unattended Code Mode automation resumed restart-paused /goal across OpenCode restart!)") +} finally { + if (childHoldRelease) childHoldRelease() + if (d1) await d1.stop().catch(() => {}) + if (d2) await d2.stop().catch(() => {}) + if (d3) await d3.stop().catch(() => {}) + provider.closeAllConnections() + await new Promise(resolve => provider.close(resolve)) +} diff --git a/scripts/test-mission-journal-head-native.mjs b/scripts/test-mission-journal-head-native.mjs new file mode 100644 index 0000000000..ae29a77e6e --- /dev/null +++ b/scripts/test-mission-journal-head-native.mjs @@ -0,0 +1,70 @@ +// Pass the absolute path to an OpenCode executable. Uses a private child and +// database containing only synthetic journal rows (no Mission or session RPC). +import assert from "node:assert/strict" +import { mkdir, writeFile } from "node:fs/promises" +import { join, resolve } from "node:path" +import { pathToFileURL } from "node:url" +import { setTimeout as delay } from "node:timers/promises" +import { DatabaseSync } from "node:sqlite" +import { build } from "esbuild" +import { withProductRuntime } from "./native-product-fixture.mjs" +import { nativePluginBuild } from "../packages/server/scripts/native-plugin-build.mjs" + +const method = { input: { type: "object" }, output: { type: "object" } } +const rpc = { id: "fixture.mission-head", methods: { read: method }, events: {} } +await withProductRuntime(process.argv[2], async ({ root }) => { + const directory = join(root, "journal-head") + await mkdir(directory) + const plugin = join(directory, "server.mjs") + await build({ ...nativePluginBuild, stdin: { resolveDir: resolve("packages/server/src"), loader: "ts", + contents: ` +import { Plugin, Rpc } from "@opencode/plugin/effect" +import { Effect } from "effect" +import { acquireNativeJournalRange } from "./opencode/missions/native-journal-range" +import { stableToken } from "./missions/receipt-identity" +export default Plugin.define({ id: "codenomad.missions", effect: ctx => { + const missionID = "msn_fixture", id = "evt_fixture", { id: projectID, canonical } = ctx.location.project + const key = "codenomad-missions/v2/" + stableToken(projectID + "\\0" + canonical, 24) + "/" + missionID + "/" + id + return ctx.rpc.register(Rpc.define(${JSON.stringify(rpc)}), { read: input => Effect.gen(function* () { + if (input.seed) yield* ctx.storage.set(key, { version:1, projectID, missionID, id, createdAt:1, type:"mission.updated", + requestID: "fixture", expectedRevision:1, notesSpecified:false, objective:"alpha" }) + const range = yield* acquireNativeJournalRange(ctx) + let objective, visits=0 + const result = yield* Effect.promise(() => range.readOrdered(missionID, batch => { + visits += batch.length + objective = batch[0].objective + }, () => true, input.digest)) + if (input.save) yield* Effect.promise(() => range.saveDisplay(missionID, result.digest, '{"fixture":true}')) + const display = yield* Effect.promise(() => range.readDisplay(missionID, () => id)) + return { ...result, key, visits, ...(objective === undefined ? {} : { objective }), + ...(display ? { source: display.event?.objective, display: display.value } : {}) } + }) }).pipe(Effect.asVoid) +} }) +` }, outfile: plugin }) + await writeFile(join(directory, "package.json"), '{"type":"module","exports":{"./server":"./server.mjs"}}\n') + return { plugins: [pathToFileURL(directory).href] } +}, async ({ client, root, env }) => { + const location = { directory: root } + const deadline = Date.now() + 15_000 + while (!(await client.plugin.list({ location })).data.some(entry => entry.id === "codenomad.missions" && entry.state.status === "active")) { + assert.ok(Date.now() < deadline, "Private journal qualification plugin unavailable") + await delay(100) + } + const read = input => client.rpc(rpc).read(input, { location }) + const first = await read({ seed: true, save: true }) + assert.equal(first.objective, "alpha") + assert.match(first.digest, /\//, "native database must qualify the indexed path") + assert.equal(first.display, '{"fixture":true}') + assert.equal(first.source, "alpha") + assert.equal((await read({ digest: first.digest })).visits, 0) + const db = new DatabaseSync(env.OPENCODE_DB) + try { + const key = `plugin:${Buffer.from("codenomad.missions", "utf16le").swap16().toString("hex")}:${first.key}` + assert.equal(db.prepare("UPDATE kv SET value=replace(value,'alpha','bravo') WHERE key=?").run(key).changes, 1) + } finally { db.close() } + const second = await read({ digest: first.digest }) + assert.notEqual(second.digest, first.digest) + assert.equal(second.objective, "bravo") + assert.equal(second.display, undefined, "external edits invalidate the persisted projection") + console.log("Native transaction index observed a same-size external rewrite") +}) diff --git a/scripts/test-mission-schedule-activation-native.mjs b/scripts/test-mission-schedule-activation-native.mjs deleted file mode 100644 index 96981e559c..0000000000 --- a/scripts/test-mission-schedule-activation-native.mjs +++ /dev/null @@ -1,121 +0,0 @@ -// Production HTTP preparation + production native RPC/CAS, private service only. -import assert from "node:assert/strict" -import path from "node:path" -import { mkdir, readFile, writeFile } from "node:fs/promises" -import { DatabaseSync } from "node:sqlite" -import { setTimeout as delay } from "node:timers/promises" -import Fastify from "fastify" -import pino from "pino" -import { withProductRuntime } from "./native-product-fixture.mjs" -import { WorkspaceManager } from "../packages/server/src/workspaces/manager.ts" -import { EventBus } from "../packages/server/src/events/bus.ts" -import { rememberRuntime } from "../packages/server/src/opencode/compatibility/runtime.ts" -import { DesktopPluginLifecycle } from "../packages/server/src/opencode/desktop-plugin-lifecycle.ts" -import { resolveDesktopPluginPaths } from "../packages/server/src/opencode/desktop-plugin-paths.ts" -import { PluginControls } from "../packages/server/src/opencode/plugin-controls.ts" -import { NativeScheduleSettingsActivation } from "../packages/server/src/opencode/native-schedule-settings-activation.ts" -import { registerMissionRoutes } from "../packages/server/src/server/routes/missions.ts" -import { WorktreeDeletionFence } from "../packages/server/src/workspaces/worktree-session-evacuation.ts" -import { NativeMissionDocumentStore } from "../packages/server/src/missions/mission-document-store.ts" - -const scratch = process.argv[3] -assert.ok(scratch && path.isAbsolute(scratch), "Pass the approved activation scratch") -await mkdir(scratch, { recursive: true }) -Object.assign(process.env, { TEMP: scratch, TMP: scratch, LOCALAPPDATA: scratch, APPDATA: scratch }) -await withProductRuntime(process.argv[2], async ({ root, configDirectory }) => { - for (const key of ["HOME", "USERPROFILE", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME", "XDG_DATA_HOME"]) process.env[key] = root - await writeFile(path.join(configDirectory, "opencode.jsonc"), '{"experimental":{"subagent_depth":2},"fixturePrivate":"DO-NOT-PERSIST"}\n') - await mkdir(path.join(root, ".opencode")) - await writeFile(path.join(root, ".opencode", "opencode.jsonc"), '{"experimental":{"subagent_depth":8}}\n') - return { update: "disable", snapshots: false, permissions: [{ action: "*", resource: "*", effect: "allow" }] } -}, async ({ client, root, requests, connection }) => { - const info = await client.server.info() - assert.equal(info.version, "2.3.0") - rememberRuntime(connection.endpoint, { version: info.version, pid: info.pid, discovery: "info" }) - const manager = new WorkspaceManager({ rootDir: root, logger: pino({ level: "silent" }), eventBus: new EventBus(), - settings: { getOwner: () => ({ environmentVariables: {} }), readEnvironmentForAdmission: async () => ({}) }, - binaryResolver: { resolveDefault: () => ({ path: process.argv[2], label: "Private activation fixture" }) }, - hostServiceLifecycleFactory: () => ({ discover: async () => connection.endpoint, ensure: async () => connection.endpoint }), - }) - const app = Fastify(), plugin = new DesktopPluginLifecycle("missions"), receipt = { runtime: info.version, root, status: "running" } - try { - const { workspace } = await manager.create(root), current = await manager.getSharedServiceConnection(workspace.id) - const paths = await resolveDesktopPluginPaths(current, { kind: "host", platform: process.platform, binary: process.argv[2] }) - assert.ok(paths.config.startsWith(root)) - await plugin.start(paths) - const location = manager.getServiceLocation(workspace.id), placed = await client.location.get({ location }) - const end = Date.now() + 30_000 - while (!(await client.plugin.list({ location })).data.some(entry => entry.id === "codenomad.missions" && entry.state.status === "active")) { - if (Date.now() > end) throw Error("Private Missions plugin unavailable") - await delay(100) - } - // Controlled bootstrap of a paused scheduled document, using the domain codec. - // Scheduled creation/arming is CORE; every phase after this seed uses the real RPC. - const db = new DatabaseSync(path.join(root, "fixture.db")) - const nativeKey = key => `plugin:${Array.from("codenomad.missions").map(char => char.charCodeAt(0).toString(16).padStart(4, "0")).join("")}:${key}` - try { - const documents = new NativeMissionDocumentStore({ - get: async key => { const row = db.prepare("SELECT value FROM kv WHERE key=?").get(nativeKey(key)); return row && JSON.parse(row.value) }, - compareAndSet: async (key, value, expected, guard) => { - db.exec("BEGIN IMMEDIATE") - try { - guard(); const prior = db.prepare("SELECT value FROM kv WHERE key=?").get(nativeKey(key)) - assert.equal(prior ? JSON.parse(prior.value).revision : null, expected) - db.prepare("INSERT INTO kv(key,value,time_created,time_updated) VALUES(?,?,?,?)").run(nativeKey(key), JSON.stringify(value), Date.now(), Date.now()) - db.exec("COMMIT") - } catch (error) { db.exec("ROLLBACK"); throw error } - }, - }, placed.project.id, placed.project.canonical) - const selected = { agent: "build", model: { providerID: "fixture", id: "fixture" } } - await documents.create("msn_activation_native", { title: "Prepared schedule", objective: "Fixture preparation only", template: "custom", - taskMode: "native", profileID: "fixture-profile", executionHost: "host", roots: [{ mode: "directory-only", directory: placed.directory }], - profiles: { coordinator: selected, roles: { specialist: selected } }, watchedConversationIDs: [], - launch: { timing: { kind: "every", intervalMs: 900_000 }, condition: null, ends: { at: null, afterMs: null, maxLaunches: null } }, - }, Date.now(), () => true) - } finally { db.close() } - const fence = new WorktreeDeletionFence(), controls = new PluginControls({ workspaceManager: manager, worktreeDeletionFence: fence, logger: pino({ level: "silent" }) }) - const executor = new NativeScheduleSettingsActivation(controls, manager) - let lose = true - registerMissionRoutes(app, { workspaceManager: manager, worktreeDeletionFence: fence, scheduleSettingsActivation: { - prepare: (...args) => executor.prepare(...args), verify: (...args) => executor.verify(...args), - apply: (id, loc, intent, journal) => executor.apply(id, loc, intent, { - ...journal, acknowledged: async (scope, digest) => { - await journal.acknowledged(scope, digest) - if (scope === "project" && lose) { lose = false; throw Error("lost native activation reply") } - }, - }), - } }) - const url = `/api/workspaces/${workspace.id}/missions/msn_activation_native/schedule-settings` - const payload = { requestID: "activate-original", expectedDocumentRevision: 0 } - const globalFile = path.join(paths.config, "opencode.jsonc") - const globalBefore = await readFile(globalFile, "utf8") - const first = await app.inject({ method: "POST", url, payload }) - assert.equal(first.statusCode, 503, first.body) - const read = await app.inject({ method: "GET", url: `${url}?requestID=activate-original&expectedDocumentRevision=0` }) - assert.equal(read.statusCode, 200, read.body) - receipt.partial = read.json().document - assert.equal(receipt.partial.state, "paused"); assert.equal(receipt.partial.scheduleActivation.state, "failed") - assert.equal(receipt.partial.scheduleActivation.targets[0].acknowledged, true) - assert.equal(receipt.partial.scheduleActivation.targets.length, 1) - assert.equal(receipt.partial.scheduleActivation.targets[0].scope, "project") - const retry = await app.inject({ method: "POST", url, payload }) - assert.equal(retry.statusCode, 200, retry.body) - receipt.ready = retry.json().document - assert.equal(receipt.ready.state, "paused"); assert.equal(receipt.ready.firstPlayedAt, null); assert.equal(receipt.ready.launchedCount, 0) - assert.equal(receipt.ready.scheduleActivation.state, "ready") - const repeated = await app.inject({ method: "POST", url, payload }) - assert.equal(repeated.statusCode, 200, repeated.body) - assert.equal(repeated.json().document.revision, receipt.ready.revision) - const fresh = await app.inject({ method: "POST", url, payload: { requestID: "fresh-after-ready", - expectedDocumentRevision: receipt.ready.revision } }) - assert.equal(fresh.statusCode, 200, fresh.body) - assert.deepEqual(fresh.json().document, receipt.ready) - assert.equal(await readFile(globalFile, "utf8"), globalBefore) - assert.equal(requests.length, 0) - assert.ok(!JSON.stringify(receipt).includes("DO-NOT-PERSIST")) - receipt.status = "passed" - console.log("PASS native 2.3.0 production HTTP + document RPC/CAS: project-only effect, unchanged global config, lost reply observation, native Flag readiness, retained ready proof, paused throughout, zero model HTTP") - } catch (error) { receipt.status = "failed"; receipt.error = error.message; throw error } - finally { await plugin.stop(); await app.close(); await manager.shutdown() - await writeFile(path.join(root, "schedule-activation-receipt.json"), JSON.stringify(receipt, null, 2)) } -}, { projectConfig: true }) diff --git a/scripts/test-missions-activation-native.mjs b/scripts/test-missions-activation-native.mjs new file mode 100644 index 0000000000..3c2d13b85e --- /dev/null +++ b/scripts/test-missions-activation-native.mjs @@ -0,0 +1,78 @@ +// Run against the installed CLI in an isolated foreground server, never the shared service. +import assert from "node:assert/strict" +import { mkdir, readFile, writeFile } from "node:fs/promises" +import path from "node:path" +import { setTimeout as delay } from "node:timers/promises" +import { fileURLToPath } from "node:url" +import { parse } from "jsonc-parser" +import { PluginControls } from "../packages/server/src/opencode/plugin-controls.ts" +import { installDesktopPluginPresence } from "../packages/server/src/opencode/desktop-plugin-installation.ts" +import { withProductRuntime } from "./native-product-fixture.mjs" + +const pluginId = "codenomad.missions" +const directoryOf = file => fileURLToPath(new URL(`../packages/server/dist/plugins/missions/${file}`, import.meta.url)) +const original = '{\n // unrelated user settings\n "username": "fixture"\n}\n' +let config, dispose +try { + await withProductRuntime(process.argv[2], async ({ root, configDirectory }) => { + config = path.join(configDirectory, "opencode.jsonc") + await writeFile(config, original) + dispose = await installDesktopPluginPresence("missions", await readFile(directoryOf("plugin.mjs")), + { config: configDirectory, data: path.join(root, "presence") }) + return {} + }, async ({ client, root, connection, requests }) => { + const directory = path.join(root, "project") + const otherDirectory = path.join(root, "other-project") + await mkdir(directory) + await mkdir(otherDirectory) + const location = { directory } + const controls = new PluginControls({ workspaceManager: { + get: () => ({}), getSharedServiceConnection: async () => connection, + getServiceDirectoryForPath: async (_id, value) => value === directory ? directory : undefined, + ownsLocation: async (_id, candidate) => candidate.directory === directory, + getWorktreeIdentityForPath: async () => "fixture-root", getServicePathStyle: () => process.platform === "win32" ? "win32" : "posix", + getServiceWslDistro: () => undefined, getHostPathForServicePath: async (_id, value) => value, + }, worktreeDeletionFence: { enter: () => () => {} }, logger: { info() {} } }) + const { id: sessionID } = await client.session.create({ location }) + const until = async (check, label) => { + const deadline = Date.now() + 15_000 + while (Date.now() < deadline) { + const result = await check() + if (result) return result + await delay(100) + } + assert.fail(label) + } + const checkTools = async (text, enabled) => { + const cursor = requests.length + await client.session.prompt({ sessionID, text }) + const request = await until(() => requests.slice(cursor) + .find(request => request.tools?.length && request.messages?.some(message => message.role === "user" && JSON.stringify(message.content).includes(text))), + `Existing session did not reach the test provider: ${text}`) + assert.equal(request.tools?.some(tool => tool.function?.name?.startsWith("mission_")) ?? false, enabled, text) + } + const settle = enabled => until(async () => { + const [snapshot, other] = await Promise.all([controls.read("fixture", location), client.plugin.list({ location: { directory: otherDirectory } })]) + const control = snapshot.controls.find(item => item.id === pluginId) + const otherPlugin = other.data.find(item => item.id === pluginId) + return control?.managedBy === "codenomad" && (control.effective !== "disabled") === enabled + && (enabled ? control.runtime?.state.status === "active" && otherPlugin?.state.status === "active" + : !control.runtime && !otherPlugin) + }, `Native Missions activation did not settle to ${enabled}`) + const activate = enabled => controls.mutate("fixture", { location, pluginId, scope: "global", enabled, managedBy: "codenomad" }) + await settle(true) + await checkTools("Missions enabled, before disable", true) + assert.equal((await activate(false)).reloadPending, true) + assert.match(await readFile(config, "utf8"), /"-codenomad\.missions"/) + await settle(false) + await checkTools("Missions disabled in the same session", false) + assert.equal((await activate(true)).reloadPending, true) + await settle(true) + await checkTools("Missions enabled again in the same session", true) + const updated = await readFile(config, "utf8") + assert.deepEqual(parse(updated).plugins, [pluginId]) + assert.match(updated, /\/\/ unrelated user settings/) + assert.match(updated, /"username": "fixture"/) + console.log("PASS: native hot disable/re-enable removes/restores Mission tools in an existing session") + }) +} finally { await dispose?.() } diff --git a/scripts/test-missions-native-contract.mjs b/scripts/test-missions-native-contract.mjs index e124e395b3..e8418478c4 100644 --- a/scripts/test-missions-native-contract.mjs +++ b/scripts/test-missions-native-contract.mjs @@ -136,28 +136,27 @@ try { const offered = requests.find(request => request.tools.some(name => /^mission[._]/.test(name)))?.tools.filter(name => /^mission[._]/.test(name)) receipt.offeredTools = offered assert.deepEqual(offered?.map(name => name.replace(/^mission[._]/, "")).sort(), - ["briefing", "configure", "control", "delegate", "delete", "inspect", "interrupt", "prepare", "report", "revise", "schedule", "settings"]) + ["briefing", "configure", "control", "delegate", "delete", "inspect", "interrupt", "prepare", "program", "report", "revise", "settings"]) const started = await missions.snapshot({}, { location }) assert.equal(started.missions.length, 1, "The native tool call recorded exactly one mission") assert.equal(started.missions[0].coordinatorSessionId, coordinator.id) assert.equal(started.missions[0].objective, "Minimum contract qualification") gate("tool transform, context hook and mission inspect execute through the native model loop") - // Recurrence RPC is registered without presence and qualifies the private - // native graph on demand. Both minimum and latest must support this contract; - // do not let authentication, storage or plugin failures masquerade as support. - stage = "recurrence capability qualification" + // The schedules the recurring engine left are read from the plugin's own storage. Both minimum and latest + // must support this reading; do not let authentication, storage or plugin failures masquerade as support. + stage = "stored schedule reading" const sessionsBefore = (await client.session.list({ location, limit: 64 })).data.map(value => value.id).sort() - const recurrence = await settle(missions.recurrenceSnapshot({}, { location })) - receipt.recurrence = recurrence.ok ? { supported: true, schedules: recurrence.value.schedules?.length } - : { supported: false, error: { type: recurrence.error?.type, message: recurrence.error?.message } } - assert(recurrence.ok, `Recurrence contract unavailable: ${recurrence.error?.type ?? ""}: ${recurrence.error?.message ?? ""}`) - assert.deepEqual(recurrence.value.schedules, [], "A fresh isolated store has no schedules") + const stored = await settle(missions.legacySchedules({}, { location })) + receipt.storedSchedules = stored.ok ? { supported: true, schedules: stored.value.schedules?.length } + : { supported: false, error: { type: stored.error?.type, message: stored.error?.message } } + assert(stored.ok, `Stored schedule reading unavailable: ${stored.error?.type ?? ""}: ${stored.error?.message ?? ""}`) + assert.deepEqual(stored.value.schedules, [], "A fresh isolated store has no schedules") assert.deepEqual((await client.session.list({ location, limit: 64 })).data.map(value => value.id).sort(), sessionsBefore, - "Recurrence qualification creates no native sessions") + "Reading stored schedules creates no native sessions") assert.deepEqual((await missions.snapshot({}, { location })).missions, started.missions, - "Recurrence qualification leaves the one-time journal unchanged") - gate("native recurrence graph available with an empty isolated schedule store") + "Reading stored schedules leaves the one-time journal unchanged") + gate("stored schedules read from an empty isolated store") receipt.status = "passed" console.log(`PASS ${version}: Missions plugin native contract (${receipt.gates.length} gates); ${root}`) } catch (error) { diff --git a/scripts/test-missions-native-trajectory.mjs b/scripts/test-missions-native-trajectory.mjs index f30f1f22d8..42d7369d71 100644 --- a/scripts/test-missions-native-trajectory.mjs +++ b/scripts/test-missions-native-trajectory.mjs @@ -68,7 +68,7 @@ const provider = createServer(async (request, response) => { const child = result(id)?.match(/working in the background \(sessionID: (ses_[A-Za-z0-9]+)\)/)?.[1] if (!child) return undefined const reports = body.messages.map(message => typeof message.content === "string" ? message.content : (message.content ?? []).map(part => part.text ?? "").join("")) - .flatMap(value => [...value.matchAll(/]*>\n([\s\S]*?)\n<\/subagent>/g)]) + .flatMap(value => [...value.matchAll(/<(subagent|background-result) (?:kind="subagent" )?sessionID="(ses_[A-Za-z0-9]+)" state="(\w+)"[^>]*>\n([\s\S]*?)\n<\/\1>/g)].map(match => [match[0], ...match.slice(2)])) .filter(match => match[1] === child) // A report tagged running is intermediate: the child still owns background work. const final = reports.findLast(match => match[2] !== "running") diff --git a/scripts/test-missions-native.mjs b/scripts/test-missions-native.mjs index bade75ab63..9ecc56bf68 100644 --- a/scripts/test-missions-native.mjs +++ b/scripts/test-missions-native.mjs @@ -296,20 +296,17 @@ try { const preferred = { template: "all", profiles, taskMode: "independent" } uiPreferences = { settings: { missionProfileDefaults: [{ ...preferred, profiles: { ...profiles, coordinator: { agent: "reviewer" } } }] } } const before = await client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, { location }) - const { DatabaseSync } = await import("node:sqlite") - const database = new DatabaseSync(process.env.OPENCODE_DB, { readOnly: true }) - try { - database.exec("PRAGMA busy_timeout = 10000") - const rows = () => database.prepare("SELECT key, value FROM kv WHERE key LIKE ? ORDER BY key").all("%codenomad-missions/%") - const retained = rows(), reads = preferenceReads, turns = requests.length - await assert.rejects(invoke("inspect", { start: { objective: "Refuse coordinator mismatch", template: "custom" } }, - caller.id, "preferences-mismatch"), /Coordinator differs from the profile selected by Missions preferences\. Pass profiles\.coordinator \(for example \{\}\) to override that preference\./) + let adopted + { + // A conversation on another agent than the preferred coordinator takes that agent and coordinates. + const other = await client.session.create({ location, title: "Private preference adoption", agent: "build", + model: { providerID: "fixture", id: "fixture" } }) + const reads = preferenceReads + adopted = await invoke("inspect", { start: { objective: "Adopt the preferred coordinator", template: "custom" } }, other.id, "preferences-mismatch") assert.ok(preferenceReads > reads, "The mismatch was resolved against nonempty owner preferences") - const after = await client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, { location }) - assert.deepEqual({ ...after, generatedAt: before.generatedAt }, before) - assert.deepEqual(rows(), retained, "Coordinator mismatch writes no creation event, document or retained intent") - assert.equal(requests.length, turns, "Coordinator mismatch admits no provider turn") - } finally { database.close() } + assert.equal(adopted.selection.profiles.coordinator.agent, "reviewer") + assert.equal((await client.session.get({ sessionID: other.id })).agent, "reviewer", "The conversation takes the coordinator's agent") + } uiPreferences = { settings: { missionProfileDefaults: [preferred] } } const start = { objective: "Persist owning-backend preferences", template: "custom" } const selected = await invoke("inspect", { start }, caller.id, "preferences-create") @@ -348,12 +345,12 @@ try { const finished = await invoke("report", { missionID: selected.mission.id, outcome: "completed", summary: "Preferences verified", final: true }, caller.id, "preferences-finish") assert.equal(finished.mission.status, "completed") - for (const mission of [prepared.mission, finished.mission]) { + for (const mission of [adopted.mission, prepared.mission, finished.mission]) { const deletion = { missionID: mission.id, requestID: `preferences-delete-${mission.id}`, expectedRevision: mission.revision } assertDocumentDeletion(await client.rpc(CODENOMAD_MISSIONS_RPC).delete(deletion, { location }), deletion, mission.objective) } assert.equal((await client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, { location })).missions.length, before.missions.length) - gate("nonempty owner preferences: coordinator mismatch has no effects, both creation paths persist profiles/policy/provenance and replay frozen choices") + gate("nonempty owner preferences: a conversation on another agent takes the coordinator's, both creation paths persist profiles/policy/provenance and replay frozen choices") } const inspected = await invoke("inspect", { catalog: true, start: { objective: "Native integration", template: "custom" } }) assert.equal(inspected.selection.preferences, undefined, "The owning fixture backend supplied readable preferences") @@ -490,8 +487,8 @@ try { assert((await client.session.get({ sessionID: actorID })).id === actorID, "Revision keeps the original actor conversation") gate("revision lineage, withdrawn late evidence and busy coordinator report consumption") - // A durable report must wake its coordinator after transport recovery, without - // another report call or human prompt. Exercise both live recovery and reload. + // Without a CodeNomad bridge the plugin delivers a report through its own session API. It must wake its + // coordinator once, whatever returns afterwards: the bridge, or the plugin after a reload. for (const restart of [false, true]) { stage = `report outbox recovery (restart=${restart})` const taskKey = restart ? "outbox-restart" : "outbox-live" @@ -501,16 +498,16 @@ try { await removeBridge(); removeBridge = undefined const savedReport = await invoke("report", { taskKey, outcome: "completed", summary }, actorID) assert.equal(savedReport.disposition, "reported", "A missing bridge does not negate a saved durable report") - assert.equal(savedReport.mission.reports.find(report => report.taskKey === taskKey)?.notificationStatus, "pending") - const pending = (await client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, { location })).missions[0] - assert.equal(pending.tasks.find(task => task.key === taskKey).report.summary, summary) - assert.equal(pending.tasks.find(task => task.key === taskKey).report.notificationStatus, "pending") - assert(!requests.some(request => request.session === coordinator.id && request.messages.includes(summary))) + assert.equal(savedReport.mission.reports.find(report => report.taskKey === taskKey)?.notificationStatus, "admitted") + const delivered = (await client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, { location })).missions[0] + assert.equal(delivered.tasks.find(task => task.key === taskKey).report.summary, summary) + assert.equal(delivered.tasks.find(task => task.key === taskKey).report.notificationStatus, "admitted") + await until(() => requests.some(request => request.session === coordinator.id && request.messages.includes(summary))) if (restart) { await plugin.stop() assert.equal((await client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, { location })).missions[0] - .reports.find(report => report.taskKey === taskKey)?.notificationStatus, "pending", - "Presence loss retains active Mission executors and the pending report") + .reports.find(report => report.taskKey === taskKey)?.notificationStatus, "admitted", + "Presence loss retains active Mission executors and the delivered report") // Presence loss deliberately retains active work now. Explicitly reload // only this owned private daemon to exercise real executor teardown and // re-registration; never discover or reload the shared user service. @@ -520,8 +517,9 @@ try { removeBridge = await publishAutomationBridge(registration) if (restart) { plugin = new DesktopPluginLifecycle("missions"); await plugin.start(paths) } await until(() => requests.some(request => request.session === coordinator.id && request.messages.includes(summary))) - await until(async () => (await client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, { location })).missions[0] - .reports.find(report => report.taskKey === taskKey)?.notificationStatus === "admitted") + // After a reload Missions registers again with the returning plugin: until then its RPC is unavailable. + await until(() => client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, { location }).then(snapshot => snapshot.missions[0] + .reports.find(report => report.taskKey === taskKey)?.notificationStatus === "admitted", () => false)) await client.session.wait({ sessionID: coordinator.id }, { signal: AbortSignal.timeout(20_000) }) const count = requests.filter(request => request.session === coordinator.id).length assert.equal((await invoke("report", { taskKey, outcome: "completed", summary }, actorID)).disposition, "existing") @@ -992,9 +990,7 @@ try { assert.equal(finished.mission.status, "completed") history.push(finished.mission) } - // The journal bound is per mission: the finished missions' own ranges, seeded in - // the isolated KV table as an earlier activation left them, take the project past - // one mission's 2,000-entry bound while each mission stays far below it. + // Include one long range alongside short ranges in this fixture's private database. const { DatabaseSync } = await import("node:sqlite") const namespace = `plugin:${Array.from("codenomad.missions").map(c => c.charCodeAt(0).toString(16).padStart(4, "0")).join("")}:` const journalEntries = (database, range) => database.prepare("SELECT COUNT(*) AS count FROM kv WHERE substr(key, 1, ?) = ?").get(range.length, range).count @@ -1011,14 +1007,15 @@ try { // One transaction: thousands of autocommits would idle the client's keep-alive connection past the daemon's timeout. seeding.exec("BEGIN IMMEDIATE") for (const mission of history) { - for (let index = 0; index < 22; index++) { - const id = `evt_seeded_${String(index).padStart(2, "0")}` + const extra = mission.id === history[0].id ? 10_020 : 22 + for (let index = 0; index < extra; index++) { + const id = `evt_seeded_${String(index).padStart(5, "0")}` insert.run(`${journalRange}${mission.id}/${id}`, JSON.stringify({ version: 1, id, type: "mission.updated", missionID: mission.id, projectID: mission.projectID, createdAt: mission.createdAt + 1 + index, requestID: `seeded-${index}`, expectedRevision: 1, notesSpecified: false, objective: `Seeded ${index}` }), Date.now(), Date.now()) } } seeding.exec("COMMIT") - assert.ok(journalEntries(seeding, journalRange) > 2_000, "The project holds more than one mission's bound") + assert.ok(journalEntries(seeding, `${journalRange}${history[0].id}/`) > 10_000, "One native mission exceeds 10,000 events") } finally { seeding.close() Object.assign(reloadDiagnostics.seed, { finishedAt: new Date().toISOString(), durationMs: performance.now() - seedStarted }) @@ -1038,7 +1035,8 @@ try { assert.equal((await invoke("report", { missionID: live.id, taskKey: liveTask.taskKey, outcome: "completed", summary: "History unaffected" }, liveCoordinator, "history-readout")).disposition, "reported") const beforeDelete = await client.rpc(CODENOMAD_MISSIONS_RPC).snapshot({}, { location }) - assert.equal(beforeDelete.missions.find(mission => mission.id === history[0].id).revision, history[0].revision + 22, "Seeded entries read as the mission's own events") + assert.equal(beforeDelete.missions.find(mission => mission.id === history[0].id).revision, history[0].revision + 10_020, + "The real plugin reloads one long range and admits work on its neighbour") // The deletion's retention purge pushes the oldest settled deletion past the history, through native storage.remove. const settled = beforeDelete.cleanups.filter(item => item.pending === 0) assert.equal(settled.length, 20) diff --git a/scripts/test-native-current-pages.mjs b/scripts/test-native-current-pages.mjs deleted file mode 100644 index 70e1955422..0000000000 --- a/scripts/test-native-current-pages.mjs +++ /dev/null @@ -1,67 +0,0 @@ -// Explicit isolated CLI only; deterministic storage seeds, no provider/model calls. -import assert from "node:assert/strict" -import path from "node:path" -import { fileURLToPath } from "node:url" -import { writeFile } from "node:fs/promises" -import { build } from "esbuild" -import { withProductRuntime } from "./native-product-fixture.mjs" -import { nativePluginBuild } from "../packages/server/scripts/native-plugin-build.mjs" -import { tsImport } from "tsx/esm/api" - -const [cli] = process.argv.slice(2), method = { input: { type: "object" }, output: { type: "object" } } -const definition = { id: "codenomad.current-display-qualification", methods: { seed: method }, events: {} } -const { CODENOMAD_MISSIONS_RPC } = await tsImport("../packages/server/src/missions/rpc.ts", import.meta.url) -await withProductRuntime(cli, async ({ root }) => { - const directory = path.join(root, "current-display-plugin") - const result = await build({ ...nativePluginBuild, metafile: true, outfile: path.join(directory, "index.mjs"), - entryPoints: [fileURLToPath(new URL("../packages/server/src/opencode/missions/native-current-pages-native-fixture.ts", import.meta.url))] }) - assert(!Object.keys(result.metafile.inputs).some(file => /node_modules[/\\](effect|@opencode[/\\]plugin)[/\\]/.test(file))) - await writeFile(path.join(directory, "package.json"), JSON.stringify({ name: "current-display-qualification", version: "1.0.0", type: "module", exports: { ".": "./index.mjs" } })) - return { plugins: [{ package: directory }] } -}, async ({ client, root, requests }) => { - const version = (await client.server.info()).version - assert.equal(version, "2.2.3") - const rpc = client.rpc(CODENOMAD_MISSIONS_RPC), options = { location: { directory: root }, signal: AbortSignal.timeout(90000) } - const seed = await client.rpc(definition).seed({}, options), receipts = [] - for (const selected of seed.schedules) { - const identity = await rpc.recurrenceCurrent(selected, options) - assert.equal(identity.mission, undefined); assert.equal(identity.source.owner, selected.owner) - assert.ok(Buffer.byteLength(JSON.stringify(identity)) <= 65536) - const read = async (selector, body) => { - let cursor, digest, text = [] - do { - const result = await rpc.recurrenceCurrentPage({ source: identity.source, selector: { ...selector, ...(cursor ? { cursor } : {}) }, ...(body ? { body } : {}) }, options) - assert.equal(result.available, true); assert.deepEqual(result.passage, identity.source) - assert.ok(Buffer.byteLength(JSON.stringify(result)) <= 65536) - digest ??= result.page.digest; assert.equal(result.page.digest, digest) - for (const piece of result.page.pieces) { assert.equal(piece.offset, text[piece.index]?.length ?? 0); text[piece.index] = (text[piece.index] ?? "") + piece.text } - cursor = result.page.next - } while (cursor) - return text.map(value => JSON.parse(value)) - } - const missionID = identity.source.missionID - const [header] = await read({ source: "mission", missionID, header: true }) - assert.equal(header.tasks.page.total, seed.tasks); assert.equal(header.root.tasks, undefined) - const [last] = await read({ source: "tasks", task: { missionID, offset: 50, order: header.tasks.page.order } }) - assert.equal(last.tasks.length, seed.tasks - 50) - const task = last.tasks.at(-1), [body] = await read({ source: "mission", missionID, field: "body", window: { offset: 0 } }, - { missionID, kind: "task", taskKey: task.key, field: "brief", offset: 0 }) - assert.equal(task.key, "wide-body") - assert.equal(body.content.characters, 20000); assert.ok(body.content.text.startsWith("\u0001")); assert.ok(body.content.next > 0) - let text = body.content.text, next = body.content.next - while (next !== undefined) { - const [continued] = await read({ source: "mission", missionID, field: "body", window: { offset: 0 } }, - { missionID, kind: "task", taskKey: task.key, field: "brief", offset: next, digest: body.content.digest }) - text += continued.content.text; next = continued.content.next - } - assert.equal(text, "\u0001".repeat(20000)) - await assert.rejects(rpc.recurrenceCurrentPage({ source: { ...identity.source, digest: "z".repeat(43) }, selector: { source: "mission", missionID, header: true } }, options)) - assert.deepEqual(await rpc.recurrenceCurrent(selected, options), identity, "reads preserve the owner and original passage") - const legacy = await rpc.recurrenceCurrentContent({ ...selected, passageID: identity.passageID, kind: "overview", section: "objective" }, options) - assert.equal(legacy.sourceText, "Exact display"); assert.ok(Buffer.byteLength(JSON.stringify(legacy)) <= 65536) - receipts.push({ owner: selected.owner, identity, headerBytes: Buffer.byteLength(JSON.stringify(header)), tasks: seed.tasks, bodyCharacters: 20000 }) - } - assert.equal(requests.length, 0) - await writeFile(path.join(root, "current-display-receipt.json"), JSON.stringify({ version, receipts, modelRequests: requests.length }, null, 2)) - console.log("PASS: daily and scheduled current native Effect graphs, bounded headers/tasks/bodies, exact continuations, source refusal and zero model requests") -}) diff --git a/scripts/test-native-mission-coordinator-reuse.mjs b/scripts/test-native-mission-coordinator-reuse.mjs deleted file mode 100644 index e36d507584..0000000000 --- a/scripts/test-native-mission-coordinator-reuse.mjs +++ /dev/null @@ -1,104 +0,0 @@ -// node scripts/test-native-mission-coordinator-reuse.mjs -import assert from "node:assert/strict" -import path from "node:path" -import { fileURLToPath } from "node:url" -import { writeFile } from "node:fs/promises" -import { setTimeout as delay } from "node:timers/promises" -import { build } from "esbuild" -import { withProductRuntime } from "./native-product-fixture.mjs" -import { nativePluginBuild } from "../packages/server/scripts/native-plugin-build.mjs" - -const [cli] = process.argv.slice(2), method = { input: { type: "object" }, output: { type: "object" } } -const definition = { id: "codenomad.coordinator-qualification", methods: { begin: method, finish: method, read: method, probe: method, watermark: method, - sameTime: method, backgroundStart: method, backgroundState: method, backgroundRelease: method }, events: {} } -await withProductRuntime(cli, async ({ root }) => { - const directory = path.join(root, "qualification-plugin") - await build({ ...nativePluginBuild, outfile: path.join(directory, "index.mjs"), - entryPoints: [fileURLToPath(new URL("../packages/server/src/opencode/missions/native-scheduled-coordinator-native-fixture.ts", import.meta.url))] }) - await writeFile(path.join(directory, "package.json"), JSON.stringify({ name: "codenomad-reuse-qualification", version: "1.0.0", type: "module", exports: "./index.mjs" })) - return { plugins: [directory], experimental: { subagent_depth: 3 }, permissions: [{ action: "*", resource: "*", effect: "allow" }], - agents: { reuse_coordinator: { mode: "all", description: "Private reuse qualification", prompt: "Reply briefly, use no tools." }, - reuse_worker: { mode: "all", description: "Private inherited worker", prompt: "Reply briefly." } } } -}, async ({ client, root, requests }) => { - const rpc = client.rpc(definition), options = { location: { directory: root }, signal: AbortSignal.timeout(120_000) } - const until = async check => { - for (const end = Date.now() + 30_000; Date.now() < end;) { const value = await check(); if (value) return value; await delay(50) } - throw Error("Private native background deadline") - } - const permissions = [{ action: "shell", resource: "*", effect: "deny" }] - const selected = await client.session.create({ location: { directory: root }, title: "Existing private work", agent: "build", permissions, - metadata: { unrelated: "preserve", "codenomad.mission": { missionID: "other_mission", kind: "coordinator", role: "coordinator", version: 1 } } }) - await client.session.prompt({ sessionID: selected.id, text: "Earlier private work" }) - await client.session.wait({ sessionID: selected.id }, { signal: AbortSignal.timeout(30_000) }) - const historical = await client.session.create({ parentID: selected.id, location: { directory: root }, agent: "build", title: "Historical child" }) - await rpc.backgroundStart({ sessionID: historical.id }, options) - await client.session.prompt({ sessionID: historical.id, text: "Earlier child work" }) - const inherited = await until(async () => { const state = await rpc.backgroundState({ sessionID: historical.id }, options); return state.last?.type === "idle" && state.childID ? state : undefined }) - const old = await client.session.context({ sessionID: selected.id }), firstRequest = { sessionID: selected.id, requestID: "first" } - await assert.rejects(rpc.begin({ ...firstRequest, loseACK: true }, options)) - const attempted = (await rpc.read({}, options)).document - assert.equal(attempted.pending.admissionAttempted, true) - const first = await rpc.begin(firstRequest, options) - assert.equal(first.admission.kind, "admitted"); assert.equal(first.document.launchedCount, 1) - assert.ok(first.document.pending.coordinatorBaseline.find(row => row[0] === historical.id)[3], "idle parent with native background delivery keeps its existing input") - await client.session.wait({ sessionID: selected.id }, { signal: AbortSignal.timeout(30_000) }) - assert.equal((await rpc.probe({}, options)).settled, false, "a pending native background result prevents settlement") - await rpc.backgroundRelease({ failedResume: true }, options) - const failedInherited = await until(async () => { const result = await rpc.probe({}, options); return result.outcome === "failed" ? result : undefined }) - const helper = await client.session.create({ parentID: selected.id, location: { directory: root }, agent: "build", title: "New child" }) - await client.session.prompt({ sessionID: helper.id, text: "First current helper input" }) - await client.session.wait({ sessionID: helper.id }, { signal: AbortSignal.timeout(30_000) }) - const entry = (await client.session.get({ sessionID: helper.id })).metadata["codenomad.passage-input"] - assert.equal(entry.passageID, first.document.pending.id) - await client.session.prompt({ sessionID: helper.id, text: "Later current helper input" }) - await client.session.wait({ sessionID: helper.id }, { signal: AbortSignal.timeout(30_000) }) - assert.deepEqual((await client.session.get({ sessionID: helper.id })).metadata["codenomad.passage-input"], entry) - const completed = await rpc.finish({}, options) - await rpc.backgroundStart({ sessionID: historical.id }, options) - await client.session.prompt({ sessionID: historical.id, text: "Another inherited background task" }) - await until(async () => { const state = await rpc.backgroundState({ sessionID: historical.id }, options); return state.last?.type === "idle" && state.childID ? state : undefined }) - const second = await rpc.begin({ sessionID: selected.id, requestID: "second" }, options) - assert.equal(second.document.pending.coordinatorSessionID, selected.id) - assert.notEqual(second.document.pending.messageID, first.document.pending.messageID) - assert.notEqual(second.document.pending.missionID, first.document.pending.missionID) - await client.session.wait({ sessionID: selected.id }, { signal: AbortSignal.timeout(30_000) }) - await rpc.backgroundRelease({}, options) - const successfulInherited = await until(async () => { const result = await rpc.probe({}, options); return result.outcome === "ended-without-report" ? result : undefined }) - const finished = await rpc.finish({}, options) - assert.equal(finished.document.history.length, 2); assert.equal(finished.document.successfulCount, 2) - assert.equal(completed.snapshot.missions[0].summary, "Native passage 1 delivered") - assert.equal(finished.snapshot.missions[0].summary, "Native passage 2 delivered") - const adopted = await client.session.get({ sessionID: selected.id }), context = await client.session.context({ sessionID: selected.id }) - assert.equal(adopted.title, selected.title); assert.deepEqual(adopted.permissions, selected.permissions) - assert.equal(adopted.metadata.unrelated, "preserve"); assert.equal(adopted.agent, "reuse_coordinator") - assert.deepEqual(adopted.model, { providerID: "fixture", id: "fixture", variant: "default" }) - assert.ok(old.every(message => context.some(item => item.id === message.id))) - for (const receipt of finished.document.history) { - assert.equal(context.filter(item => item.id === receipt.messageID).length, 1) - assert.ok(receipt.settlementProof) - } - assert.equal(requests.length, 13, "two native background cycles, old root work, two passages and helper inputs, without duplicate original turns") - const clock = await rpc.sameTime({ sessionID: historical.id }, options) - assert.equal(clock.first.updated, clock.second.updated, "actual native updates can share a recency timestamp") - assert.ok(clock.second.sequence > clock.first.sequence, "native aggregate sequence advances independently of the clock") - const third = await rpc.begin({ sessionID: selected.id, requestID: "third" }, options) - await client.session.wait({ sessionID: selected.id }, { signal: AbortSignal.timeout(30_000) }) - await client.session.prompt({ sessionID: helper.id, text: "First third-passage input" }) - await client.session.wait({ sessionID: helper.id }, { signal: AbortSignal.timeout(30_000) }) - const thirdEntry = (await client.session.get({ sessionID: helper.id })).metadata["codenomad.passage-input"] - assert.equal(thirdEntry.passageID, third.document.pending.id) - const beforeRevert = await rpc.watermark({ sessionID: helper.id }, options) - await client.session.revert.stage({ sessionID: helper.id, messageID: thirdEntry.messageID, files: false }) - await client.session.revert.commit({ sessionID: helper.id }) - const afterRevert = await rpc.watermark({ sessionID: helper.id }, options) - assert.ok(afterRevert.sequence > beforeRevert.sequence, "retention/reset preserves the native aggregate watermark") - await client.session.prompt({ sessionID: helper.id, text: "Later input after native revert" }) - await client.session.wait({ sessionID: helper.id }, { signal: AbortSignal.timeout(30_000) }) - assert.deepEqual((await client.session.get({ sessionID: helper.id })).metadata["codenomad.passage-input"], thirdEntry) - assert.equal((await rpc.probe({}, options)).settled, false, "a later native input cannot replace a pruned first owned input") - assert.equal((await rpc.read({}, options)).document.pending.id, third.document.pending.id) - await writeFile(path.join(root, "coordinator-reuse-receipt.json"), JSON.stringify({ version: (await client.server.info()).version, - selected, attempted, first, completed, second, finished, adopted, context, clock, third, beforeRevert, afterRevert, - inherited, failedInherited, successfulInherited }, null, 2)) - console.log("PASS: native adoption, inherited background success/failure, preserved work, isolated passages, lost ACK, child entries, fixed clock and prune/reset uncertainty") -}, { service: true }) diff --git a/scripts/test-native-mission-preparation.mjs b/scripts/test-native-mission-preparation.mjs deleted file mode 100644 index 195c8c0079..0000000000 --- a/scripts/test-native-mission-preparation.mjs +++ /dev/null @@ -1,80 +0,0 @@ -// node scripts/test-native-mission-preparation.mjs -import assert from "node:assert/strict" -import path from "node:path" -import { fileURLToPath } from "node:url" -import { writeFile } from "node:fs/promises" -import { build } from "esbuild" -import { withProductRuntime } from "./native-product-fixture.mjs" -import { nativePluginBuild } from "../packages/server/scripts/native-plugin-build.mjs" -const [cli] = process.argv.slice(2) -const method = { input: { type: "object" }, output: { type: "object" } } -const definition = { id: "codenomad.preparation-qualification", methods: { create: method, configure: method, read: method, play: method }, events: {} } -await withProductRuntime(cli, async ({ root }) => { - const directory = path.join(root, "qualification-plugin") - await build({ ...nativePluginBuild, outfile: path.join(directory, "index.mjs"), - entryPoints: [fileURLToPath(new URL("../packages/server/src/opencode/missions/native-mission-preparation-native-fixture.ts", import.meta.url))] }) - await writeFile(path.join(directory, "package.json"), JSON.stringify({ name: "codenomad-preparation-qualification", version: "1.0.0", type: "module", exports: { ".": "./index.mjs" } })) - return { plugins: [directory], agents: { preparation_coordinator: { mode: "all", description: "Private preparation qualification", prompt: "Reply briefly, use no tools." } } } -}, async ({ client, root, requests }) => { - const info = await client.server.info(); assert.equal(info.version, "2.2.3") - const rpc = client.rpc(definition), options = { location: { directory: root }, signal: AbortSignal.timeout(30000) } - const created = (await rpc.create({ requestID: "private_creation" }, options)).mission - const original = await rpc.read({ missionID: created.id }, options), binding = original.document.oneTime - const configuration = { ...original.document.configuration, title: "Edited private preparation", objective: "Edited private instructions", - template: "delivery", taskMode: "independent", profiles: { coordinator: { agent: "preparation_coordinator", model: { providerID: "fixture", id: "fixture", variant: "default" } }, - roles: { developer: { agent: "build", model: { providerID: "fixture", id: "fixture" } } } } } - const input = { missionID: created.id, requestID: "private_edit", expectedRevision: original.document.revision, configuration } - await assert.rejects(rpc.configure({ ...input, loseNativeACK: true }, options)) - const partial = await rpc.read({ missionID: created.id }, options) - assert.equal(partial.document.preparation.pending, true) - assert.equal(partial.document.preparation.attempted, true) - const replacement = partial.document.preparation.coordinatorSessionID - const native = await client.session.get({ sessionID: replacement }) - assert.equal(native.agent, "preparation_coordinator"); assert.deepEqual(native.model, configuration.profiles.coordinator.model) - assert.equal(requests.length, 0, "Create and edit never request a model") - const edited = (await rpc.configure(input, options)).document - assert.equal(edited.preparation.pending, false); assert.equal(edited.oneTime.coordinatorSessionID, replacement) - assert.deepEqual({ ...edited.oneTime, coordinatorSessionID: binding.coordinatorSessionID }, binding) - assert.deepEqual((await rpc.configure(input, options)).document, edited, "lost response replay remains exactly idempotent") - let snapshot = (await rpc.read({ missionID: created.id }, options)).snapshot - assert.equal(snapshot.missions.length, 1); assert.equal(snapshot.missions[0].coordinatorSessionId, replacement) - const followed = await client.session.create({ title: "Private followed context", location: { directory: root }, agent: "preparation_coordinator" }) - await client.session.prompt({ sessionID: followed.id, text: "Frozen private followed context at Play" }) - await client.session.wait({ sessionID: followed.id }, { signal: AbortSignal.timeout(30000) }) - const sourceRequests = requests.length - const scheduled = (await rpc.configure({ missionID: created.id, requestID: "private_scheduled", expectedRevision: edited.revision, - configuration: { ...configuration, profileID: "fixture", executionHost: "fixture", watchedConversationIDs: [followed.id], - template: "custom", profiles: { coordinator: configuration.profiles.coordinator, roles: { specialist: configuration.profiles.coordinator } }, - launch: { ...configuration.launch, timing: { kind: "every", intervalMs: 900000 } } } }, options)).document - const immediate = (await rpc.configure({ missionID: created.id, requestID: "private_immediate", expectedRevision: scheduled.revision, - configuration: { ...configuration, watchedConversationIDs: [followed.id] } }, options)).document - assert.equal(immediate.id, created.id); assert.equal(immediate.firstPlayedAt, null) - assert.equal(requests.length, sourceRequests, "source selection and conversion never request a model") - snapshot = (await rpc.read({ missionID: created.id }, options)).snapshot - const playInput = { missionID: created.id, requestID: "private_play", expectedRevision: snapshot.missions[0].revision } - await assert.rejects(rpc.play({ ...playInput, loseAdmissionACK: true }, options)) - const lostAdmission = (await rpc.read({ missionID: created.id }, options)).document - assert.equal(lostAdmission.oneTime.firstPlay.admittedAt, null) - const originalFrozen = lostAdmission.oneTime.firstPlay.inputText - await client.session.prompt({ sessionID: followed.id, text: "New source text after lost first-Play ACK" }) - await client.session.wait({ sessionID: followed.id }, { signal: AbortSignal.timeout(30000) }) - const played = (await rpc.play(playInput, options)).mission - const playedCoordinator = immediate.oneTime.coordinatorSessionID - assert.equal(played.document.launchedCount, 1); assert.equal(played.coordinatorSessionId, playedCoordinator) - const frozen = (await rpc.read({ missionID: created.id }, options)).document.oneTime.firstPlay.inputText - assert.equal(frozen, originalFrozen); assert.doesNotMatch(frozen, /New source text after/) - assert.match(frozen, /Frozen private followed context at Play/) - assert.match(frozen, /untrusted source data/) - await rpc.play({ missionID: created.id, requestID: "private_play", expectedRevision: snapshot.missions[0].revision }, options) - const admission = await client.session.inbox.list({ sessionID: playedCoordinator }) - const context = await client.session.context({ sessionID: playedCoordinator }) - assert.ok(admission.some(item => item.id === played.document.firstPlay.messageID) - || context.some(item => item.id === played.document.firstPlay.messageID), "Play admits the original new-coordinator input") - const originalInput = [...admission, ...context].find(item => item.id === played.document.firstPlay.messageID) - assert.equal(originalInput.text ?? originalInput.payload?.text, frozen) - assert.equal((await client.session.get({ sessionID: playedCoordinator })).agent, "preparation_coordinator") - assert.deepEqual((await client.session.get({ sessionID: playedCoordinator })).model, configuration.profiles.coordinator.model) - assert.equal((await client.session.context({ sessionID: binding.coordinatorSessionID })).length, 0, "the original remains empty") - await writeFile(path.join(root, "preparation-receipt.json"), JSON.stringify({ version: info.version, created, original, partial, edited, scheduled, immediate, lostAdmission, played, frozen, admission, context }, null, 2)) - console.log("PASS: private native preparation, conversion with followed context, lost creation/admission ACK, frozen exact replay, and Play with new profiles") -}) diff --git a/scripts/test-native-mission-schedule-list.mjs b/scripts/test-native-mission-schedule-list.mjs deleted file mode 100644 index 95e1c51191..0000000000 --- a/scripts/test-native-mission-schedule-list.mjs +++ /dev/null @@ -1,71 +0,0 @@ -// node scripts/test-native-mission-schedule-list.mjs -import assert from "node:assert/strict" -import path from "node:path" -import { fileURLToPath } from "node:url" -import { writeFile } from "node:fs/promises" -import { build } from "esbuild" -import { withProductRuntime } from "./native-product-fixture.mjs" -import { nativePluginBuild } from "../packages/server/scripts/native-plugin-build.mjs" -import { buildNativeScheduleFoundation } from "../packages/server/scripts/build-native-schedule-foundation.mjs" - -const [cli] = process.argv.slice(2) -const method = { input: { type: "object" }, output: { type: "object" } } -const definition = { id: "codenomad.schedule-list-qualification", methods: { - seed: method, scheduleRead: method, scheduleList: method, -}, events: {} } - -await withProductRuntime(cli, async ({ root }) => { - const directory = path.join(root, "qualification-plugin") - const artifacts = await buildNativeScheduleFoundation(path.join(root, "artifacts")) - const result = await build({ ...nativePluginBuild, metafile: true, outfile: path.join(directory, "index.mjs"), - entryPoints: [fileURLToPath(new URL("../packages/server/src/opencode/missions/native-mission-schedule-list-native-fixture.ts", import.meta.url))] }) - assert(!Object.keys(result.metafile.inputs).some(file => /node_modules[/\\](effect|@opencode[/\\]plugin)[/\\]/.test(file))) - await writeFile(path.join(directory, "package.json"), JSON.stringify({ name: "codenomad-schedule-list-qualification", version: "1.0.0", type: "module", exports: { ".": "./index.mjs" } })) - return { plugins: [{ package: directory, options: artifacts }], experimental: { schedules: true } } -}, async ({ client, root, requests }) => { - const info = await client.server.info() - assert.equal(info.version, "2.2.3") - const rpc = client.rpc(definition), options = { location: { directory: root }, signal: AbortSignal.timeout(20_000) } - const seed = await rpc.seed({}, options) - assert.equal(seed.count, 10); assert.equal(seed.tombstone, "display_01"); assert.equal(seed.armed, "display_08") - assert.ok(Number.isSafeInteger(seed.principalDueAt) && seed.principalDueAt > Date.now()) - const first = await rpc.scheduleList({ limit: 8 }, options) - assert.equal(first.schedules.length, 7, "The tombstone consumes one of the eight native page slots") - assert.equal(first.next, "display_07") - const second = await rpc.scheduleList({ after: first.next, limit: 8 }, options) - assert.deepEqual(second.schedules.map(item => item.id), ["display_08", "display_09", "display_10"]) - assert.equal(second.next, undefined) - const detail = await rpc.scheduleRead({ missionID: "display_08" }, options) - assert.deepEqual(detail.document, second.schedules[0]) - assert.deepEqual(await rpc.scheduleList({ limit: 8 }, options), first, "Repeated reads preserve every document revision") - for (const row of [...first.schedules, ...second.schedules]) { - assert.equal(row.launchedCount, 0) - assert.equal(row.checks.count, 0) - assert.ok(Number.isSafeInteger(row.checks.since) && row.checks.since > 0 && row.checks.since <= Date.now()) - if (row.id === seed.armed) { - assert.equal(row.state, "running"); assert.equal(row.observation.state, "known") - assert.equal(row.observation.nextDueAt, seed.principalDueAt); assert.equal(row.observation.wakeCount, 0) - assert.ok(row.availableActions.includes("pause")) - } else { - assert.equal(row.state, "paused"); assert.equal(row.firstPlayedAt, null) - assert.equal(row.observation.state, "unarmed"); assert.equal(row.observation.nextDueAt, null) - assert.ok(row.availableActions.includes("play")) - } - assert.ok(row.edit.structural) - } - await client.experimental.schedule.pause({ scheduleID: seed.principalID }) - const paused = await rpc.scheduleRead({ missionID: seed.armed }, options) - assert.equal(paused.document.state, "running", "Desired state is preserved by a display read") - assert.equal(paused.document.revision, detail.document.revision) - assert.equal(paused.document.observation.nativeStatus, "paused") - assert.equal(paused.document.observation.nextDueAt, null) - await client.experimental.schedule.delete({ scheduleID: seed.principalID }) - const missing = await rpc.scheduleRead({ missionID: seed.armed }, options) - assert.equal(missing.document.revision, detail.document.revision) - assert.equal(missing.document.observation.state, "unknown", "A missing native row is never rearmed by a read") - assert.equal(missing.document.observation.wakeCount, null) - assert.equal(requests.length, 0, "Display qualification sends no model request") - await writeFile(path.join(root, "schedule-list-receipt.json"), JSON.stringify({ version: info.version, - first, second, detail, paused, missing, modelRequests: requests.length }, null, 2)) - console.log("PASS: real native RPC/storage.scan pagination, tombstone cursor, list/detail parity and mutation-free reads") -}) diff --git a/scripts/test-native-mission-schedule-product.mjs b/scripts/test-native-mission-schedule-product.mjs deleted file mode 100644 index bd1c78544f..0000000000 --- a/scripts/test-native-mission-schedule-product.mjs +++ /dev/null @@ -1,743 +0,0 @@ -// Isolated retained-product qualification: private service, storage and local provider. -// node --import tsx scripts/test-native-mission-schedule-product.mjs --parent-ready --kinds=at,in -// --kinds=every --natural-every uses the real >=15-minute product interval. -import assert from "node:assert/strict" -import { spawn } from "node:child_process" -import { createHash, randomUUID } from "node:crypto" -import { existsSync } from "node:fs" -import { appendFile, mkdir, readFile, writeFile } from "node:fs/promises" -import { createServer } from "node:http" -import path from "node:path" -import { DatabaseSync } from "node:sqlite" -import { setTimeout as delay } from "node:timers/promises" -import { parseArgs } from "node:util" -import { fileURLToPath } from "node:url" -import { stopFixtureChild } from "./native-fixture-guards.mjs" -import { fixtureCliVersion } from "./native-fixture-cli-version.mjs" -import { collectColdFailure } from "./native-fixture-cold-diagnostics.mjs" -import { projectFailureSQL } from "./native-fixture-sql-projection.mjs" - -const { positionals: [cli, scratch], values } = parseArgs({ allowPositionals: true, options: { - "parent-ready": { type: "boolean" }, kinds: { type: "string", default: "at,in" }, "natural-every": { type: "boolean" }, - // Cold recovery can wait for the native 60-second leader lease and 30-second loop. - "delay-ms": { type: "string", default: "30000" }, "grace-ms": { type: "string", default: "120000" }, - "controlled-settlement": { type: "boolean" }, - "arm-only": { type: "boolean" }, - "first-admission-race": { type: "boolean" }, "crash-pending": { type: "boolean" }, - live: { type: "boolean" }, - "diagnose-stop": { type: "boolean" }, - "diagnose-product-stop": { type: "boolean" }, - "convert-preparation": { type: "boolean" }, - "existing-coordinator": { type: "boolean" }, -} }) -assert(values["parent-ready"], "Explicit product qualification requires --parent-ready") -assert(cli && scratch && path.isAbsolute(cli) && path.isAbsolute(scratch) && !existsSync(scratch), "Absolute CLI and fresh approved scratch child required") -const approved = [path.resolve(process.env.TEMP, "opencode")] -assert(approved.some(base => { const relative = path.relative(base, path.resolve(scratch)); return relative && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative) }), "Use an approved native scratch child") -const kinds = values.kinds.split(","), delayMs = Number(values["delay-ms"]), graceMs = Number(values["grace-ms"]) -const cliVersion = await fixtureCliVersion(cli) -const controlsKinds = ["paused-manual", "stop-pending", "flag-off-pause", "stop-preparing", "delete-preparing"] -assert(kinds.length && new Set(kinds).size === kinds.length && kinds.every(kind => ["at", "in", "every", ...controlsKinds].includes(kind))) -assert(!kinds.some(kind => controlsKinds.includes(kind)) || values["controlled-settlement"], "Control journeys require the explicit native Clock observer") -assert(!kinds.some(kind => controlsKinds.includes(kind)) || !values.live && !values["crash-pending"] && !values["first-admission-race"] && !values["arm-only"], "Use separate runs for control journeys and baseline mode flags") -assert(Number.isSafeInteger(delayMs) && delayMs >= 6000 && delayMs <= 120000) -assert(Number.isSafeInteger(graceMs) && graceMs >= 10000 && graceMs <= 180000) -assert(!kinds.includes("every") || values["natural-every"], "Natural every requires --natural-every and a real 900000 ms wait") -assert(!values["first-admission-race"] || !values["crash-pending"], "Use separate fresh runs for race and crash") -assert(!values["arm-only"] || !values["first-admission-race"] && !values["crash-pending"]) -assert(!values["diagnose-stop"] || kinds.length === 1 && kinds[0] === "stop-pending", "The narrow diagnostic owns one Stop-pending case only") -assert(!values["diagnose-product-stop"] || kinds.length === 1 && kinds[0] === "stop-pending" && !values["diagnose-stop"], "The product-context trace owns one separate Stop-pending case") -await mkdir(scratch, { recursive: true }) -if (process.env.GITHUB_ENV) await appendFile(process.env.GITHUB_ENV, `NATIVE_SCHEDULE_PRODUCT_FIXTURE=${scratch}\n`) -const originalEnvironment = { ...process.env }, hash = bytes => createHash("sha256").update(bytes).digest("hex") -const receipt = { preparedContract: 1, cliSHA256: hash(await readFile(cli)), kinds, cases: [], outcome: "running", gates: [ - "No deterministic lost-ACK/admission-before-count fault injection in this natural fixture", - "Concurrent replay qualifies dedupe of an actual admitted wake, not simultaneous first dispatch", - "Paused-before-Play has no native wake to replay; its cold no-admission assertion is separate", -] } - -// Managed sibling of native-product-fixture.mjs: that helper's standalone -// process has no registration/restart contract. Never share its live DB with a -// second process. This driver keeps the same private-root/local-provider policy. -async function journey(kind) { - const root = path.join(scratch, kind), project = path.join(root, "project"), databaseFile = path.join(root, "fixture.db") - await mkdir(project, { recursive: true }) - const env = Object.fromEntries(Object.entries(originalEnvironment).filter(([key]) => /^(SystemRoot|WINDIR|ComSpec|PATHEXT|PATH)$/i.test(key))) - Object.assign(env, { HOME: root, USERPROFILE: root, APPDATA: path.join(root, "appdata"), LOCALAPPDATA: path.join(root, "localappdata"), - ProgramData: path.join(root, "ProgramData"), TEMP: path.join(root, "tmp"), TMP: path.join(root, "tmp"), - OPENCODE_TEST_HOME: root, OPENCODE_CONFIG_DIR: path.join(root, "config"), OPENCODE_DB: databaseFile, - OPENCODE_CONFIG_PROJECT_DISABLE: "1", OPENCODE_DISABLE_MODELS_FETCH: "1", OPENCODE_DISABLE_FFF: "1", - npm_config_userconfig: path.join(root, ".npmrc"), npm_config_globalconfig: path.join(root, "global.npmrc"), npm_config_cache: path.join(root, "npm-cache") }) - for (const name of ["CONFIG", "DATA", "STATE", "CACHE"]) env[`XDG_${name}_HOME`] = path.join(root, `xdg-${name.toLowerCase()}`) - env.XDG_RUNTIME_DIR = path.join(root, "runtime") - for (const [name, directory] of Object.entries(env)) if (/^(HOME|USERPROFILE|APPDATA|LOCALAPPDATA|ProgramData|TEMP|TMP|OPENCODE_CONFIG_DIR|XDG_.*)$/.test(name)) await mkdir(directory, { recursive: true }) - for (const name of Object.keys(process.env)) if (/^(OPENCODE_|CODENOMAD_|XDG_|WSL_|npm_config_|GIT_)/i.test(name)) delete process.env[name] - Object.assign(process.env, env) - process.env.CLI_CONFIG = path.join(root, "profile.yaml") - const [{ default: Fastify }, { default: pino }, { OpenCode }, { Service }, - { WorkspaceManager }, { EventBus }, { rememberRuntime }, { DesktopPluginLifecycle }, { resolveDesktopPluginPaths }, - { createAutomationBridgeRegistration, publishAutomationBridge }, { registerAutomationPluginRoute }, { registerMissionRoutes }, - { WorktreeDeletionFence }, { PluginControls }, { NativeScheduleSettingsActivation }, { missionDocumentPassage }, - { NativeScheduleTransportRpc, nativeScheduleWakeKey }, { readNativeScheduleIncarnation }, { nativeScheduleCarrierLookupKey }, experimentalEditor] = await Promise.all([ - import("fastify"), import("pino"), import("@opencode/client"), import("@opencode/client/service"), - import("../packages/server/src/workspaces/manager.ts"), import("../packages/server/src/events/bus.ts"), - import("../packages/server/src/opencode/compatibility/runtime.ts"), import("../packages/server/src/opencode/desktop-plugin-lifecycle.ts"), - import("../packages/server/src/opencode/desktop-plugin-paths.ts"), import("../packages/server/src/opencode/automation-plugin.ts"), - import("../packages/server/src/server/routes/automation-plugin.ts"), import("../packages/server/src/server/routes/missions.ts"), - import("../packages/server/src/workspaces/worktree-session-evacuation.ts"), import("../packages/server/src/opencode/plugin-controls.ts"), - import("../packages/server/src/opencode/native-schedule-settings-activation.ts"), import("../packages/server/src/missions/mission-document-passage-storage.ts"), - import("../packages/server/src/opencode/missions/native-schedule-transport-contract.ts"), import("../packages/server/src/opencode/missions/native-schedule-transport-identity.ts"), - import("../packages/server/src/opencode/missions/native-schedule-carrier-binding.ts"), - import("../packages/server/src/opencode/native-experimental-settings.ts"), - ]) - const bundled = new URL("../packages/server/dist/plugins/missions/plugin.mjs", import.meta.url) - const providerBundle = new URL("../packages/server/dist/plugins/missions/provider.mjs", import.meta.url) - const result = { kind, root, status: "running", armOnly: !!values["arm-only"], firstAdmissionRaceMode: !!values["first-admission-race"], crashPendingMode: !!values["crash-pending"], productBundleSHA256: hash(await readFile(bundled)), providerBundleSHA256: hash(await readFile(providerBundle)), serviceStarts: [], http: [] } - if (values["diagnose-stop"]) assert.equal(result.productBundleSHA256, "3578b0357396e1834221a0f37159a8fe2d6a8a63f81fcad11b3d364b1dca0c10", "Diagnostic requires the unchanged failing qualification bundle") - receipt.cases.push(result) - const prefix = `plugin:${Array.from("codenomad.missions").map(char => char.charCodeAt(0).toString(16).padStart(4, "0")).join("")}:` - const registrationFile = path.join(env.XDG_STATE_HOME, "opencode/service.json"), children = [], releases = new Set() - let nativeErrorLength = 0, nativeErrorTruncated = false, credentialsChild, qualificationError - const maintenanceLog = path.join(root, "maintenance-events.jsonl") - let ownedTechnical = [] - let controlTrace - let child, client, endpoint, manager, app, plugin, removeBridge, baseURL, workspace, providerError, holdBusiness = true - const calls = [], reported = new Set(), providerOpen = new Set(), secrets = new Set(["fixture-only"]) - const barrierToken = randomUUID(); secrets.add(barrierToken) - let heldOriginal, pendingHandoff, releaseOriginal, barrierDone = false - const releaseBarrier = reason => { if (heldOriginal && !heldOriginal.releasedAt) { heldOriginal.releasedAt = Date.now(); heldOriginal.releaseReason = reason }; releaseOriginal?.() } - const barrier = createServer(async (request, response) => { - try { - if (request.method !== "POST" || !["/original", "/pending"].includes(request.url) || request.headers["x-fixture-barrier"] !== barrierToken) return response.writeHead(403).end() - let raw = ""; for await (const bytes of request) { raw += bytes; if (raw.length > 32768) throw Error("barrier-input-bound") } - const input = JSON.parse(raw) - assert.equal(input.document?.missionID, result.documentID) - assert.equal(input.request?.registrationFile, registrationFile); assert.equal(input.request?.incarnation?.pid, child.pid) - assert.equal(input.request?.wake?.missionID, result.documentID) - assert(!input.sessionID.startsWith("ses_cn_schedule_"), "Only the original business admission may be held") - if (request.url === "/pending") { pendingHandoff = { ...input, enteredAt: Date.now() }; return response.writeHead(200, { "content-type": "application/json" }).end('{"observed":true}') } - if (barrierDone) return response.writeHead(200, { "content-type": "application/json" }).end('{"resume":true,"alreadyReleased":true}') - assert(!heldOriginal, "Only one original admission barrier is allowed") - heldOriginal = { ...input, enteredAt: Date.now(), releasedAt: null }; barrierDone = true - const timer = setTimeout(() => releaseBarrier("barrier-budget-expired"), 6000) - response.once("close", () => releaseBarrier(heldOriginal?.releasedAt ? heldOriginal.releaseReason : "barrier-client-aborted")) - try { await new Promise(resolve => { releaseOriginal = resolve }) } finally { clearTimeout(timer) } - if (!response.destroyed) response.writeHead(200, { "content-type": "application/json" }).end('{"resume":true}') - } catch { providerError = "fixture-original-barrier-contract"; if (!response.destroyed) response.writeHead(400).end() } - }) - const provider = createServer(async (request, response) => { - let callRecord - providerOpen.add(response) - try { - let raw = ""; for await (const bytes of request) { raw += bytes; if (raw.length > 2 * 1024 * 1024) throw Error("provider-input-bound") } - const input = JSON.parse(raw), sessionID = request.headers["x-fixture-session"] - assert.equal(request.headers["x-fixture-kind"], "primary", "A technical/auxiliary turn reached the business provider") - assert.equal(typeof sessionID, "string") - const tools = (input.tools ?? []).map(tool => tool.function?.name), first = !reported.has(sessionID) - if (first) assert(tools.includes("mission_report"), "Actual native mission_report tool unavailable") - callRecord = { sessionID, first, at: Date.now() }; calls.push(callRecord) - if (holdBusiness) await new Promise(resolve => { releases.add(resolve); response.once("close", resolve) }) - if (response.destroyed) { callRecord.closedBeforeResponse = true; return } - const call = { index: 0, id: `fixture_${randomUUID().replaceAll("-", "")}`, type: "function", function: { name: "mission_report", - arguments: JSON.stringify({ outcome: "completed", summary: "Owned native product passage completed", final: true }) } } - reported.add(sessionID) - callRecord.reportStreamed = first - response.writeHead(200, { "content-type": "text/event-stream" }) - for (const [delta, finish_reason] of [[first ? { role: "assistant", tool_calls: [call] } : { role: "assistant", content: "Done" }, null], [{}, first ? "tool_calls" : "stop"]]) - response.write(`data: ${JSON.stringify({ id: "fixture", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta, finish_reason }] })}\n\n`) - response.end("data: [DONE]\n\n") - } catch { providerError = "fixture-provider-contract"; if (!response.destroyed) { response.writeHead(400, { "content-type": "application/json" }); response.end('{"error":{"type":"invalid_request_error","message":"fixture-provider-contract"}}') } } - finally { providerOpen.delete(response) } - }) - const save = (name, value) => writeFile(path.join(root, `${name}.json`), JSON.stringify(value, null, 2)) - const readSQL = use => { - const db = new DatabaseSync(databaseFile, { readOnly: true, timeout: 5000 }) - try { db.exec("BEGIN"); const value = use(db); db.exec("COMMIT"); return value } finally { db.close() } - } - const readOnlyStorage = { get: async key => readSQL(db => { const row = db.prepare("SELECT value FROM kv WHERE key=?").get(`${prefix}${key}`); return row && JSON.parse(row.value) }), - scan: async ({ prefix: key, after, limit = 100 }) => readSQL(db => { - const entries = db.prepare("SELECT key,value FROM kv WHERE key>=? AND key? ORDER BY key LIMIT ?").all(`${prefix}${key}`, `${prefix}${key}\uffff`, `${prefix}${after ?? ""}`, limit) - .map(row => ({ key: row.key.slice(prefix.length), value: JSON.parse(row.value) })) - return { entries, ...(entries.length === limit ? { next: entries.at(-1).key } : {}) } - }), set: async () => { throw Error("qualification-read-only") } } - const document = (db, id) => { - const rows = db.prepare("SELECT value FROM kv WHERE instr(key,?)=1 AND instr(key,'/project/')>0 AND json_extract(value,'$.id')=? LIMIT 2") - .all(`${prefix}codenomad-missions/documents-v1/`, id) - assert.equal(rows.length, 1, "Exact unified document unavailable") - assert(Buffer.byteLength(rows[0].value) <= 256 * 1024) - return JSON.parse(rows[0].value) - } - const snapshot = (id, failureDetails = false) => readSQL(db => { - const doc = document(db, id), passage = doc.pending ?? doc.history?.at(-1) - const start = passage ? db.prepare("SELECT id,type FROM session_message WHERE session_id=? AND type IN ('user','synthetic') ORDER BY seq LIMIT 16").all(passage.coordinatorSessionID) : [] - const sessions = db.prepare("SELECT id,parent_id,metadata,time_suspended FROM session_v2 WHERE json_extract(metadata,'$.\"codenomad.mission\".document.missionID')=? LIMIT 16").all(id) - const schedules = (doc.calendarOwner?.slots ?? []).filter(slot => slot.scheduleID).map(slot => { - const schedule = { role: slot.role, - ...db.prepare('SELECT id,session_id,status,next_due_at,run_count,time_created,"when" AS native_when FROM schedule WHERE id=?').get(slot.scheduleID) } - if (failureDetails) { - Object.assign(schedule, db.prepare("SELECT last_outcome,retry_at,time_updated,last_message_id FROM schedule WHERE id=?").get(slot.scheduleID)) - const proof = row => { - if (!row) return null - const { body, ...status } = row, data = body === null ? null : JSON.parse(body), text = data?.text - return { ...status, bodyOmitted: body === null, schedule: data?.metadata?.schedule ?? null, - textBytes: typeof text === "string" ? Buffer.byteLength(text) : null, textSHA256: typeof text === "string" ? hash(text) : null } - } - schedule.carrier = { sessionID: slot.sessionID, - session: db.prepare("SELECT id,time_suspended,time_busy,time_idle,idle_outcome FROM session_v2 WHERE id=?").get(slot.sessionID) ?? null, - messages: Array.from(new Set([schedule.last_message_id, ...(schedule.id ? [`msg_${schedule.id}_${schedule.run_count + 1}`] : [])].filter(Boolean)), messageID => ({ messageID, - message: proof(db.prepare("SELECT type,seq,time_created,time_updated,length(CAST(data AS BLOB)) AS bytes,CASE WHEN length(CAST(data AS BLOB))<=262144 THEN data END AS body FROM session_message WHERE id=? AND session_id=?").get(messageID, slot.sessionID)), - inbox: proof(db.prepare("SELECT type,delivery,enqueued_seq,time_created,length(CAST(payload AS BLOB)) AS bytes,CASE WHEN length(CAST(payload AS BLOB))<=262144 THEN payload END AS body FROM session_inbox WHERE id=? AND session_id=?").get(messageID, slot.sessionID)) })) } - } - return schedule - }) - const startDetails = passage ? db.prepare("SELECT id,type,data FROM session_message WHERE session_id=? AND type IN ('user','synthetic') ORDER BY seq LIMIT 64").all(passage.coordinatorSessionID) - .map(row => { const data = JSON.parse(row.data); return { id: row.id, type: row.type, textSHA256: hash(data.text ?? ""), - metadataKeys: Object.keys(data.metadata ?? {}), missionDocument: data.metadata?.["codenomad.mission"]?.document, - description: typeof data.description === "string" && /^[A-Za-z0-9 .,:_-]{1,128}$/.test(data.description) ? data.description : undefined } }) : [] - return { document: doc, start, startDetails, sessions: sessions.map(({ id, parent_id }) => ({ id, parent_id })), - claims: sessions.map(({ id, time_suspended }) => ({ id, time_suspended })), - inboxCount: passage ? db.prepare("SELECT count(*) AS count FROM session_inbox WHERE session_id=?").get(passage.coordinatorSessionID).count : 0, schedules } - }) - const technicalRows = () => readSQL(db => ownedTechnical.map(item => { - const session = db.prepare("SELECT time_suspended FROM session_v2 WHERE id=?").get(item.sessionID) - return { ...item, sessionPresent: !!session, nativeClaim: session?.time_suspended, - inboxCount: db.prepare("SELECT count(*) AS count FROM session_inbox WHERE session_id=?").get(item.sessionID).count, - schedulePresent: !!db.prepare("SELECT 1 FROM schedule WHERE id=?").get(item.scheduleID), reverseIndexPresent: !!db.prepare("SELECT 1 FROM kv WHERE key=?").get(item.lookupKey) } - })) - const learnTechnical = state => { - const location = { project: { id: state.document.projectID, canonical: state.document.projectCanonical } } - ownedTechnical = state.document.calendarOwner.slots.map(slot => ({ role: slot.role, sessionID: slot.sessionID, scheduleID: slot.scheduleID, - lookupKey: `${prefix}${nativeScheduleCarrierLookupKey({ location }, slot.sessionID)}` })) - } - const maintenanceEvents = async () => { - const bytes = await readFile(maintenanceLog).catch(error => { if (error.code !== "ENOENT") throw error; return Buffer.alloc(0) }) - assert(bytes.length <= 1024 * 1024, "Qualification maintenance evidence overflow") - const events = bytes.toString("utf8").trim().split("\n").filter(Boolean).map(JSON.parse) - assert(!events.some(event => event.kind === "observer-overflow")) - return events - } - const until = async (check, timeout = graceMs) => { - for (const deadline = Date.now() + timeout; Date.now() < deadline;) { - if (providerError) throw Error(providerError) - const value = await check(); if (value) return value - assert(!child || child.exitCode === null, "Owned native process exited") - await delay(100) - } - throw Error("bounded-product-qualification-deadline") - } - const launch = async (cold = false) => { - assert(!child || child.exitCode !== null || child.signalCode !== null, "Never run two service incarnations against this DB") - credentialsChild = undefined; nativeErrorLength = 0; nativeErrorTruncated = false - child = spawn(cli, ["serve", "--service", "--hostname", "127.0.0.1", "--port", "0"], { cwd: project, env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }) - const current = { child, closed: new Promise(resolve => child.once("close", resolve)) }; children.push(current) - child.stdout.resume(); child.stderr.on("data", bytes => { - // Retain only bounded diagnostic bookkeeping, never credential fragments. - nativeErrorLength += bytes.toString().length - nativeErrorTruncated ||= nativeErrorLength > 32000 - nativeErrorLength = Math.min(nativeErrorLength, 32000) - }) - const publicInfo = await until(async () => { - try { const info = readNativeScheduleIncarnation(registrationFile); return info.pid === child.pid ? info : false } catch { return false } - }, 40000) - assert.notEqual(new URL(publicInfo.url).port, "28894") - result.serviceStarts.push({ ...publicInfo, cold, at: Date.now() }) - client = undefined; endpoint = undefined - if (!cold) await connect() - } - const connect = async signal => { - // Registration can precede HTTP readiness. Retry only discovery of our own - // process; native mutations and the cold no-client window keep their gates. - endpoint = await until(async () => { - signal?.throwIfAborted() - assert.equal(readNativeScheduleIncarnation(registrationFile).pid, child.pid) - return Service.discover({ file: registrationFile }) - }, 40000) - signal?.throwIfAborted() - assert(endpoint && endpoint.url === readNativeScheduleIncarnation(registrationFile).url) - client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }) - if (endpoint.auth?.password) { secrets.add(endpoint.auth.password); secrets.add(Buffer.from(`${endpoint.auth.username}:${endpoint.auth.password}`).toString("base64")) } - const info = await client.server.info({ signal }); assert.equal(info.version, cliVersion); assert.equal(info.pid, child.pid) - if (endpoint.auth?.password) credentialsChild = child - rememberRuntime(endpoint, { version: info.version, pid: info.pid, discovery: "info" }) - } - const stop = async () => { - const owned = children.find(entry => entry.child === child) - if (owned && child.exitCode === null && child.signalCode === null) await stopFixtureChild(child, owned.closed) - client = undefined; endpoint = undefined - } - const yaml = path.join(root, "profile.yaml"), human = { sessionId: randomUUID(), username: "fixture-human" } - const scope = { channel: "native-fixture", configIdentity: yaml, key: hash(`native-fixture\0${yaml}`) } - const settings = { getProfileScope: () => scope, configYamlPathForAuthority: () => yaml, getOwner: () => ({ environmentVariables: {} }), readEnvironmentForAdmission: async () => ({}) } - const cookie = `session=${human.sessionId}`, auth = { isAuthEnabled: () => true, - isLoopbackRequest: request => ["127.0.0.1", "::1", "::ffff:127.0.0.1"].includes(request.ip), getCookieName: () => "session", - getSessionFromHeaders: headers => headers.cookie === cookie ? human : null, getSessionFromRequest: request => request.headers.cookie === cookie ? human : null } - secrets.add(cookie); secrets.add(human.sessionId) - const closeBackend = async () => { - await plugin?.stop(); plugin = undefined - await removeBridge?.(); removeBridge = undefined - await app?.close(); app = undefined - await manager?.shutdown(); manager = undefined - client = undefined; endpoint = undefined - } - const http = async (suffix, payload, allowPending = false) => { - const response = await fetch(`${baseURL}/api/workspaces/${workspace.id}/missions${suffix}`, { method: "POST", headers: { cookie, "content-type": "application/json" }, - body: JSON.stringify(payload), signal: AbortSignal.timeout(95_000) }) - const raw = await response.text() - let body - try { body = JSON.parse(raw) } catch { throw Error(`Product HTTP ${response.status}: non-json-response`) } - if (!body || typeof body !== "object" || Array.isArray(body)) throw Error(`Product HTTP ${response.status}: non-object-response`) - const code = typeof body.code === "string" && /^[a-z0-9-]{1,80}$/.test(body.code) ? body.code : undefined - const reason = typeof body.refusal?.reason === "string" && /^[a-z0-9-]{1,120}$/.test(body.refusal.reason) ? body.refusal.reason : undefined - if (code === "schedule-refused") assert(reason, "Schedule refusal requires its native reason") - result.http.push({ suffix, action: payload.action ?? "activate", requestID: payload.requestID, - expectedRevision: payload.expectedRevision ?? payload.expectedDocumentRevision, status: response.status, ...(code ? { code } : {}), reason, pending: body.pending, - document: body.document && { id: body.document.id, revision: body.document.revision, state: body.document.state, - launchedCount: body.document.launchedCount, pending: body.document.pending, activation: body.document.scheduleActivation?.state } }) - assert(response.status === 200 || allowPending && response.status === 503 && body.pending === true, `Product HTTP ${response.status}: ${code ?? "unconfirmed"}; reason=${reason ?? "missing"}`) - return body - } - const create = async (label, timing, maxLaunches = 1) => { - const selected = { agent: "fixture-worker", model: { providerID: "fixture", id: "fixture" } } - const existing = values["existing-coordinator"] ? await client.session.create({ location: { directory: project }, - title: `Existing ${label}`, agent: "build", model: { providerID: "fixture", id: "fixture" }, metadata: { unrelated: "preserve" } }) : undefined - const configuration = { - title: `Native ${label}`, objective: "Use the actual mission_report tool to finalize this owned fixture passage. No helpers or other effects.", - template: "custom", taskMode: "native", profiles: { coordinator: selected, roles: { specialist: selected } }, watchedConversationIDs: [], - launch: { timing, condition: null, ends: { at: null, afterMs: null, maxLaunches } }, - ...(existing ? { coordinatorSessionID: existing.id } : {}), - } - let response - if (values["convert-preparation"]) { - const { launch: _launch, watchedConversationIDs: _watched, coordinatorSessionID: _coordinator, ...fields } = configuration - const original = await http("", { ...fields, requestId: `create_${label}_${randomUUID().replaceAll("-", "")}`, directory: project }) - const before = snapshot(original.mission.id) - assert(before.document.oneTime && before.document.firstPlayedAt === null && before.schedules.length === 0) - response = await http(`/${original.mission.id}/schedule`, { requestID: `convert_${label}_${randomUUID().replaceAll("-", "")}`, - expectedRevision: before.document.revision, action: "configure", configuration }) - const converted = snapshot(original.mission.id) - assert.equal(response.document.id, original.mission.id) - assert.equal(converted.document.oneTime.creationDigest, before.document.oneTime.creationDigest) - assert.equal(converted.document.oneTime.creationRequestID, before.document.oneTime.creationRequestID) - assert(converted.document.dormantJournal && converted.document.firstPlayedAt === null && converted.schedules.length === 0) - assert.equal(calls.length, 0) - result.conversions ??= []; result.conversions.push({ id: original.mission.id, before, converted }) - } else response = await http("/scheduled", { requestID: `create_${label}_${randomUUID().replaceAll("-", "")}`, expectedRevision: 0, action: "create", configuration }) - assert.equal(response.document.state, "paused"); assert.equal(response.document.launchedCount, 0) - if (existing) { result.existingCoordinators ??= []; result.existingCoordinators.push({ missionID: response.document.id, id: existing.id, title: existing.title }) } - return response.document.id - } - const activate = async id => { - const before = snapshot(id).document - const activation = await http(`/${id}/schedule-settings`, { requestID: `activate_${randomUUID().replaceAll("-", "")}`, expectedDocumentRevision: before.revision }) - assert.equal(activation.document.scheduleActivation.state, "ready"); assert.equal(activation.document.state, "paused") - } - const control = async (id, action, options = {}) => http(`/${id}/schedule`, { requestID: `${action}_${randomUUID().replaceAll("-", "")}`, expectedRevision: snapshot(id).document.revision, action, - ...(action === "delete" ? { deleteManagedSessions: false } : {}) }, options.allowPending) - try { - await writeFile(yaml, "server:\n environmentVariables: {}\n") - await new Promise(resolve => provider.listen(0, "127.0.0.1", resolve)); assert.notEqual(provider.address().port, 28894) - if (values["first-admission-race"]) { await new Promise(resolve => barrier.listen(0, "127.0.0.1", resolve)); assert.notEqual(barrier.address().port, 28894) } - const observer = path.join(root, "provider-observer"); await mkdir(observer) - await writeFile(path.join(observer, "package.json"), JSON.stringify({ name: "codenomad-product-provider-observer", type: "module", exports: { ".": "./index.mjs" } })) - await writeFile(path.join(observer, "index.mjs"), `import {Plugin,Rpc} from "@opencode/plugin/effect"; -import {Effect,Stream,Scope} from "effect";import {appendFileSync} from "node:fs"; -const file=${JSON.stringify(maintenanceLog)},key=Symbol.for("codenomad.product-qualification.maintenance-observer"); -const method="/api/rpc/codenomad.missions.schedule-maintenance/reconcile",wakeMethod="/api/rpc/codenomad.missions.schedule/wake"; -export default Plugin.define({id:"codenomad.product-provider-observer",effect:ctx=>Effect.gen(function*(){ - const ownerScope=yield*Scope.Scope; - let state=globalThis[key];if(!state){ - state={refs:0,count:0,request:0,original:globalThis.fetch,wakes:new Map(),raced:new Set(),handoffs:new Set()}; - state.log=event=>{if(state.count++>512)return;appendFileSync(file,JSON.stringify(state.count===513?{kind:"observer-overflow"}:{...event,at:Date.now(),pid:process.pid})+"\\n")}; - state.wrapper=new Proxy(state.original,{apply(target,thisArg,args){ - const [input,init]=args;let match=false;try{const url=new URL(input instanceof Request?input.url:String(input));const own=["127.0.0.1","localhost","[::1]"].includes(url.hostname)&&(init?.method??input?.method)==="POST"; - if(own&&url.pathname===wakeMethod&&typeof init?.body==="string"&&init.body.length<=32768){const body=JSON.parse(init.body);if(typeof body.input?.wake?.missionID==="string"&&state.wakes.size<32){state.wakes.set(body.input.wake.missionID,structuredClone(body.input));state.log({kind:"genuine-wake-captured",missionID:body.input.wake.missionID,sessionID:body.input.wake.sessionID})}} - match=own&&url.pathname===method}catch{} - if(!match)return Reflect.apply(target,thisArg,args); - let sessionID;try{if(typeof init?.body==="string"&&init.body.length<=32768){const body=JSON.parse(init.body);if(typeof body.input?.sessionID==="string"&&/^[A-Za-z0-9_.:-]{1,240}$/.test(body.input.sessionID))sessionID=body.input.sessionID}}catch{} - const requestID=++state.request;state.log({kind:"maintenance-http-request",requestID,sessionID}); - return Promise.resolve(Reflect.apply(target,thisArg,args)).then(response=>{state.log({kind:"maintenance-http-response",requestID,sessionID,status:response.status});return response},error=>{state.log({kind:"maintenance-http-error",requestID,sessionID});throw error}); - }});globalThis.fetch=state.wrapper;globalThis[key]=state; - } - state.refs++;yield*Effect.addFinalizer(()=>Effect.sync(()=>{if(--state.refs===0){if(globalThis.fetch===state.wrapper)globalThis.fetch=state.original;if(globalThis[key]===state)delete globalThis[key]}})); - state.log({kind:"observer-setup",raceConfigured:!!ctx.options.raceBarrier}); - if(ctx.options.raceBarrier)yield*ctx.session.hook("prompt",event=>Effect.gen(function*(){ - state.log({kind:"prompt-observed",sessionID:event.sessionID,messageID:event.messageID,metadataKeys:Object.keys(event.metadata??{})}); - const document=event.metadata?.["codenomad.mission"]?.document; - if(!document||state.raced.has(event.messageID))return; - if(event.sessionID.startsWith("ses_cn_schedule_"))throw Error("fixture-barrier-technical-session"); - const request=state.wakes.get(document.missionID);if(!request)throw Error("fixture-barrier-original-wake-unavailable"); - state.raced.add(event.messageID);state.log({kind:"original-admission-held",sessionID:event.sessionID,messageID:event.messageID}); - yield*Effect.tryPromise({try:async signal=>{const response=await Reflect.apply(state.original,globalThis,[ctx.options.raceBarrier.url,{method:"POST",headers:{"content-type":"application/json","x-fixture-barrier":ctx.options.raceBarrier.token},body:JSON.stringify({document,sessionID:event.sessionID,messageID:event.messageID,request}),signal:AbortSignal.any([signal,AbortSignal.timeout(6500)])}]);if(!response.ok)throw Error("fixture-barrier-refused");await response.json()},catch:()=>Error("fixture-original-barrier-failed")}).pipe(Effect.orDie); - })); - yield*ctx.session.hook("http.request",event=>Effect.gen(function*(){ - event.request.headers.set("x-fixture-kind",event.kind);event.request.headers.set("x-fixture-session",event.sessionID); - if(ctx.options.raceBarrier&&event.kind==="primary"&&!event.sessionID.startsWith("ses_cn_schedule_")&&!state.handoffs.has(event.sessionID)){ - const request=[...state.wakes.values()].at(-1);if(!request)throw Error("fixture-pending-wake-unavailable");state.handoffs.add(event.sessionID); - yield*Effect.tryPromise({try:async signal=>{const response=await Reflect.apply(state.original,globalThis,[ctx.options.raceBarrier.url.replace(/original$/,"pending"),{method:"POST",headers:{"content-type":"application/json","x-fixture-barrier":ctx.options.raceBarrier.token},body:JSON.stringify({document:{missionID:request.wake.missionID},sessionID:event.sessionID,request}),signal}]);if(!response.ok)throw Error("fixture-pending-handoff-refused");await response.json()},catch:()=>Error("fixture-pending-handoff-failed")}).pipe(Effect.orDie); - } - })); - const preparingRpc=Rpc.define({id:"codenomad.product-qualification",methods:{armPreparing:{input:{type:"object"},output:{type:"object"}}},events:{}}); - yield*ctx.rpc.register(preparingRpc,{armPreparing:raw=>Effect.gen(function*(){ - const target=raw,session=yield*ctx.session.get({sessionID:target.sessionID}),marker=session.metadata?.["codenomad.schedule-carrier"]; - const url=new URL(target.url);if(url.protocol!=="http:"||url.hostname!=="127.0.0.1"||url.pathname!=="/hold-preparing"||url.port==="28894"||url.username||url.password||url.search||url.hash||marker?.missionID!==target.missionID||marker.role!=="principal")throw Error("fixture-preparing-target"); - let used=false;yield*ctx.session.hook("prompt",event=>Effect.gen(function*(){ - if(used||event.sessionID!==target.sessionID)return;used=true;const schedule=event.metadata?.schedule; - if(typeof schedule?.id!=="string"||event.messageID!=="msg_"+schedule.id+"_"+schedule.run)throw Error("fixture-preparing-wake"); - yield*Effect.tryPromise({try:async signal=>{const response=await Reflect.apply(state.original,globalThis,[url.href,{method:"POST",headers:{"content-type":"application/json","x-fixture-barrier":target.token},body:JSON.stringify({sessionID:event.sessionID,messageID:event.messageID,schedule}),signal:AbortSignal.any([signal,AbortSignal.timeout(6500)])}]);if(!response.ok)throw Error("fixture-preparing-refused");await response.json()},catch:()=>Error("fixture-preparing-aborted")}).pipe(Effect.orDie); - })).pipe(Effect.provideService(Scope.Scope,ownerScope));return{armed:true,sessionID:target.sessionID}; - })}); - yield*ctx.event.subscribe({types:["session.execution.started","session.execution.succeeded","session.execution.failed","session.execution.interrupted"]}).pipe(Stream.runForEach(event=>Effect.sync(()=>{if(typeof event.data?.sessionID==="string")state.log({kind:event.type==="session.execution.started"?"execution-started":"terminal",type:event.type,sessionID:event.data.sessionID,nativeCreatedAt:typeof event.created==="number"?event.created:undefined})})),Effect.forkScoped); -})});`) - const extraPlugins = [values["first-admission-race"] ? { package: observer, options: { raceBarrier: { url: `http://127.0.0.1:${barrier.address().port}/original`, token: barrierToken } } } : observer] - if (values["diagnose-product-stop"]) { - const { buildControlTraceBundle } = await import("./native-mission-schedule-control-trace.mjs") - controlTrace = await buildControlTraceBundle(root, registrationFile, [...secrets]) - result.originalProductBundleSHA256 = result.productBundleSHA256 - result.diagnosticVariant = controlTrace; result.loadedRuntimeKind = "scratch-control-trace-not-final-product" - } - if (values["diagnose-stop"]) { - const { buildStopDiagnosticPlugin } = await import("./native-mission-schedule-stop-diagnostic.mjs") - const diagnostic = await buildStopDiagnosticPlugin(root) - result.diagnosticSourceSHA256 = diagnostic.sourceSHA256; extraPlugins.push(diagnostic.directory) - } - if (values["controlled-settlement"]) { - const [{ build }, { nativePluginBuild }] = await Promise.all([import("esbuild"), import("../packages/server/scripts/native-plugin-build.mjs")]) - const clock = path.join(root, "clock-observer"); await mkdir(clock) - await build({ ...nativePluginBuild, entryPoints: [fileURLToPath(new URL("../packages/server/src/opencode/missions/native-schedule-carrier-clock-fixture.ts", import.meta.url))], outfile: path.join(clock, "index.mjs") }) - await writeFile(path.join(clock, "package.json"), JSON.stringify({ name: "codenomad-product-clock-qualification", type: "module", exports: { ".": "./index.mjs" } })); extraPlugins.push(clock) - } - const configuration = { update: "disable", snapshots: false, experimental: { schedules: true }, permissions: [{ action: "*", resource: "*", effect: "allow" }], - plugins: extraPlugins, model: "fixture/fixture", agents: { "fixture-worker": { mode: "all", description: "Owned native product coordinator" }, title: { model: "fixture/fixture" }, compaction: { model: "fixture/fixture" } }, - providers: { fixture: { activation: "enabled", package: "@opencode/ai/providers/openai-compatible", settings: { baseURL: `http://127.0.0.1:${provider.address().port}/v1`, apiKey: "fixture-only" }, models: { fixture: { limit: { context: 128000, output: 4096 } } } } } } - assert(!("codenomad-missions-local" in configuration.providers)) - await writeFile(path.join(env.OPENCODE_CONFIG_DIR, "opencode.json"), JSON.stringify(configuration)) - await writeFile(path.join(env.XDG_CONFIG_HOME, "opencode", "service.json"), JSON.stringify({ hostname: "127.0.0.1", port: 0, disabled: false })).catch(async error => { - if (error.code !== "ENOENT") throw error - await mkdir(path.join(env.XDG_CONFIG_HOME, "opencode"), { recursive: true }); await writeFile(path.join(env.XDG_CONFIG_HOME, "opencode/service.json"), '{"hostname":"127.0.0.1","port":0,"disabled":false}') - }) - await launch() - manager = new WorkspaceManager({ rootDir: root, logger: pino({ level: "silent" }), eventBus: new EventBus(), settings, - binaryResolver: { resolveDefault: () => ({ path: cli, label: "Owned scheduled product fixture" }) }, - hostServiceLifecycleFactory: () => ({ discover: async () => endpoint, ensure: async () => endpoint }) }) - workspace = (await manager.create(project)).workspace - const connection = await manager.getSharedServiceConnection(workspace.id), paths = await resolveDesktopPluginPaths(connection, { kind: "host", platform: process.platform, binary: cli }) - assert(path.relative(root, paths.config) && !path.relative(root, paths.config).startsWith("..")) - const fence = new WorktreeDeletionFence(), registration = createAutomationBridgeRegistration("http://127.0.0.1:1") - secrets.add(registration.token) - app = Fastify(); app.addHook("preHandler", (request, reply, done) => { - if (request.url.startsWith("/api/workspaces/") && !auth.getSessionFromRequest(request)) return reply.code(401).send({ code: "fixture-human-required" }) - done() - }) - const controls = new PluginControls({ workspaceManager: manager, worktreeDeletionFence: fence, logger: pino({ level: "silent" }) }) - app.post("/fixture/native-schedules", async (request, reply) => { - if (!auth.getSessionFromRequest(request) || typeof request.body?.enabled !== "boolean") return reply.code(403).send({ code: "fixture-config-refused" }) - try { - await controls.editConfigDocuments(workspace.id, { directory: project }, view => { - const target = view.documents.find(item => item.scope === "global"), relative = target && path.relative(root, target.document.writePath) - assert(target && relative && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) - return [{ scope: "global", path: target.path, expectation: experimentalEditor.nativeSettingExpectation(target.document), - updated: experimentalEditor.editMissionExperimental(target.document, "schedules", request.body.enabled, - experimentalEditor.inheritedMissionExperimental(view.entries, target.path, view.location.directory), "global") }] - }, { beforeWrite: async () => {}, afterWrite: async () => {} }) - return { enabled: request.body.enabled } - } catch { return reply.code(503).send({ code: "fixture-config-unconfirmed" }) } - }) - registerMissionRoutes(app, { workspaceManager: manager, worktreeDeletionFence: fence, auth, settings, bridgeToken: registration.token, - scheduleSettingsActivation: new NativeScheduleSettingsActivation(controls, manager) }) - registerAutomationPluginRoute(app, { workspaceManager: manager, worktreeDeletionFence: fence, authManager: auth, settings, bridgeToken: registration.token, nativeParent: {}, developerCdp: {} }) - await app.listen({ host: "127.0.0.1", port: 0 }); baseURL = `http://127.0.0.1:${app.server.address().port}`; assert.notEqual(app.server.address().port, 28894) - registration.url = `${baseURL}/api/opencode-plugin/automation`; removeBridge = await publishAutomationBridge(registration) - plugin = controlTrace ? new DesktopPluginLifecycle("missions", () => readFile(controlTrace.file)) : new DesktopPluginLifecycle("missions"); await plugin.start(paths) - await until(async () => (await client.plugin.list({ location: { directory: project } })).data.some(item => item.id === "codenomad.missions" && item.state.status === "active")) - if (controlsKinds.includes(kind)) { - const { runProductControlJourney } = await import("./native-mission-schedule-product-controls.mjs") - await runProductControlJourney(kind, { result, project, delayMs, create, activate, control, snapshot, save, until, readSQL, - diagnoseStop: !!values["diagnose-stop"], - controlTrace, - technicalRows, learnTechnical, maintenanceEvents, client: () => client, calls, providerOpen: () => providerOpen.size, - reported: id => reported.has(id), secret: value => secrets.add(value), hold: enabled => { holdBusiness = enabled; if (!enabled) { for (const release of releases) release(); releases.clear() } }, - business: doc => missionDocumentPassage(readOnlyStorage, doc, () => true).journal.snapshot(), - nativeFlag: async enabled => { - const response = await fetch(`${baseURL}/fixture/native-schedules`, { method: "POST", headers: { cookie, "content-type": "application/json" }, body: JSON.stringify({ enabled }), signal: AbortSignal.timeout(15000) }) - assert.equal(response.status, 200, "Owned fixture config API failed") - await until(async () => experimentalEditor.effectiveMissionExperimental(await client.config.get({ location: { directory: project } })).schedules === enabled) - } }) - result.calls = calls; result.status = values["diagnose-stop"] || controlTrace ? "diagnostic-only" : "passed"; result.stage = "completed"; return result - } - const pausedID = await create("paused", { kind: "in", delayMs }), stoppedID = await create("stopped", { kind: "in", delayMs }) - await activate(stoppedID); await control(stoppedID, "play"); await control(stoppedID, "stop") - if (values["convert-preparation"]) { - const deletedID = await create("delete", { kind: "in", delayMs }) - assert.equal((await control(deletedID, "delete")).deleted, true) - const response = await fetch(`${baseURL}/api/workspaces/${workspace.id}/missions`, { headers: { cookie }, signal: AbortSignal.timeout(15000) }) - assert.equal(response.status, 200) - const panel = await response.json() - assert(!panel.missions.some(mission => mission.id === deletedID) && !panel.summaries.some(mission => mission.id === deletedID)) - result.deletedConvertedID = deletedID - } - const timing = kind === "every" ? { kind, intervalMs: 900000 } : kind === "at" ? { kind, at: Date.now() + delayMs, zone: "UTC" } : { kind, delayMs } - const id = await create(kind, timing); await activate(id) - if (kind === "at") { - // Creation and activation may take longer than the actual wake delay. - timing.at = Date.now() + delayMs - const before = snapshot(id).document - const { roots: _roots, profileID: _profileID, executionHost: _host, ...configuration } = before.configuration - await http(`/${id}/schedule`, { requestID: `configure_${randomUUID().replaceAll("-", "")}`, expectedRevision: before.revision, - action: "configure", configuration: { ...configuration, launch: { ...configuration.launch, timing } } }) - } - result.stage = "play" - await control(id, "play") - const armed = snapshot(id), principal = armed.schedules.find(item => item.role === "principal"), auxiliary = armed.schedules.find(item => item.role === "reconciliation") - assert(armed.document.calendarOwner.auxiliaryReady && !armed.document.calendarOwner.operation.pending) - assert(auxiliary?.status === "active" && principal?.status === "active") - learnTechnical(armed) - assert(technicalRows().every(item => item.sessionPresent && item.schedulePresent && item.reverseIndexPresent)) - assert.equal(armed.document.calendarOwner.slots[0].role, "reconciliation") - assert.equal(calls.length, 0); assert(principal.next_due_at >= Date.now() + 6000, "Insufficient real due-time headroom") - result.documentID = id; result.guardIDs = { pausedID, stoppedID }; result.dueAt = principal.next_due_at - await save("armed", armed) - if (values["arm-only"]) { - result.arming = { pausedCreation: true, activationReady: armed.document.scheduleActivation?.state === "ready", auxiliaryReady: true, - auxiliaryScheduleID: auxiliary.id, principalScheduleID: principal.id, providerRequests: calls.length, - installation: armed.document.calendarOwner.installation, noBusinessAdmission: armed.document.pending === null && armed.document.launchedCount === 0 } - assert(result.arming.activationReady && result.arming.noBusinessAdmission) - result.status = "passed" - return result // finally closes backend/leases/bridge and waits for every owned child. - } - await closeBackend(); if (!values.live) await stop() - result.initialWakeMode = values.live ? "live-same-process" : "cold-restart" - assert(Date.now() < principal.next_due_at, "Natural due must remain in the future when closing the backend") - result.noClientWindowStartedAt = Date.now() - await delay(Math.max(0, principal.next_due_at - Date.now()) + 250) - result.stage = values.live ? "natural-live-first-admission" : "natural-cold-first-admission" - if (!values.live) await launch(true) // Cold startup is registration-read-only; live keeps the original process. - if (values["first-admission-race"]) { - result.stage = "first-original-admission-held" - const held = await until(() => { - const state = snapshot(id), pending = state.document.pending - const beforeACK = heldOriginal && pending?.admissionAttempted && pending.admittedAt === null && state.document.launchedCount === 0 && state.start.length === 0 && state.inboxCount === 0 - const admittedFallback = !heldOriginal && pendingHandoff && pending?.admittedAt != null && state.document.launchedCount === 1 && state.start.length === 1 && providerOpen.size > 0 - return state.sessions.length === 1 && (beforeACK || admittedFallback) ? state : false - }) - const relay = heldOriginal ?? pendingHandoff, beforeACK = !!heldOriginal - const pending = held.document.pending, original = pending.origin.wakes[0] - const mapped = held.document.calendars.find(item => item.scheduleID === original.scheduleID) - const actualWake = { missionID: id, generation: mapped.timeGeneration, sessionID: mapped.sessionID, scheduleID: original.scheduleID, run: original.run, messageID: original.messageID } - assert(mapped.highWater >= original.run, "The genuine first wake must already be consumed durably") - assert.equal(relay.sessionID, pending.coordinatorSessionID) - if (beforeACK) { assert.equal(relay.messageID, pending.messageID); assert.equal(relay.document.passageID, pending.id) } - assert.deepEqual(relay.request.wake, actualWake); assert.deepEqual(relay.request.incarnation, readNativeScheduleIncarnation(registrationFile)) - if (relay.request.preflight?.signature) secrets.add(relay.request.preflight.signature) - assert(Date.now() - relay.request.preflight.issuedAt < 5000, "Insufficient genuine preflight headroom") - result.noClientFirstAdmissionHeldAt = Date.now(); await save("first-admission-held", held) - const started = Date.now(), abort = new AbortController(), timer = setTimeout(() => { abort.abort(); releaseBarrier("race-budget-expired") }, 2000) - let after - try { - await connect(abort.signal) - const expectedKey = nativeScheduleWakeKey(actualWake) - const outcomes = await Promise.allSettled(Array.from({ length: 8 }, () => client.rpc(NativeScheduleTransportRpc) - .wake(structuredClone(relay.request), { location: { directory: project }, signal: abort.signal }))) - result.firstAdmissionRace = { coverage: beforeACK ? "native original already reserved and in-flight before inbox/ACK; not simultaneous reservation CAS" : "authorized fallback: original already admitted, same pending and provider HTTP held; not pre-admission concurrency", - preAdmissionBarrierEngaged: beforeACK, - pendingID: pending.id, rootID: pending.coordinatorSessionID, originalMessageID: pending.messageID, highWater: mapped.highWater, - preflightCapturedFromActualProductDispatch: true, before: { count: held.document.launchedCount, roots: held.sessions.length, startMessages: held.start.length, inbox: held.inboxCount }, - outcomes: outcomes.map(entry => entry.status === "fulfilled" ? { status: entry.status, key: entry.value.key, state: entry.value.state } - : { status: entry.status, type: entry.reason?.type ?? entry.reason?.reason?.type ?? entry.reason?._tag ?? "unclassified" }), elapsedMs: Date.now() - started } - assert((beforeACK ? !heldOriginal.releasedAt : holdBusiness && providerOpen.size > 0) && Date.now() - started < 2000, "The measured original phase must remain held throughout the bounded race") - assert(outcomes.every(entry => entry.status === "fulfilled" && entry.value.key === expectedKey && entry.value.state === "applied"), "Every consumed-path replay must return its exact typed applied reply") - after = snapshot(id) - assert.equal(after.document.pending.id, pending.id); if (beforeACK) assert.equal(after.document.revision, held.document.revision) - assert.equal(after.document.launchedCount, held.document.launchedCount); assert.deepEqual(after.sessions, held.sessions); assert.deepEqual(after.start, held.start); assert.equal(after.inboxCount, held.inboxCount) - } finally { clearTimeout(timer); releaseBarrier("race-finished") } - result.firstAdmissionRace.heldMs = (heldOriginal?.releasedAt ?? Date.now()) - relay.enteredAt - result.firstAdmissionRace.releaseReason = heldOriginal?.releaseReason ?? "provider-remains-held" - await save("first-admission-race", { ...result.firstAdmissionRace, after }) - } - const positive = await until(() => { - const state = snapshot(id), pending = state.document.pending - return state.document.launchedCount === 1 && state.start.length === 1 && pending?.admittedAt != null - && state.schedules.filter(item => item.role === "principal").every(item => item.status !== "active") ? state : false - }) - assert.equal(positive.sessions.length, 1); assert.equal(positive.sessions[0].id, positive.document.pending.coordinatorSessionID) - assert.equal(positive.start[0].id, positive.document.pending.messageID) - if (values["existing-coordinator"]) { - const existing = result.existingCoordinators.find(item => item.missionID === id) - assert.equal(positive.document.pending.coordinatorSessionID, existing.id) - assert.equal(positive.document.pending.coordinatorReused, true) - assert(positive.document.pending.coordinatorBaseline.some(row => row[0] === existing.id)) - const adopted = readSQL(db => db.prepare("SELECT title,metadata,agent FROM session_v2 WHERE id=?").get(existing.id)) - assert.equal(adopted.title, existing.title); assert.equal(JSON.parse(adopted.metadata).unrelated, "preserve") - assert.equal(adopted.agent, "fixture-worker") - result.existingCoordinatorAdopted = true - } - if (values["convert-preparation"]) { - assert.deepEqual(positive.document.pending.configuration.launch.timing, timing) - assert.equal(positive.document.pending.configurationGeneration, armed.document.configurationGeneration) - assert.equal(positive.document.pending.timeGeneration, armed.document.timeGeneration) - assert.notEqual(positive.document.pending.coordinatorSessionID, armed.document.oneTime.coordinatorSessionID) - result.firstAdmissionUsesConvertedPolicy = true - } - await until(() => calls.some(call => call.sessionID === positive.document.pending.coordinatorSessionID)) - assert(positive.schedules.some(item => item.role === "reconciliation" && item.status === "active"), "Last pending passage requires its live auxiliary") - for (const guardID of [pausedID, stoppedID]) { const guard = snapshot(guardID); assert.equal(guard.document.launchedCount, 0); assert.equal(guard.sessions.length, 0) } - if (values.live) { assert.equal(result.serviceStarts.length, 1); assert.equal(child.pid, result.serviceStarts[0].pid); result.naturalLivePositiveAt = Date.now() } - else result.naturalColdPositiveAt = Date.now() - result.admittedPositiveBeforeAnyExternalClient = !values["first-admission-race"] - await save(values.live ? "natural-live-positive" : "natural-cold-positive", positive) - const pending = positive.document.pending, originalWake = pending.origin.wakes[0], calendar = positive.document.calendars.find(item => item.scheduleID === originalWake.scheduleID) - const wake = { missionID: id, generation: calendar.timeGeneration, sessionID: calendar.sessionID, scheduleID: originalWake.scheduleID, run: originalWake.run, messageID: originalWake.messageID } - result.stage = "business-report" - if (values["crash-pending"]) { - result.stage = "crash-pending-provider-held" - const beforeCrash = await until(() => { - const state = snapshot(id), claim = state.claims.find(item => item.id === pending.coordinatorSessionID) - return state.document.pending?.id === pending.id && state.document.launchedCount === 1 && state.start.length === 1 - && Number.isSafeInteger(claim?.time_suspended) && claim.time_suspended > 0 && providerOpen.size > 0 ? state : false - }) - assert(!reported.has(pending.coordinatorSessionID)); assert(holdBusiness) - await save("before-pending-crash", beforeCrash) - const killedPID = child.pid, owned = children.find(entry => entry.child === child) - child.kill("SIGKILL"); await owned.closed; client = undefined; endpoint = undefined - for (const deadline = Date.now() + 5000; providerOpen.size > 0;) { assert(Date.now() < deadline, "Killed provider connection did not close"); await delay(10) } - assert(!reported.has(pending.coordinatorSessionID), "The disconnected original HTTP handler must not emit a report") - const afterKill = snapshot(id) - assert.equal(afterKill.document.pending.id, pending.id); assert.equal(afterKill.document.launchedCount, 1) - assert.deepEqual(afterKill.start, beforeCrash.start); assert.deepEqual(afterKill.sessions, beforeCrash.sessions) - assert.deepEqual(afterKill.claims, beforeCrash.claims, "Hard kill must preserve the actual durable native claim") - await save("after-pending-hard-kill", afterKill) - result.crashPending = { killedPID, hardKill: true, originalHandlerClosedWithoutReport: true, oldClaimRetained: true, - pendingID: pending.id, rootID: pending.coordinatorSessionID, originalMessageID: pending.messageID, noClientRecoveryWindowStartedAt: Date.now() } - holdBusiness = false; for (const release of releases) release(); releases.clear() - result.stage = "cold-pending-execution-recovery-no-client" - await launch(true) - const recovered = await until(async () => { - const state = snapshot(id) - assert.equal(state.document.launchedCount, 1); assert.deepEqual(state.sessions, beforeCrash.sessions) - assert.equal(state.start.filter(message => message.id === pending.messageID).length, 1) - const terminal = readSQL(db => { - const rows = db.prepare("SELECT id,type,data FROM session_message WHERE session_id=? AND type IN ('assistant','idle') ORDER BY seq DESC LIMIT 64").all(pending.coordinatorSessionID) - const report = rows.filter(row => row.type === "assistant").flatMap(row => JSON.parse(row.data).content ?? []).find(part => part.type === "tool" && part.name === "mission_report" && part.state?.status === "completed") - const idle = rows.find(row => row.type === "idle") - return { report: !!report, idle: idle && { id: idle.id, outcome: JSON.parse(idle.data).outcome } } - }) - if (!terminal.report || terminal.idle?.outcome !== "succeeded") return false - const business = await missionDocumentPassage(readOnlyStorage, positive.document, () => true).journal.snapshot() - return business.missions[0]?.status === "completed" ? { state, terminal, businessStatus: "completed" } : false - }) - const messages = recovered.state.startDetails.map(message => ({ ...message, - classification: message.id === pending.messageID ? "missions-original" : !message.missionDocument && message.type === "synthetic" ? "native-recovery-unmarked-synthetic" : "unclassified-continuation" })) - assert.equal(messages.filter(message => message.classification === "missions-original").length, 1) - assert(!messages.some(message => message.id !== pending.messageID && message.missionDocument), "An extra Missions-origin start requires investigation") - assert(recovered.state.schedules.some(item => item.role === "reconciliation" && item.status === "active")) - result.crashPending.recoveredBeforeAnyClient = true; result.crashPending.recoveredAt = Date.now(); result.crashPending.messages = messages - await save("cold-pending-recovered", { ...recovered, messages }) - } else { holdBusiness = false; for (const release of releases) release(); releases.clear() } - await until(() => readSQL(db => db.prepare("SELECT 1 AS idle FROM session_message WHERE session_id=? AND type='idle' AND json_extract(data,'$.outcome')='succeeded' LIMIT 1").get(pending.coordinatorSessionID))) - const business = await missionDocumentPassage(readOnlyStorage, positive.document, () => true).journal.snapshot() - assert.equal(business.missions[0]?.status, "completed"); result.businessFinalReport = true - const completedStarts = snapshot(id).start - result.stage = "second-cold-reboot" - await stop(); await launch(true); await delay(8000) - const rebooted = snapshot(id); assert.equal(rebooted.document.launchedCount, 1); assert.deepEqual(rebooted.start, completedStarts); assert.deepEqual(rebooted.sessions, positive.sessions) - await save("second-cold-reboot", rebooted) - // Natural no-client proof is already saved. Authenticated exact replay is a - // separate mutation-dedupe stage, using a genuine native persisted wake. - await connect() - const beforeMaintenance = snapshot(id) - if (values["controlled-settlement"]) { - result.stage = "controlled-auxiliary-settlement" - const auxiliaryDue = beforeMaintenance.schedules.find(item => item.role === "reconciliation" && item.status === "active")?.next_due_at - if (beforeMaintenance.document.pending) { - assert(Number.isSafeInteger(auxiliaryDue)) - const definition = { id: "codenomad.schedule-clock-qualification", methods: { tick: { input: { type: "object" }, output: { type: "object" } } }, events: {} } - await client.rpc(definition).tick({ at: auxiliaryDue + 1 }, { location: { directory: project }, signal: AbortSignal.timeout(20000) }) - } - const settled = await until(() => { const state = snapshot(id); return state.document.pending === null && state.document.settledCount === 1 ? state : false }) - assert.equal(settled.document.history[0].outcome, "completed"); assert.equal(settled.document.launchedCount, 1) - result.controlledSettlement = { usedNativeEffectClockOnly: !!beforeMaintenance.document.pending, osClockUnchanged: true }; await save("controlled-settled", settled) - result.stage = "after-idle-maintenance" - // No fixture maintenance call and no replay may perform this cleanup. - // Observe the real terminal hint -> fixed product HTTP RPC -> exact row removal. - const afterIdle = await until(async () => { - const rows = technicalRows(), events = await maintenanceEvents(), settledAt = settled.document.history[0].settledAt - const terminal = events.find(event => event.kind === "terminal" && event.sessionID === auxiliary.session_id && event.at >= settledAt) - const request = terminal && events.find(event => event.kind === "maintenance-http-request" && event.sessionID === auxiliary.session_id - && event.pid === terminal.pid && event.at >= terminal.at) - const response = request && events.find(event => event.kind === "maintenance-http-response" && event.requestID === request.requestID - && event.pid === request.pid && event.status === 200) - return terminal && request && response && rows.every(item => !item.sessionPresent && !item.schedulePresent && !item.reverseIndexPresent) - ? { rows, terminal, request, response, observedAt: Date.now() } : false - }) - result.afterIdleMaintenance = true; await save("after-idle-maintenance", afterIdle) - } else result.settlementGate = "Natural auxiliary settlement may require up to 15 minutes; use separate --controlled-settlement qualification" - result.stage = "after-purge-replay" - const payload = { wake, registrationFile, incarnation: readNativeScheduleIncarnation(registrationFile) } - const replay = await Promise.allSettled(Array.from({ length: 8 }, () => client.rpc(NativeScheduleTransportRpc).wake(payload, { location: { directory: project }, signal: AbortSignal.timeout(15000) }))) - result.concurrentReplay = replay.map(entry => entry.status === "fulfilled" ? { status: entry.status, state: entry.value.state } : { status: entry.status }) - const deduped = snapshot(id); assert.equal(deduped.document.launchedCount, 1); assert.deepEqual(deduped.start, completedStarts) - result.calls = calls; result.status = "passed"; result.stage = "completed" - } catch (error) { - result.status = "failed" - qualificationError = error - const failureAt = Date.now(), cold = result.stage === "natural-cold-first-admission" - let coldFailure, privateEvidenceAvailable = credentialsChild === child && !!child - if (cold) { - try { - const collected = await collectColdFailure({ status: result.status, stage: result.stage, failureAt, - root, registrationFile, databaseFile, documentID: result.documentID, prefix, secrets: [...secrets], - onSecrets: learned => { for (const secret of learned) secrets.add(secret); privateEvidenceAvailable = true }, - child, expected: result.serviceStarts.at(-1), diagnostic: { stage: result.stage, nativeErrorTruncated, - error: { message: error?.message === "bounded-product-qualification-deadline" ? error.message : "private-text-omitted" } } }) - coldFailure = collected?.evidence ?? { error: collected?.error ?? "cold-failure-diagnostic-unavailable" } - if (collected?.saveError) result.storageError = "diagnostic-save-unavailable" - } catch { coldFailure = { error: "cold-failure-diagnostic-unavailable" } } - } - const detail = item => item && "private-text-omitted" - result.status = "failed"; result.error = error?.message === "bounded-product-qualification-deadline" ? error.message : "private-text-omitted" - if (!cold) try { - const diagnostic = { stage: result.stage, failureAt, error: detail(error), reason: detail(error?.reason), cause: detail(error?.cause), - nativeErrorTail: "private-text-omitted", nativeErrorTruncated, coldFailure } - const json = JSON.stringify(diagnostic) - await save("failure-diagnostic", Buffer.byteLength(json) <= 512 * 1024 ? diagnostic : { stage: result.stage, failureAt, error: "failure-diagnostic-overflow" }) - } catch { result.storageError = "diagnostic-save-unavailable" } - if (!cold && privateEvidenceAvailable && result.documentID) try { - const state = projectFailureSQL(snapshot(result.documentID, true)) - state.maintenance = await maintenanceEvents().then(events => ({ count: events.length }), - () => ({ error: "maintenance-events-unavailable" })) - const json = JSON.stringify(state) - await writeFile(path.join(root, "failure-sql.json"), Buffer.byteLength(json) <= 512 * 1024 ? json : '{"error":"failure-sql-bound"}') - } catch { result.storageError = "sql-save-unavailable" } - throw error - } - finally { - let cleanupError - try { - releaseBarrier("fixture-finally") - holdBusiness = false; for (const release of releases) release(); releases.clear() - await closeBackend() - } catch (error) { cleanupError = error; result.cleanupError = "backend-cleanup-failed" } - try { - const stopped = await Promise.allSettled(children.map(entry => entry.child.exitCode === null && entry.child.signalCode === null ? stopFixtureChild(entry.child, entry.closed) : entry.closed)) - provider.closeAllConnections(); await new Promise(resolve => provider.close(resolve)) - barrier.closeAllConnections(); if (barrier.listening) await new Promise(resolve => barrier.close(resolve)) - result.calls = calls - result.allOwnedServicesStopped = stopped.every(entry => entry.status === "fulfilled") - assert(result.allOwnedServicesStopped, "An owned native process failed cleanup") - } catch (error) { cleanupError ??= error; result.cleanupError = "owned-cleanup-failed" } - if (cleanupError) result.status = "failed" - try { await save("receipt", result) } - catch (error) { result.status = "failed"; result.storageError = "receipt-save-unavailable"; if (!qualificationError && !cleanupError) throw error } - if (!qualificationError && cleanupError) throw cleanupError - } -} - -let qualificationError -try { for (const kind of kinds) await journey(kind); receipt.outcome = values["diagnose-stop"] || values["diagnose-product-stop"] ? "diagnostic-only" : "passed" } -catch (error) { qualificationError = error; receipt.outcome = "failed" } -finally { - for (const name of Object.keys(process.env)) if (!(name in originalEnvironment)) delete process.env[name] - Object.assign(process.env, originalEnvironment) - try { await writeFile(path.join(scratch, "receipt.json"), JSON.stringify(receipt, null, 2)) } - catch (error) { qualificationError ??= error; receipt.outcome = "failed"; receipt.storageError = "receipt-save-unavailable" } -} -if (qualificationError) { console.error("Native product qualification failed; see receipt"); process.exitCode = 1 } diff --git a/scripts/test-native-schedule-context.mjs b/scripts/test-native-schedule-context.mjs deleted file mode 100644 index d58d6e9060..0000000000 --- a/scripts/test-native-schedule-context.mjs +++ /dev/null @@ -1,53 +0,0 @@ -import assert from "node:assert/strict" -import { readFile, mkdir, writeFile } from "node:fs/promises" -import path from "node:path" -import { DatabaseSync } from "node:sqlite" -import { setTimeout as delay } from "node:timers/promises" -import { withProductRuntime } from "./native-product-fixture.mjs" -import { fixtureCliVersion } from "./native-fixture-cli-version.mjs" - -const cli = process.argv[2], version = await fixtureCliVersion(cli) -await withProductRuntime(cli, async ({ root }) => { - const plugin = path.join(root, "observer") - await mkdir(plugin) - await writeFile(path.join(plugin, "package.json"), JSON.stringify({ name: "schedule-context-observer", type: "module", exports: "./index.mjs" })) - await writeFile(path.join(plugin, "index.mjs"), ` - import { Plugin } from "@opencode/plugin/effect" - import { Effect } from "effect" - import { appendFileSync } from "node:fs" - export default Plugin.define({ id: "fixture.schedule-context", effect: ctx => Effect.gen(function* () { - yield* ctx.session.hook("context", event => Effect.sync(() => appendFileSync(${JSON.stringify(path.join(root, "context.jsonl"))}, - JSON.stringify({ sessionID: event.sessionID, messages: event.messages.map(({ id, role, metadata }) => ({ id, role, metadata })) }) + "\\n"))) - }) }) - `) - return { experimental: { schedules: true }, plugins: [plugin] } -}, async ({ client, root }) => { - assert.equal((await client.server.info()).version, version) - const session = await client.session.create({ title: "Schedule context contract", location: { directory: root } }) - const schedule = await client.experimental.schedule.create({ sessionID: session.id, - when: { at: new Date(Date.now() + 2000).toISOString() }, prompt: "FIXTURE_SCHEDULE_WAKE" }) - const id = `msg_${schedule.id}_1` - let context - for (const end = Date.now() + 20000; Date.now() < end;) { - const lines = await readFile(path.join(root, "context.jsonl"), "utf8").catch(() => "") - context = lines.trim().split("\n").filter(Boolean).map(JSON.parse).find(event => event.messages.some(message => message.id === id)) - if (context) break - await delay(50) - } - assert(context, "The native scheduled input retains its ID in context") - const db = new DatabaseSync(path.join(root, "fixture.db"), { readOnly: true }) - let stored - try { stored = db.prepare("SELECT id,type,data FROM session_message WHERE id=? AND session_id=?").get(id, session.id) } finally { db.close() } - assert.equal(stored.type, "user") - const metadata = JSON.parse(stored.data).metadata.schedule - assert.equal(metadata.id, schedule.id); assert.equal(metadata.run, 1) - assert(Number.isSafeInteger(metadata.dueAt) && metadata.dueAt >= 0) - assert.equal(typeof metadata.late, "boolean") - assert.equal(JSON.parse(stored.data).text, "FIXTURE_SCHEDULE_WAKE") - const projected = context.messages.find(message => message.id === id) - assert.equal(projected.role, "user") - if (projected.metadata?.schedule) assert.deepEqual(projected.metadata.schedule, metadata) - const result = { version, context: projected, stored: { id: stored.id, type: stored.type, schedule: metadata } } - await writeFile(path.join(root, "schedule-context-proof.json"), JSON.stringify(result, null, 2)) - console.log(JSON.stringify(result)) -}, { service: true }) diff --git a/scripts/test-native-schedule-foundation.mjs b/scripts/test-native-schedule-foundation.mjs deleted file mode 100644 index 0cc90c913c..0000000000 --- a/scripts/test-native-schedule-foundation.mjs +++ /dev/null @@ -1,343 +0,0 @@ -import assert from "node:assert/strict" -import { spawn } from "node:child_process" -import { createServer } from "node:http" -import { createHash, randomBytes } from "node:crypto" -import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs" -import path from "node:path" -import { pathToFileURL } from "node:url" -import { setTimeout as sleep } from "node:timers/promises" -import { OpenCode } from "@opencode/client" -import { Service } from "@opencode/client/service" -import { buildNativeScheduleFoundation } from "../packages/server/scripts/build-native-schedule-foundation.mjs" -import { fixtureCliVersion } from "./native-fixture-cli-version.mjs" - -const [cli, root] = process.argv.slice(2) -const statusOnly = process.argv.includes("--status-only") -const coldMissing = process.argv.find(value => value.startsWith("--cold-missing="))?.split("=")[1] -const controlledMaintenance = process.argv.includes("--controlled-maintenance") -assert(!coldMissing || ["runtime", "provider"].includes(coldMissing), "cold missing artifact must be runtime or provider") -assert([statusOnly, !!coldMissing, controlledMaintenance].filter(Boolean).length <= 1, "choose one qualification mode") -assert(cli && path.isAbsolute(cli) && root && path.isAbsolute(root), "absolute isolated CLI and fresh scratch directory required") -const cliVersion = await fixtureCliVersion(cli) -assert(!existsSync(root), "Preserve existing evidence; use a fresh scratch child") -mkdirSync(root, { recursive: true }) -if (process.env.GITHUB_ENV) appendFileSync(process.env.GITHUB_ENV, `NATIVE_SCHEDULE_FOUNDATION_FIXTURE=${root}\n`) -const save = (name, value) => { writeFileSync(path.join(root, `${name}.json`), JSON.stringify(value, null, 2)); return value } -const log = event => appendFileSync(path.join(root, "harness.jsonl"), JSON.stringify({ at: Date.now(), ...event }) + "\n") -const eventsFile = path.join(root, "native.jsonl") -const events = () => existsSync(eventsFile) ? readFileSync(eventsFile, "utf8").trim().split("\n").filter(Boolean).map(JSON.parse) : [] -const env = {} -for (const key of ["SystemRoot", "WINDIR", "ComSpec", "PATHEXT"]) if (process.env[key]) env[key] = process.env[key] -for (const role of ["CONFIG", "STATE", "DATA", "CACHE"]) env[`XDG_${role}_HOME`] = path.join(root, role.toLowerCase()) -Object.assign(env, { XDG_RUNTIME_DIR: path.join(root, "runtime"), HOME: path.join(root, "home"), USERPROFILE: path.join(root, "home"), - APPDATA: path.join(root, "appdata"), LOCALAPPDATA: path.join(root, "localappdata"), ProgramData: path.join(root, "programdata"), - TEMP: path.join(root, "tmp"), TMP: path.join(root, "tmp"), PATH: "C:\\Windows\\System32;C:\\Program Files\\Git\\cmd", - OPENCODE_CONFIG_PROJECT_DISABLE: "1", OPENCODE_TEST_HOME: path.join(root, "home"), OPENCODE_DB: path.join(root, "fixture.db"), - OPENCODE_DISABLE_CLAUDE_CODE: "true", OPENCODE_DISABLE_MODELS_FETCH: "true", - OPENCODE_DISABLE_FILEWATCHER: "true", OPENCODE_DISABLE_FFF: "true", OPENCODE_LOG_LEVEL: "DEBUG" }) -for (const [key, value] of Object.entries(env)) - if (key.startsWith("XDG_") || ["HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "ProgramData", "TEMP", "TMP"].includes(key)) - mkdirSync(value, { recursive: true }) -const project = path.join(root, "project"), configRoot = path.join(env.XDG_CONFIG_HOME, "opencode") -mkdirSync(project); mkdirSync(configRoot, { recursive: true }) -const registrationFile = path.join(env.XDG_STATE_HOME, "opencode", "service.json") -const providerRequests = [] -const spy = createServer(async (req, res) => { providerRequests.push({ method: req.method, path: req.url }); res.writeHead(500).end("Provider HTTP forbidden") }) -await new Promise(resolve => spy.listen(0, "127.0.0.1", resolve)) -const spyPort = spy.address().port -assert.notEqual(spyPort, 28894) -const portServer = createServer() -await new Promise(resolve => portServer.listen(0, "127.0.0.1", resolve)) -const port = portServer.address().port -await new Promise(resolve => portServer.close(resolve)) -assert.notEqual(port, 28894) -const owned = [] -let current, client, endpoint -const wait = async (predicate, timeout = 30_000) => { - const deadline = Date.now() + timeout - while (Date.now() < deadline) { - if (await predicate()) return - if (current?.exitCode !== null && current?.exitCode !== undefined) throw new Error("Isolated service exited") - await sleep(100) - } - throw new Error("Bounded native qualification wait expired") -} -const stop = async child => { - if (!child || child.exitCode !== null || child.signalCode !== null) return - child.kill("SIGKILL") - await new Promise(resolve => child.once("exit", resolve)) -} -const launch = async label => { - const child = spawn(cli, ["serve", "--service", "--hostname", "127.0.0.1", "--port", String(port)], - { cwd: project, env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }) - owned.push(child); current = child - const output = { stdout: "", stderr: "" } - child.stdout.on("data", value => { output.stdout += value }) - child.stderr.on("data", value => { output.stderr += value }) - child.once("exit", () => { - writeFileSync(path.join(root, `${label}-stdout.txt`), output.stdout) - writeFileSync(path.join(root, `${label}-stderr.txt`), output.stderr) - }) - await wait(async () => { - if (!existsSync(registrationFile)) return false - const registration = JSON.parse(readFileSync(registrationFile)) - if (registration.pid !== child.pid) return false - endpoint = await Service.discover({ file: registrationFile, version: cliVersion }) - return !!endpoint - }) - assert.equal(endpoint.url, `http://127.0.0.1:${port}`) - const { id, pid, url, version } = JSON.parse(readFileSync(registrationFile)) - save(label, { id, pid, url, version }) - client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }) - return { id, pid, url, version } -} -const definition = { id: "codenomad.schedule-qualification", methods: Object.fromEntries( - ["initialize", "snapshot", "forceTitle", "ordinary", "replay", "claimOnly"].map(name => [name, { input: { type: "object" }, output: { type: "object" } }])), events: {} } -const qa = (name, input = {}) => client.rpc(definition)[name](input, { location: { directory: project }, signal: AbortSignal.timeout(20_000) }) -const observerDefinition = { id: "codenomad.schedule-clock-qualification", methods: { - tick: { input: { type: "object" }, output: { type: "object" } }, snapshot: { input: { type: "object" }, output: { type: "object" } }, -}, events: {} } -const observe = (name, input) => client.rpc(observerDefinition)[name](input, { location: { directory: project }, signal: AbortSignal.timeout(20_000) }) -let artifacts, principal, reconciliation, principalSchedule, reconciliationSchedule -try { - artifacts = await buildNativeScheduleFoundation(path.join(root, "artifacts"), { qualification: true }) - const config = { "$schema": "https://opencode.ai/config.json", snapshots: false, update: "disable", experimental: { schedules: true }, - plugins: [{ package: path.dirname(artifacts.qualification.file), options: { registrationFile, provider: artifacts.provider, - runtime: artifacts.qualification, logFile: eventsFile, loseFirstReply: !coldMissing && !controlledMaintenance, - holdCompaction: controlledMaintenance } }, - ...(coldMissing || controlledMaintenance ? [{ package: path.dirname(artifacts.observer.file) }] : [])], - model: "codenomad-missions-local/schedule-noop", agents: { title: { model: "remote-aux/forbidden" }, compaction: { model: "remote-aux/forbidden" } }, - providers: { - "codenomad-missions-local": { name: "Owned local carrier", package: `aisdk:${pathToFileURL(artifacts.provider.file).href}`, - models: { "schedule-noop": { limit: { context: 32000, output: 4096 } } } }, - "remote-aux": { name: "Forbidden auxiliary network", package: "@opencode/ai/providers/openai-compatible", - settings: { baseURL: `http://127.0.0.1:${spyPort}/v1`, apiKey: "fixture-only" }, models: { forbidden: { limit: { context: 32000, output: 4096 } } } }, - } } - writeFileSync(path.join(configRoot, "opencode.json"), JSON.stringify(config)) - writeFileSync(path.join(configRoot, "service.json"), JSON.stringify({ hostname: "127.0.0.1", port, disabled: false })) - save("isolation", { cli, cliSHA256: createHash("sha256").update(readFileSync(cli)).digest("hex"), root, project, port, spyPort, - backend: "absent", sharedServiceAccess: "none", environmentKeys: Object.keys(env), artifacts, - nativeIntervalMinutes: controlledMaintenance ? 90 : 1, productIntervalMinutes: 90, coldMissing, controlledMaintenance, - scope: "reconciliation without passage; product mapping owner absent" }) - await launch("first-incarnation") - const model = { providerID: "codenomad-missions-local", id: "schedule-noop" } - const create = role => client.session.create({ title: "Mission schedule carrier", location: { directory: project }, model, - metadata: { "codenomad.schedule-carrier": { missionID: "native_foundation", timeGeneration: 1, role, slot: 0 } } }) - principal = await create("principal") - if (coldMissing || controlledMaintenance) { - const now = Date.now(), info = { ...principal, id: `ses_qualification_${randomBytes(12).toString("hex")}`, - metadata: { "codenomad.schedule-carrier": { missionID: "native_foundation", timeGeneration: 1, role: "reconciliation", slot: 0 } }, - agent: "build", outcome: "succeeded", time: { created: now - 10, updated: now, idle: now }, title: "Mission schedule carrier" } - const seedText = "Native bounded carrier history for automatic compaction. ".repeat(3000) - const tokenFixture = { input: 40000, output: 4, reasoning: 0, cache: { read: 0, write: 0 } } - reconciliation = await client.experimental.session.import({ location: { directory: project }, info, messages: [ - { id: "msg_qualification_seed_user", type: "user", time: { created: now - 6 }, text: seedText }, - { id: "msg_qualification_seed_assistant", type: "assistant", time: { created: now - 5, completed: now - 4 }, agent: "build", model, - content: [{ type: "text", text: "Seed history complete." }], cost: 0, tokens: tokenFixture, finish: "stop" }, - { id: "msg_qualification_seed_idle", type: "idle", time: { created: now - 3 }, outcome: "succeeded" }, - ] }) - save("seed-history", { method: "official native import before calendar arming; same technical identity retained thereafter", - sessionID: reconciliation.id, textCharacters: seedText.length, textSHA256: createHash("sha256").update(seedText).digest("hex"), - measuredTokensFixture: tokenFixture, contextLimit: 32000, automaticCompactionVerifiedByHealthyControl: controlledMaintenance }) - } else reconciliation = await create("reconciliation") - const signal = "CODENOMAD_MISSION_SCHEDULE_WAKE" - principalSchedule = await client.experimental.schedule.create({ sessionID: principal.id, when: { every: "90 minutes" }, - ends: { after: "91 minutes", times: 3 }, prompt: signal, name: "foundation-principal-phase" }) - reconciliationSchedule = await client.experimental.schedule.create({ sessionID: reconciliation.id, when: { every: controlledMaintenance ? "90 minutes" : "1 minute" }, - ends: controlledMaintenance ? { times: 3, after: "181 minutes" } : { times: 4 }, prompt: signal, name: "foundation-native-carrier-qualification" }) - if (controlledMaintenance) await client.experimental.schedule.pause({ scheduleID: principalSchedule.id }) - save("document-initial", await qa("initialize", { principal: { sessionID: principal.id, scheduleID: principalSchedule.id }, - reconciliation: { sessionID: reconciliation.id, scheduleID: reconciliationSchedule.id } })) - if (coldMissing) { - const initial = save("cold-before", await observe("snapshot", { sessionID: reconciliation.id, scheduleID: reconciliationSchedule.id })) - const nativeCount = events().length, firstPID = current.pid - await stop(current) - const artifact = coldMissing === "runtime" ? artifacts.qualification : artifacts.provider - renameSync(artifact.file, `${artifact.file}.held`) - const cold = await launch(`cold-missing-${coldMissing}`) - assert.notEqual(cold.pid, firstPID) - log({ kind: "cold-negative-no-project-client-start", pid: cold.pid, missing: coldMissing }) - // The original every:1-minute native schedule fires naturally. No tick RPC, - // prompt, context read or other project client warms the cold Location here. - await sleep(Math.max(0, reconciliationSchedule.nextDueAt - Date.now()) + 5000) - log({ kind: "cold-negative-no-project-client-end", pid: cold.pid, providerHTTP: providerRequests.length }) - const after = save("cold-after", await observe("snapshot", { sessionID: reconciliation.id, scheduleID: reconciliationSchedule.id })) - save("cold-plugin-diagnostics", await client.plugin.list({ location: { directory: project } })) - assert.equal(after.session.id, initial.session.id) - assert.equal(after.schedule.id, initial.schedule.id) - assert.equal(after.schedule.session_id, initial.schedule.session_id) - assert.equal(after.document.revision, initial.document.revision) - assert.equal(after.document.launchedCount, 0) - assert.equal(after.document.pending, null) - assert.equal(events().slice(nativeCount).filter(event => event.kind === "cas" || event.kind === "registered").length, 0) - const failures = after.messages.filter(message => message.type === "idle" && message.outcome === "failed") - assert(failures.length > 0, "missing artifact must fail the native technical turn") - assert.equal(providerRequests.length, 0, "cold missing hooks must not reach a remote auxiliary provider") - save("result", { completed: true, coldMissing, safeClosed: true, nativeNaturalWake: true, originalSessionAndSchedule: true, - providerHTTP: providerRequests.length, runtimeRegisteredAfterCold: false, failedTurns: failures, - documentRevisionUnchanged: true, launchedCount: 0, originalDueAt: initial.schedule.next_due_at, - nativeNextDueAt: after.schedule.next_due_at, seededHistoryStillPresent: after.messages.some(message => message.id === "msg_qualification_seed_user") }) - console.log(JSON.stringify({ completed: true, coldMissing, providerHTTP: providerRequests.length, evidence: root })) - } else if (controlledMaintenance) { - const snapshot = () => observe("snapshot", { sessionID: reconciliation.id, scheduleID: reconciliationSchedule.id }) - const first = save("controlled-before", await snapshot()), firstDue = first.schedule.next_due_at - assert.equal(JSON.parse(first.schedule.when).every, "90 minutes") - save("controlled-tick-one", await observe("tick", { at: firstDue })) - await wait(() => events().some(event => event.kind === "compaction-held")) - const held = save("controlled-during-auto-compaction", await snapshot()) - assert(held.messages.some(message => message.type === "compaction" && message.reason === "auto" && message.status === "running")) - assert.equal(held.schedule.next_due_at, firstDue + 90 * 60_000) - assert.equal(held.schedule.run_count, 1) - assert.equal(held.schedule.remaining_runs, 2) - writeFileSync(path.join(root, "release-compaction"), "release only the fixture hook; preserve native identities") - await wait(() => events().some(event => event.kind === "cas" && event.run === 1)) - const compacted = save("controlled-after-auto-compaction", await snapshot()) - assert(compacted.messages.some(message => message.type === "compaction" && message.reason === "auto" && message.status === "completed")) - for (const key of ["id", "session_id", "when", "next_due_at", "ends_at", "remaining_runs", "run_count", "time_created", "time_updated"]) - assert.deepEqual(compacted.schedule[key], held.schedule[key], key) - await stop(current) - const cold = await launch("controlled-cold") - const restarted = save("controlled-after-cold", await snapshot()) - for (const key of ["id", "session_id", "when", "next_due_at", "ends_at", "remaining_runs", "run_count", "time_created", "time_updated"]) - assert.deepEqual(restarted.schedule[key], compacted.schedule[key], key) - save("controlled-tick-two", await observe("tick", { at: restarted.schedule.next_due_at })) - await wait(() => events().some(event => event.pid === cold.pid && event.kind === "cas" && event.run === 2)) - const final = save("controlled-final", await snapshot()) - assert.equal(final.session.id, first.session.id) - assert.equal(final.schedule.id, first.schedule.id) - assert.equal(final.schedule.run_count, 2) - assert.equal(final.schedule.remaining_runs, 1) - assert.equal(final.schedule.status, "done") // next 270-minute slot is beyond ends.at at 181 minutes. - assert.equal(final.schedule.ends_at, first.schedule.ends_at) - assert.equal(final.document.calendars.find(item => item.role === "reconciliation").highWater, 2) - assert.equal(final.document.launchedCount, 0) - assert.equal(providerRequests.length, 0) - save("result", { completed: true, controlledMaintenance: true, clock: "native Effect Clock on explicit tick only; OS clock unchanged", - sameCarrierEvery90Minutes: true, automaticCompaction: true, historyReallyOverCeiling: true, originalSessionAndSchedule: true, - phaseAndEndsPreservedDuringMaintenanceAndColdRestart: true, secondNativeSlotFinishedAtOriginalEnd: true, - highWater: 2, launchedCount: 0, providerHTTP: providerRequests.length }) - console.log(JSON.stringify({ completed: true, controlledMaintenance: true, evidence: root })) - } else if (statusOnly) { - const { id, pid, url, version } = JSON.parse(readFileSync(registrationFile)) - const wake = { missionID: "native_foundation", generation: 1, scheduleID: reconciliationSchedule.id, - sessionID: reconciliation.id, run: 1, messageID: `msg_${reconciliationSchedule.id}_1` } - const definition = { id: "codenomad.missions.schedule", methods: { status: { input: { type: "object" }, output: { type: "object" } } }, events: {} } - const status = () => client.rpc(definition).status({ wake, incarnation: { id, pid, url, version }, registrationFile }, { location: { directory: project } }) - const before = await qa("snapshot") - assert.equal((await status()).state, "unknown") - assert.equal((await qa("claimOnly", wake)).claimed, true) - assert.equal((await status()).state, "pending") - assert.equal((await qa("claimOnly", wake)).claimed, false) - assert.equal((await qa("snapshot")).revision, before.revision) - assert.equal(events().filter(event => event.kind === "rpc-wake" || event.kind === "cas").length, 0) - save("result", { completed: true, statusOnly: true, unknownBeforeClaim: true, pendingAfterClaim: true, - duplicateClaimRefused: true, documentRevisionUnchanged: true, wakeMutations: 0, providerHTTP: providerRequests.length }) - console.log(JSON.stringify({ completed: true, statusOnly: true, evidence: root })) - } else { - await wait(() => events().some(event => event.kind === "transport" && event.result.state === "uncertain"), 85_000) - const first = save("document-after-lost-ack", await qa("snapshot")) - assert.equal(first.calendars.find(item => item.role === "reconciliation").highWater, 1) - assert.equal(first.launchedCount, 0) - save("ordinary-guard", await qa("ordinary", { ownedCarrier: true, metadata: { schedule: { id: reconciliationSchedule.id, run: 2 } } })) - assert.deepEqual(await qa("ordinary", { ownedCarrier: true }), { allowed: false }) - let forgedRefused = false - try { await client.session.prompt({ sessionID: reconciliation.id, id: "msg_forged", text: signal, - metadata: { schedule: { id: reconciliationSchedule.id, run: 2, dueAt: Date.now(), late: false } } }) } catch { forgedRefused = true } - assert(forgedRefused) - save("forged-input", { refused: forgedRefused, boundary: "native prompt hook + separately invoked reusable ordinary guard" }) - await qa("forceTitle", { sessionID: reconciliation.id }) - const phaseBefore = save("phase-before-compaction", await client.experimental.schedule.get({ scheduleID: principalSchedule.id })) - const auxiliaryBefore = save("aux-before-compaction", await client.experimental.schedule.get({ scheduleID: reconciliationSchedule.id })) - await client.session.compact({ sessionID: reconciliation.id }) - await wait(async () => { - const result = await client.message.list({ sessionID: reconciliation.id, limit: 32 }) - return result.data.some(message => message.type === "compaction" && message.status === "completed") - }) - const phaseCompacted = save("phase-after-compaction", await client.experimental.schedule.get({ scheduleID: principalSchedule.id })) - const auxiliaryCompacted = save("aux-after-compaction", await client.experimental.schedule.get({ scheduleID: reconciliationSchedule.id })) - for (const key of ["id", "sessionID", "nextDueAt", "endsAt", "remainingRuns", "runCount"]) - assert.deepEqual(phaseCompacted[key], phaseBefore[key], key) - for (const key of ["id", "sessionID", "nextDueAt", "remainingRuns", "runCount"]) - assert.deepEqual(auxiliaryCompacted[key], auxiliaryBefore[key], key) - const firstPID = current.pid - await wait(() => events().some(event => event.pid === firstPID && event.kind === "cas" && event.run === 2), 75_000) - await wait(() => events().filter(event => event.pid === firstPID && event.kind === "local-stream").length >= 2) - const streams = events().filter(event => event.pid === firstPID && event.kind === "local-stream") - assert.equal(new Set(streams.map(event => event.token)).size, 1) - save("cached-language-two-occurrences", { pid: firstPID, streams: streams.length, languageObjects: 1 }) - const beforeCold = save("document-before-cold-restart", await qa("snapshot")) - assert.equal(beforeCold.calendars.find(item => item.role === "reconciliation").highWater, 2) - const oldPID = current.pid - await stop(current) - const cold = await launch("cold-incarnation") - assert.notEqual(cold.pid, oldPID) - // Only own local receipt files are observed here: zero project API requests, - // CodeNomad backend or external wake calls until the native schedule fires. - log({ kind: "no-project-client-window-start", pid: cold.pid }) - await wait(() => events().some(event => event.pid === cold.pid && event.kind === "cas" && event.run === 3), 85_000) - log({ kind: "no-project-client-window-end", pid: cold.pid }) - const second = save("document-after-cold-wake", await qa("snapshot")) - assert.equal(second.calendars.find(item => item.role === "reconciliation").highWater, 3) - assert.equal(second.launchedCount, 0) - assert.equal(second.pending, null) - const phaseCold = save("phase-after-cold-wake", await client.experimental.schedule.get({ scheduleID: principalSchedule.id })) - for (const key of ["id", "sessionID", "nextDueAt", "endsAt", "remainingRuns", "runCount"]) assert.deepEqual(phaseCold[key], phaseBefore[key], key) - const wake = { missionID: second.id, generation: second.timeGeneration, scheduleID: reconciliationSchedule.id, run: 1, - sessionID: reconciliation.id, messageID: `msg_${reconciliationSchedule.id}_1` } - const replay = save("old-wake-replay", await qa("replay", { wake, incarnation: cold, registrationFile })) - assert.equal(replay.state, "applied") - assert.equal((await qa("snapshot")).revision, second.revision) - // Disable auto-start while leaving this explicitly launched isolated daemon alive. - writeFileSync(path.join(configRoot, "service.json"), JSON.stringify({ hostname: "127.0.0.1", port, disabled: true })) - assert(await Service.discover({ file: registrationFile })) - save("disabled-live", { discovered: true, supervision: "absent", pid: cold.pid }) - // Artifact checks also fence an already cached local model. - renameSync(artifacts.provider.file, `${artifacts.provider.file}.held`) - let missingProviderRefused = false - try { await client.session.prompt({ sessionID: reconciliation.id, id: `msg_${reconciliationSchedule.id}_4`, text: signal, - metadata: { schedule: { id: reconciliationSchedule.id, run: 4, dueAt: Date.now(), late: false } } }) } catch { missingProviderRefused = true } - assert(missingProviderRefused) - renameSync(`${artifacts.provider.file}.held`, artifacts.provider.file) - assert.equal((await qa("snapshot")).revision, second.revision) - save("provider-absence", { refused: true, documentUnchanged: true, cachedModel: true }) - renameSync(artifacts.qualification.file, `${artifacts.qualification.file}.held`) - let missingBundleRefused = false - try { await client.session.prompt({ sessionID: reconciliation.id, id: `msg_${reconciliationSchedule.id}_4`, text: signal, - metadata: { schedule: { id: reconciliationSchedule.id, run: 4, dueAt: Date.now(), late: false } } }) } catch { missingBundleRefused = true } - renameSync(`${artifacts.qualification.file}.held`, artifacts.qualification.file) - assert(missingBundleRefused) - assert.equal((await qa("snapshot")).revision, second.revision) - save("bundle-absence", { refused: true, documentUnchanged: true, loadedRegistration: true }) - const observed = events() - assert.equal(observed.filter(event => event.kind === "cas").length, 3) - assert.equal(observed.filter(event => event.kind === "rpc-wake" && event.input.wake.run === 1).length, 2) // original + explicit QA replay - assert(observed.some(event => event.kind === "title-result" && event.model.providerID === "remote-aux" && event.local)) - assert(observed.some(event => event.kind === "compaction-result" && event.model.providerID === "remote-aux" && event.local)) - assert(observed.filter(event => event.kind === "language-cache").every(event => event.same)) - assert.equal(observed.filter(event => ["provider-http-hook", "forbidden-lifecycle", "forbidden-child", "forbidden-signal"].includes(event.kind)).length, 0) - assert.equal(providerRequests.length, 0) - save("result", { completed: true, nativeVersion: cliVersion, casCount: 3, highWater: 3, launchedCount: 0, - coldWakeWithoutProjectClient: true, lostACKNoAutomaticResend: true, forcedCompaction: true, - remoteTitleAndCompactionLocal: true, providerHTTP: providerRequests.length, forbiddenWakeOperations: 0, - productInstalledRegistration: false, coreBusinessAdmissionQualified: false }) - console.log(JSON.stringify({ completed: true, evidence: root, providerHTTP: providerRequests.length })) - } -} catch (error) { - if (client) { - try { save("plugin-diagnostics", await client.plugin.list({ location: { directory: project } })) } catch {} - } - save("result", { completed: false, message: error.message, stack: error.stack }) - save("failure-diagnostic", { message: error.message, stack: error.stack }) - console.error(error) - process.exitCode = 1 -} finally { - if (artifacts?.provider && existsSync(`${artifacts.provider.file}.held`)) renameSync(`${artifacts.provider.file}.held`, artifacts.provider.file) - if (artifacts?.qualification && existsSync(`${artifacts.qualification.file}.held`)) renameSync(`${artifacts.qualification.file}.held`, artifacts.qualification.file) - for (const child of owned) await stop(child) - spy.closeAllConnections(); await new Promise(resolve => spy.close(resolve)) - save("cleanup", { ownPIDs: owned.map(child => child.pid), running: owned.filter(child => child.exitCode === null && child.signalCode === null).map(child => child.pid), - providerRequests, sharedServiceAccess: "none", externalClient: statusOnly ? "harness only; read-only status qualification" - : controlledMaintenance ? "harness clock tick RPC; controlled-time maintenance explicitly qualified" - : "harness only; bounded no-project-client cold window recorded" }) - save("receipt", JSON.parse(readFileSync(path.join(root, "result.json"), "utf8"))) -} diff --git a/scripts/test-native-schedule-installation.mjs b/scripts/test-native-schedule-installation.mjs deleted file mode 100644 index 3599284ef4..0000000000 --- a/scripts/test-native-schedule-installation.mjs +++ /dev/null @@ -1,117 +0,0 @@ -// node --import tsx scripts/test-native-schedule-installation.mjs -import assert from "node:assert/strict" -import { spawn } from "node:child_process" -import { createHash } from "node:crypto" -import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs" -import path from "node:path" -import { pathToFileURL } from "node:url" -import { setTimeout as delay } from "node:timers/promises" -import { build } from "esbuild" -import { OpenCode } from "@opencode/client" -import { Service } from "@opencode/client/service" -import { nativePluginBuild } from "../packages/server/scripts/native-plugin-build.mjs" -import { installDesktopPluginPresence } from "../packages/server/src/opencode/desktop-plugin-installation.ts" - -const [cli, root] = process.argv.slice(2) -assert(cli && root && path.isAbsolute(cli) && path.isAbsolute(root) && !existsSync(root), "absolute CLI and fresh owned root required") -mkdirSync(root, { recursive: true }) -const env = {} -for (const key of ["SystemRoot", "WINDIR", "ComSpec", "PATHEXT", "PATH"]) if (process.env[key]) env[key] = process.env[key] -for (const name of ["CONFIG", "STATE", "CACHE", "DATA"]) env[`XDG_${name}_HOME`] = path.join(root, name.toLowerCase()) -Object.assign(env, { XDG_RUNTIME_DIR: path.join(root, "runtime"), HOME: path.join(root, "home"), USERPROFILE: path.join(root, "home"), - APPDATA: path.join(root, "appdata"), LOCALAPPDATA: path.join(root, "localappdata"), ProgramData: path.join(root, "programdata"), - TEMP: path.join(root, "tmp"), TMP: path.join(root, "tmp"), OPENCODE_DISABLE_PROJECT_CONFIG: "true", - OPENCODE_DISABLE_CLAUDE_CODE: "true", OPENCODE_DISABLE_MODELS_FETCH: "true", OPENCODE_DISABLE_FILEWATCHER: "true", OPENCODE_DISABLE_FFF: "true" }) -for (const [key, value] of Object.entries(env)) if (/^(XDG_|HOME$|USERPROFILE$|APPDATA$|LOCALAPPDATA$|ProgramData$|TEMP$|TMP$)/.test(key)) mkdirSync(value, { recursive: true }) -const project = path.join(root, "project"), config = path.join(env.XDG_CONFIG_HOME, "opencode"), data = path.join(root, "retained") -mkdirSync(project); mkdirSync(config, { recursive: true }) -writeFileSync(path.join(config, "opencode.json"), JSON.stringify({ snapshots: false, update: "disable" })) -writeFileSync(path.join(config, "service.json"), JSON.stringify({ hostname: "127.0.0.1", port: 0, disabled: false })) -const registrationFile = path.join(env.XDG_STATE_HOME, "opencode", "service.json") -const rpc = { id: "codenomad.installation-qualification", methods: { observe: { input: { type: "object" }, output: { type: "object" } } }, events: {} } -const entry = path.join(root, "entry.mjs"), bundleFile = path.join(root, "fixture.mjs"), providerFile = path.join(root, "provider.mjs") -const acquisitionSource = path.resolve("packages/server/src/opencode/missions/native-schedule-installation.ts") -writeFileSync(entry, `import assert from "node:assert/strict"; -import { Plugin, Rpc } from "@opencode/plugin/effect"; -import { Context, Effect, Option } from "effect"; -import { readFileSync, writeFileSync } from "node:fs"; -import { acquireNativeScheduleInstallation } from ${JSON.stringify(acquisitionSource)}; -const rpc=Rpc.define(${JSON.stringify(rpc)}); -export function desktopPlugin(presence,artifacts){return Plugin.define({id:"codenomad.installation-qualification",effect(ctx){return Effect.gen(function*(){ - const setup={global:Option.isSome(yield* Effect.serviceOption(Context.Service("@opencode/Global"))),server:Option.isSome(yield* Effect.serviceOption(Context.Service("@opencode/server/ServerInfo")))}; - let previous; - yield* ctx.rpc.register(rpc,{observe:()=>Effect.gen(function*(){ - const priorReleased=previous?(()=>{try{previous();return false}catch{return true}})():null; - const {installation,assertCurrent}=yield* acquireNativeScheduleInstallation(artifacts); - const active=assertCurrent();previous=assertCurrent; - const global=yield* Context.Service("@opencode/Global"),server=yield* Context.Service("@opencode/server/ServerInfo"); - const raw=readFileSync(installation.registrationFile,"utf8"),negatives=[]; - // This exact fixture owns its service record; restore it synchronously before - // the native registration monitor can observe a different incarnation. - try{for(const change of [{id:"different"},{pid:process.pid+1}]){ - writeFileSync(installation.registrationFile,JSON.stringify({...JSON.parse(raw),...change})); - let refused=false;try{assertCurrent()}catch{refused=true}assert(refused);negatives.push(refused); - }}finally{writeFileSync(installation.registrationFile,raw)} - assert.equal(assertCurrent(),true); - return {installation,active,priorReleased,setup,graph:{state:global.state,urls:server.urls(),pid:process.pid},negatives,manifestFrozen:Object.isFrozen(installation)&&Object.isFrozen(installation.provider)&&Object.isFrozen(installation.runtime)}; - }).pipe(Effect.scoped)}); -});}})} -`) -let child, closed, stopPresence -try { - const built = await build({ ...nativePluginBuild, entryPoints: [entry], outfile: bundleFile, - nodePaths: [path.resolve("node_modules")], metafile: true }) - assert(!Object.keys(built.metafile.inputs).some(file => /node_modules[/\\](effect|@opencode[/\\]plugin)[/\\]/.test(file)), "host Effect and SDK must remain external") - const localProvider = await build({ ...nativePluginBuild, entryPoints: [path.resolve("packages/server/src/opencode/missions/native-schedule-carrier-provider.ts")], outfile: providerFile, metafile: true }) - assert(Object.values(localProvider.metafile.outputs).every(output => output.imports.length === 0), "provider artifact is dependency-free") - const providerModule = await import(pathToFileURL(providerFile).href) - assert.throws(() => providerModule.createNativeScheduleCarrierProvider().languageModel(), /schedule-carrier-language-unavailable/) - const payload = readFileSync(bundleFile), provider = readFileSync(providerFile) - stopPresence = await installDesktopPluginPresence("missions", payload, { config, data }, () => {}, provider) - const source = readFileSync(path.join(config, "plugins", "codenomad-missions.ts"), "utf8") - const [, artifacts] = JSON.parse(`[${/export default desktopPlugin\((.+)\)\n$/.exec(source)[1]}]`) - child = spawn(cli, ["serve", "--service", "--hostname", "127.0.0.1", "--port", "0"], { cwd: project, env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }) - closed = new Promise(resolve => child.once("exit", resolve)) - let logs = "" - child.stdout.on("data", data => { logs += data }); child.stderr.on("data", data => { logs += data }) - let endpoint - const deadline = Date.now() + 40_000 - while (!endpoint) { - assert(child.exitCode === null && Date.now() < deadline, "private native startup deadline") - if (existsSync(registrationFile)) { - const info = JSON.parse(readFileSync(registrationFile, "utf8")) - if (info.pid === child.pid) endpoint = await Service.discover({ file: registrationFile }) - } - if (!endpoint) await delay(100) - } - assert.notEqual(new URL(endpoint.url).port, "28894") - const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }) - const info = await client.server.info() - const observe = () => client.rpc(rpc).observe({}, { location: { directory: project }, signal: AbortSignal.timeout(20_000) }) - const first = await observe(), second = await observe() - assert.equal(first.active, true); assert.equal(first.manifestFrozen, true) - assert.deepEqual(first.setup, { global: false, server: false }, "private services belong to the fresh RPC graph") - assert.equal(first.installation.registrationFile, registrationFile) - assert.deepEqual({ provider: first.installation.provider, runtime: first.installation.runtime }, artifacts) - assert.equal(first.graph.pid, child.pid) - assert.equal(first.graph.state, path.dirname(registrationFile)) - assert(first.graph.urls.some(url => new URL(url).href === new URL(endpoint.url).href)) - assert.equal(second.priorReleased, true) - await stopPresence() - assert.equal((await observe()).active, true, "fresh RPC acquisition works with backend lease absent") - await client.debug.location.evict({ location: { directory: project } }) - const reloaded = await observe() - assert.equal(reloaded.active, true) - assert.equal(reloaded.priorReleased, null, "eviction reconstructs the plugin from its retained installed artifacts") - assert.deepEqual(reloaded.installation, first.installation) - for (const artifact of Object.values(artifacts)) assert.equal(createHash("sha256").update(readFileSync(artifact.file)).digest("hex"), artifact.sha256) - const evidence = { completed: true, nativeVersion: info.version, cliSHA256: createHash("sha256").update(readFileSync(cli)).digest("hex"), - first, scopeReleasedBetweenRPCs: second.priorReleased, backendPresenceAbsent: true, retainedAfterLocationEviction: true, hostRuntimeExternal: true, - sourceSHA256: createHash("sha256").update(readFileSync(acquisitionSource)).digest("hex") } - writeFileSync(path.join(root, "evidence.json"), JSON.stringify(evidence, null, 2)) - console.log(JSON.stringify({ completed: true, nativeVersion: info.version, root })) -} finally { - await stopPresence?.() - if (child && child.exitCode === null && child.signalCode === null) child.kill("SIGKILL") - await closed -} diff --git a/scripts/test-native-schedule-openapi.mjs b/scripts/test-native-schedule-openapi.mjs deleted file mode 100644 index 2245f10db0..0000000000 --- a/scripts/test-native-schedule-openapi.mjs +++ /dev/null @@ -1,18 +0,0 @@ -// node --import tsx scripts/test-native-schedule-openapi.mjs -import assert from "node:assert/strict" -import { execFileSync } from "node:child_process" -import path from "node:path" -import { nativeScheduleCapability } from "../packages/server/src/opencode/native-schedule-capability.ts" - -const [checkout] = process.argv.slice(2) -assert(checkout && path.isAbsolute(checkout), "Pass an absolute read-only OpenCode source checkout") -for (const tag of ["v2.2.1", "v2.2.2", "v2.2.3"]) { - const document = JSON.parse(execFileSync("git", ["-C", checkout, "show", `${tag}:packages/protocol/openapi.json`], { - encoding: "utf8", maxBuffer: 16 * 1024 * 1024, - })) - assert.deepEqual(nativeScheduleCapability(document), { available: true }, tag) - // Optional when still needs the complete consumed timing contract. - delete document.components.schemas["Schedule.CreatePayload"].properties.when - assert.deepEqual(nativeScheduleCapability(document), { available: false, reason: "incompatible-contract" }, tag) - console.log(`PASS ${tag}: consumed schedule shapes, optional when and malformed-when refusal`) -} diff --git a/scripts/test-native-schedule-provider-registration.mjs b/scripts/test-native-schedule-provider-registration.mjs deleted file mode 100644 index 270425375b..0000000000 --- a/scripts/test-native-schedule-provider-registration.mjs +++ /dev/null @@ -1,135 +0,0 @@ -// node scripts/test-native-schedule-provider-registration.mjs -import assert from "node:assert/strict" -import { spawn } from "node:child_process" -import { createHash } from "node:crypto" -import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs" -import { createServer } from "node:http" -import path from "node:path" -import { setTimeout as delay } from "node:timers/promises" -import { build } from "esbuild" -import { OpenCode } from "@opencode/client" -import { Service } from "@opencode/client/service" -import { nativePluginBuild } from "../packages/server/scripts/native-plugin-build.mjs" - -const [cli, root] = process.argv.slice(2) -assert(cli && root && path.isAbsolute(cli) && path.isAbsolute(root) && !existsSync(root), "absolute CLI and fresh owned scratch required") -mkdirSync(root, { recursive: true }) -const source = path.resolve("packages/server/src/opencode/missions/native-schedule-provider-registration.ts") -const entry = path.join(root, "entry.mjs"), runtimeFile = path.join(root, "plugin", "index.mjs"), providerFile = path.join(root, "provider.mjs") -const rpc = { id: "codenomad.provider-registration-qualification", methods: Object.fromEntries(["inspect", "create"].map(name => - [name, { input: { type: "object" }, output: { type: "object" } }])), events: {} } -writeFileSync(entry, `import { Plugin,Rpc } from "@opencode/plugin/effect"; -import { Effect } from "effect"; -import { registerNativeScheduleProvider,assertNativeScheduleProviderAvailable } from ${JSON.stringify(source)}; -import { nativeScheduleCarrierHooks,NATIVE_SCHEDULE_CARRIER_MODEL,NATIVE_SCHEDULE_CARRIER_TITLE } from ${JSON.stringify(path.resolve("packages/server/src/opencode/missions/native-schedule-carrier.ts"))}; -const rpc=Rpc.define(${JSON.stringify(rpc)}); -export default Plugin.define({id:"codenomad.provider-registration-qualification",effect(ctx){return Effect.gen(function*(){ - const artifacts=ctx.options.artifacts,owned=new Set(); - yield* registerNativeScheduleProvider(ctx,artifacts); - if(ctx.options.hooks){const h=nativeScheduleCarrierHooks(id=>owned.has(id)); - yield*ctx.aisdk.hook("language",event=>Effect.sync(()=>h.language(event))); - for(const [name,method] of [["context","context"],["title","title"],["compaction","compaction"],["http.request","httpRequest"]]) - yield*ctx.session.hook(name,event=>Effect.sync(()=>h[method](event))); - } - yield*ctx.rpc.register(rpc,{ - inspect:()=>Effect.gen(function*(){ - const available=(yield*assertNativeScheduleProviderAvailable(ctx,artifacts).pipe(Effect.exit))._tag==="Success"; - const provider=yield*ctx.provider.get({providerID:NATIVE_SCHEDULE_CARRIER_MODEL.providerID}); - const models=yield*ctx.model.list({types:["chat"]}),def=yield*ctx.model.default(); - return JSON.parse(JSON.stringify({available,provider:provider.data,models:models.data.filter(m=>m.providerID===NATIVE_SCHEDULE_CARRIER_MODEL.providerID),defaultModel:def.data})); - }), - create:()=>Effect.gen(function*(){ - const available=(yield*assertNativeScheduleProviderAvailable(ctx,artifacts).pipe(Effect.exit))._tag==="Success"; - if(!available)return {refused:true}; - const session=yield*ctx.session.create({title:NATIVE_SCHEDULE_CARRIER_TITLE,model:NATIVE_SCHEDULE_CARRIER_MODEL}); - owned.add(session.id);return JSON.parse(JSON.stringify({session})); - }) - }); -});}}); -`) -const built = await build({ ...nativePluginBuild, entryPoints: [entry], outfile: runtimeFile, nodePaths: [path.resolve("node_modules")], metafile: true }) -assert(!Object.keys(built.metafile.inputs).some(file => /node_modules[/\\](effect|@opencode[/\\]plugin)[/\\]/.test(file))) -await build({ ...nativePluginBuild, entryPoints: [path.resolve("packages/server/src/opencode/missions/native-schedule-carrier-provider.ts")], outfile: providerFile }) -writeFileSync(path.join(root, "plugin", "package.json"), JSON.stringify({ name: "codenomad-provider-registration-qualification", type: "module", exports: { ".": "./index.mjs" } })) -const artifact = file => ({ file, sha256: createHash("sha256").update(readFileSync(file)).digest("hex") }) -const artifacts = { provider: artifact(providerFile), runtime: artifact(runtimeFile) }, requests = [] -const spy = createServer((req, res) => { requests.push({ method: req.method, path: req.url }); res.writeHead(500).end("Forbidden remote provider HTTP") }) -await new Promise(resolve => spy.listen(0, "127.0.0.1", resolve)) -const spyPort = spy.address().port -assert.notEqual(spyPort, 28894) -const evidence = { artifacts, sourceSHA256: artifact(source).sha256, cliSHA256: artifact(cli).sha256, cases: [] } -try { - for (const mode of ["healthy", "collision", "hookless"]) { - const directory = path.join(root, mode), env = {} - for (const key of ["SystemRoot", "WINDIR", "ComSpec", "PATHEXT", "PATH"]) if (process.env[key]) env[key] = process.env[key] - for (const name of ["CONFIG", "STATE", "DATA", "CACHE"]) env[`XDG_${name}_HOME`] = path.join(directory, name.toLowerCase()) - Object.assign(env, { HOME: path.join(directory, "home"), USERPROFILE: path.join(directory, "home"), XDG_RUNTIME_DIR: path.join(directory, "runtime"), - APPDATA: path.join(directory, "appdata"), LOCALAPPDATA: path.join(directory, "localappdata"), ProgramData: path.join(directory, "programdata"), - TEMP: path.join(directory, "tmp"), TMP: path.join(directory, "tmp"), OPENCODE_DISABLE_PROJECT_CONFIG: "true", OPENCODE_DISABLE_CLAUDE_CODE: "true", - OPENCODE_DISABLE_MODELS_FETCH: "true", OPENCODE_DISABLE_FILEWATCHER: "true", OPENCODE_DISABLE_FFF: "true" }) - for (const [key, value] of Object.entries(env)) if (/^(XDG_|HOME$|USERPROFILE$|APPDATA$|LOCALAPPDATA$|ProgramData$|TEMP$|TMP$)/.test(key)) mkdirSync(value, { recursive: true }) - const config = path.join(env.XDG_CONFIG_HOME, "opencode"), project = path.join(directory, "project") - mkdirSync(config, { recursive: true }); mkdirSync(project) - const remote = { name: "Forbidden remote default", package: "@opencode/ai/providers/openai-compatible", activation: "enabled", - settings: { baseURL: `http://127.0.0.1:${spyPort}/v1`, apiKey: "isolated-fixture-only" }, models: { forbidden: { limit: { context: 32000, output: 4096 } } } } - const configuration = { snapshots: false, update: "disable", plugins: [{ package: path.dirname(runtimeFile), options: { artifacts, hooks: mode !== "hookless" } }], - model: "remote-aux/forbidden", agents: { title: { model: "remote-aux/forbidden" }, compaction: { model: "remote-aux/forbidden" } }, - providers: { "remote-aux": remote, ...(mode === "collision" ? { "codenomad-missions-local": { ...remote, models: { "schedule-noop": {} } } } : {}) } } - const configFile = path.join(config, "opencode.json"), configBytes = JSON.stringify(configuration) - writeFileSync(configFile, configBytes) - writeFileSync(path.join(config, "service.json"), JSON.stringify({ hostname: "127.0.0.1", port: 0, disabled: false })) - const registrationFile = path.join(env.XDG_STATE_HOME, "opencode", "service.json") - const child = spawn(cli, ["serve", "--service", "--hostname", "127.0.0.1", "--port", "0"], { cwd: project, env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }) - const closed = new Promise(resolve => child.once("exit", resolve)) - child.stdout.resume(); child.stderr.resume() - try { - let endpoint - for (const deadline = Date.now() + 40_000; !endpoint;) { - assert(child.exitCode === null && Date.now() < deadline, "owned service startup deadline") - if (existsSync(registrationFile) && JSON.parse(readFileSync(registrationFile, "utf8")).pid === child.pid) - endpoint = await Service.discover({ file: registrationFile }) - if (!endpoint) await delay(100) - } - assert.notEqual(new URL(endpoint.url).port, "28894") - const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }), info = await client.server.info() - const qa = client.rpc(rpc), options = { location: { directory: project }, signal: AbortSignal.timeout(20_000) } - const inspected = await qa.inspect({}, options) - writeFileSync(path.join(directory, "catalog.json"), JSON.stringify(inspected, null, 2)) - assert.equal(inspected.defaultModel.providerID, "remote-aux") - assert.equal(inspected.available, mode !== "collision") - const created = await qa.create({}, options) - let outcome, compactionIDs = [] - if (mode === "collision") { - assert.deepEqual(created, { refused: true }) - assert.equal(inspected.provider.package, remote.package) - } else { - assert.equal(created.session.model.providerID, "codenomad-missions-local") - assert.equal(created.session.title, "Mission schedule carrier") - await client.session.prompt({ sessionID: created.session.id, text: "Bounded local carrier qualification" }) - await client.experimental.session.wait({ sessionID: created.session.id }, { signal: AbortSignal.timeout(20_000) }) - if (mode === "healthy") { - await client.session.compact({ sessionID: created.session.id }) - await client.experimental.session.wait({ sessionID: created.session.id }, { signal: AbortSignal.timeout(20_000) }) - } - const session = await client.session.get({ sessionID: created.session.id }) - assert.equal(session.outcome, mode === "healthy" ? "succeeded" : "failed") - outcome = session.outcome - if (mode === "healthy") { - const messages = await client.message.list({ sessionID: session.id, limit: 32, order: "asc" }) - compactionIDs = messages.data.filter(message => message.type === "compaction" && message.status === "completed").map(message => message.id) - assert.equal(compactionIDs.length, 1, "the real native compaction completed through the local hook") - } - } - assert.equal(readFileSync(configFile, "utf8"), configBytes, "the plugin never authors provider configuration") - assert.equal(requests.length, 0) - evidence.cases.push({ mode, nativeVersion: info.version, providerConfiguredInJSON: mode === "collision", available: inspected.available, - defaultUnchanged: true, carrierCreated: !!created.session, sessionID: created.session?.id, outcome, compactionIDs, - technicalHooksFixture: mode === "healthy", remoteHTTP: requests.length }) - } finally { - if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL") - await closed - } - } - writeFileSync(path.join(root, "evidence.json"), JSON.stringify({ ...evidence, completed: true, allOwnedServicesStopped: true }, null, 2)) - console.log(JSON.stringify({ completed: true, cases: evidence.cases, root })) -} finally { spy.closeAllConnections(); await new Promise(resolve => spy.close(resolve)) } diff --git a/scripts/test-opencode-browser-attach-native.mjs b/scripts/test-opencode-browser-attach-native.mjs new file mode 100644 index 0000000000..8d5c1119fc --- /dev/null +++ b/scripts/test-opencode-browser-attach-native.mjs @@ -0,0 +1,113 @@ +// Isolated native contract: a non-OpenCode client attaches as the desktop browser of a session +// (`experimental.browser` RPC, version 4) and answers the commands a Code Mode call dispatches. +// Usage: node scripts/test-opencode-browser-attach-native.mjs +import assert from "node:assert/strict" +import { mkdir, writeFile } from "node:fs/promises" +import path from "node:path" +import { setTimeout as delay } from "node:timers/promises" +import { Service } from "@opencode/client/service" +import { withProductRuntime } from "./native-product-fixture.mjs" + +const code = ` +const state = await tools.browser.tabs.list({}); +const tabID = state.tabs[0].id; +const snap = await tools.browser.snapshot({ tabID }); +const clicked = await tools.browser.click({ tabID, ref: "e2" }); +return { tabs: state.tabs.length, content: snap.content, url: clicked.url }; +` +const tab = { id: "tab_00000000-0000-4000-8000-000000000001", url: "http://127.0.0.1:9/page", title: "Fixture", loading: false, canGoBack: false, canGoForward: false, generation: 1 } + +await withProductRuntime(process.argv[2], async ({ root }) => { + const directory = path.join(root, "browser-model") + await mkdir(directory) + await writeFile(path.join(directory, "index.ts"), `export default { id: "browser-model-fixture", async setup(ctx) { + const seen = new Set(); + await ctx.session.hook("http.response", async event => { + if (event.kind !== "primary" || seen.has(event.sessionID)) return; + seen.add(event.sessionID); + await event.response.body?.cancel(); + const chunk = (delta, finish_reason = null) => "data: " + JSON.stringify({ id: "fixture", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta, finish_reason }] }) + "\\n\\n"; + const call = { index: 0, id: "call_browser", type: "function", function: { name: "execute", arguments: JSON.stringify({ code: ${JSON.stringify(code)} }) } }; + event.response = new Response(chunk({ role: "assistant", tool_calls: [call] }) + chunk({}, "tool_calls") + "data: [DONE]\\n\\n", { headers: { "content-type": "text/event-stream" } }); + }); + } }`) + return { plugins: [directory] } +}, async ({ client, root, requests, connection }) => { + const { endpoint } = connection + const headers = { ...Service.headers(endpoint), "content-type": "application/json" } + const location = `location[directory]=${encodeURIComponent(root)}` + const rpc = (method, input, signal) => fetch(`${endpoint.url}/api/rpc/experimental.browser/${method}?${location}`, + { method: "POST", headers, body: JSON.stringify({ input }), signal }).then(async response => { + const body = await response.json().catch(() => undefined) + if (!response.ok) throw new Error(`${method} ${response.status} ${JSON.stringify(body)}`) + return body?.output + }) + const session = await client.session.create({ location: { directory: root } }) + // The Location activates its plugins after the first request that names it. + const ready = Date.now() + 30_000 + for (;;) { + const listed = await fetch(`${endpoint.url}/api/plugin?${location}`, { headers }).then(response => response.json()) + const browser = listed.data.find(plugin => plugin.id === "opencode.browser") + if (browser?.state?.status === "active") break + assert(Date.now() < ready, `the native browser plugin activates: ${JSON.stringify(browser ?? listed.data.map(plugin => plugin.id))}`) + await delay(100) + } + const connectionID = crypto.randomUUID() + const attachment = new AbortController(), events = new AbortController() + const seen = [] + let attached = false + // The desktop subscribes to control events before it attaches. + const stream = await fetch(`${endpoint.url}/api/event?${location}`, { headers, signal: events.signal }) + assert(stream.ok, `event stream ${stream.status}`) + const listening = (async () => { + const decoder = new TextDecoder(); let buffer = "" + for await (const chunk of stream.body) { + buffer += decoder.decode(chunk, { stream: true }) + let index + while ((index = buffer.indexOf("\n\n")) >= 0) { + const block = buffer.slice(0, index); buffer = buffer.slice(index + 2) + const data = block.split("\n").filter(line => line.startsWith("data:")).map(line => line.slice(5).trim()).join("") + if (!data) continue + const event = JSON.parse(data) + if (event.type !== "rpc.experimental.browser.control" || event.data?.connectionID !== connectionID) continue + const control = event.data + if (control.type === "attached") { attached = true; await rpc("state", { sessionID: session.id, connectionID, state: { tabs: [tab], focusedTabID: tab.id } }); continue } + if (control.type !== "command") continue + const command = await rpc("command", { sessionID: session.id, connectionID, requestID: control.requestID }) + seen.push(command.action.type) + const value = command.action.type === "tabs.list" ? { tabs: [tab], focusedTabID: tab.id } + : command.action.type === "snapshot" ? { tab, content: '- button "Go" [ref=e2]', truncated: false } + : command.action.type === "click" ? { ...tab, url: "http://127.0.0.1:9/done" } + : undefined + const outcome = value === undefined ? { type: "failure", code: "unsupported", message: `browser.${command.action.type} is unsupported` } + : { type: "success", result: { value, files: [] } } + await rpc("result", { sessionID: session.id, connectionID, requestID: control.requestID, outcome }) + } + } + })().catch(error => { if (!events.signal.aborted) listenError = error }) + let listenError + const holding = rpc("attach", { sessionID: session.id, connectionID, version: 4 }, attachment.signal).catch(error => error) + try { await run() } finally { attachment.abort(); events.abort(); await Promise.allSettled([holding, listening]) } + if (listenError) throw listenError + console.log("PASS: a non-OpenCode client attaches as the session's browser and serves Code Mode browser calls") + + async function run() { + const deadline = Date.now() + 15_000 + while (!attached) { + if (listenError) throw listenError + assert(Date.now() < deadline, `attached control; attach: ${await Promise.race([holding, delay(1).then(() => "pending")])}`); await delay(25) + } + await client.session.prompt({ sessionID: session.id, text: "Use the browser." }) + await client.session.wait({ sessionID: session.id }, { signal: AbortSignal.timeout(60_000) }) + const offered = requests.find(request => request.tools?.some(tool => tool.function?.name === "execute")) + assert(offered, "native execute is available") + const messages = (await client.message.list({ sessionID: session.id, order: "asc", limit: 100 })).data + const part = messages.flatMap(message => message.type === "assistant" ? message.content : []).find(item => item.type === "tool" && item.name === "execute") + assert(part, "the execute call ran") + const text = part.state.content?.filter(item => item.type === "text").map(item => item.text).join("\n") ?? "" + console.log(JSON.stringify({ version: (await client.server.info()).version, status: part.state.status, seen, text: text.slice(0, 600) })) + assert.equal(part.state.status, "completed", text) + assert.deepEqual(seen, ["tabs.list", "snapshot", "click"]) + assert.deepEqual(JSON.parse(text), { tabs: 1, content: '- button "Go" [ref=e2]', url: "http://127.0.0.1:9/done" }) + } +}) diff --git a/scripts/test-opencode-location-native.mjs b/scripts/test-opencode-location-native.mjs index 6c4e0ec5c0..acb8479660 100644 --- a/scripts/test-opencode-location-native.mjs +++ b/scripts/test-opencode-location-native.mjs @@ -38,7 +38,7 @@ export async function testNativeLocationIdentity({ client, root, service }) { console.log("PASS: native modern worktree location and obsolete-selector rejection") } -export async function runIsolated(cli, run = testNativeLocationIdentity) { +export async function runIsolated(cli, run = testNativeLocationIdentity, config = {}) { if (!cli || !path.isAbsolute(cli)) throw new Error("Pass an absolute isolated CLI executable path") const temporaryRoot = path.join(os.tmpdir(), "opencode") await mkdir(temporaryRoot, { recursive: true }) @@ -50,7 +50,7 @@ export async function runIsolated(cli, run = testNativeLocationIdentity) { HOME: root, USERPROFILE: root, OPENCODE_TEST_HOME: root, OPENCODE_DB: path.join(root, "fixture.db"), OPENCODE_CONFIG_DIR: path.join(root, "config"), OPENCODE_SERVER_PASSWORD: password, OPENCODE_CONFIG_PROJECT_DISABLE: "1", - OPENCODE_DISABLE_MODELS_FETCH: "1", OPENCODE_DISABLE_FFF: "1", OPENCODE_CONFIG_CONTENT: "{}", + OPENCODE_DISABLE_MODELS_FETCH: "1", OPENCODE_DISABLE_FFF: "1", OPENCODE_CONFIG_CONTENT: JSON.stringify(config), }) await mkdir(env.OPENCODE_CONFIG_DIR) let output = "" diff --git a/scripts/test-recurring-simple-native.mjs b/scripts/test-recurring-simple-native.mjs deleted file mode 100644 index a55ecbe833..0000000000 --- a/scripts/test-recurring-simple-native.mjs +++ /dev/null @@ -1,425 +0,0 @@ -// Real isolated OpenCode + shipped bundle + authenticated production HTTP/HMAC routes. -// Usage: node scripts/test-recurring-simple-native.mjs [ordered subset of ABCDGELFWQN; default ABCD] -// E/L/F/W/Q/N (family quiescence, large family, provider failure, watched cursors, Wayfinder Form, ordinary dock Form) live in recurring-simple-native/journeys.mjs. -// No installer, default service discovery, shared database/config or pattern kills. -// Settlement is event-driven: each archive must follow family quiescence within -// SETTLE (2.5 min), far below the hourly Job ceiling. Next-day passages cannot be -// fast-forwarded here; the offline day e2e covers them. -import assert from "node:assert/strict" -import { spawn, execFileSync } from "node:child_process" -import { createHash, randomUUID } from "node:crypto" -import { createServer } from "node:http" -import { existsSync } from "node:fs" -import { copyFile, mkdir, mkdtemp, readFile, realpath, writeFile } from "node:fs/promises" -import path from "node:path" -import { setTimeout as delay } from "node:timers/promises" -import { tsImport } from "tsx/esm/api" -import Fastify from "fastify" -import pino from "pino" -import { OpenCode } from "@opencode/client" -import { stopFixtureChild } from "./native-fixture-guards.mjs" - -const source = process.argv[2], journeys = process.argv[3] ?? "ABCD" -assert.ok(source && path.isAbsolute(source), "Explicit existing CLI required") -assert.match(journeys, /^A?B?C?D?G?E?L?F?W?Q?N?$/, "Journeys: ordered subset of ABCDGELFWQN") -const parent = path.join(process.env.LOCALAPPDATA, "Temp/opencode") -await mkdir(parent, { recursive: true }) -const root = await realpath(await mkdtemp(path.join(parent, "recurring-simple-native-"))) -const cli = path.join(root, "opencode.exe"), project = path.join(root, "project") -await copyFile(source, cli) -const clean = Object.fromEntries(Object.entries(process.env).filter(([key]) => - /^(SystemRoot|WINDIR|ComSpec|PATHEXT|OS|NUMBER_OF_PROCESSORS|PROCESSOR_ARCHITECTURE|PATH)$/i.test(key))) -const env = { ...clean, HOME: root, USERPROFILE: root, APPDATA: root, LOCALAPPDATA: root, - ProgramData: path.join(root, "ProgramData"), - OPENCODE_TEST_HOME: root, OPENCODE_CONFIG_DIR: path.join(root, "config"), OPENCODE_DB: path.join(root, "fixture.db"), - OPENCODE_SERVER_PASSWORD: randomUUID(), OPENCODE_CONFIG_PROJECT_DISABLE: "1", OPENCODE_DISABLE_MODELS_FETCH: "1", - OPENCODE_DISABLE_FFF: "1", DO_NOT_TRACK: "1", TEMP: path.join(root, "tmp"), TMP: path.join(root, "tmp") } -for (const name of ["DATA", "CONFIG", "STATE", "CACHE", "RUNTIME"]) env[`XDG_${name}_HOME`] = path.join(root, `xdg-${name.toLowerCase()}`) -env.XDG_RUNTIME_DIR = path.join(root, "runtime") -for (const directory of [project, env.TEMP, env.ProgramData, env.OPENCODE_CONFIG_DIR, ...Object.entries(env).filter(([k]) => k.startsWith("XDG_")).map(([,v]) => v)]) await mkdir(directory, { recursive: true }) -// Imported backend modules must see the same private roots as the child service. -for (const key of Object.keys(process.env)) if (/^(OPENCODE_|XDG_|CODENOMAD_|WSL_)/i.test(key)) delete process.env[key] -Object.assign(process.env, env) -execFileSync("git", ["init", "-q", project], { env }) -await writeFile(path.join(project, "input.txt"), "deterministic native useful-work input\n") -const version = execFileSync(cli, ["--version"], { env, encoding: "utf8" }).trim() -const evidence = { root, cliVersion: version, outcome: "running", journeys: {}, providerCalls: [], isolation: {} } -for (const key of ["home", "config", "state", "data", "cache", "db"]) { - const actual = execFileSync(cli, ["debug", "paths", key], { env, encoding: "utf8" }).trim() - assert.ok(!path.relative(root, actual).startsWith("..") && path.isAbsolute(actual), `Private ${key}`) - evidence.isolation[key] = actual -} -const load = file => tsImport(`../packages/server/src/${file}.ts`, import.meta.url) -const { WorkspaceManager } = await load("workspaces/manager") -const { EventBus } = await load("events/bus") -const { rememberRuntime } = await load("opencode/compatibility/runtime") -const { DesktopPluginLifecycle } = await load("opencode/desktop-plugin-lifecycle") -const { resolveDesktopPluginPaths } = await load("opencode/desktop-plugin-paths") -const { createAutomationBridgeRegistration, publishAutomationBridge } = await load("opencode/automation-plugin") -const { registerAutomationPluginRoute } = await load("server/routes/automation-plugin") -const { registerMissionRecurrenceCreate } = await load("server/routes/mission-recurrence-create") -const { registerMissionRecurrenceControl } = await load("server/routes/mission-recurrence-control") -const { registerMissionRecurrenceManual } = await load("server/routes/mission-recurrence-manual") -const { WorktreeDeletionFence } = await load("workspaces/worktree-session-evacuation") -const { CODENOMAD_MISSIONS_RPC } = await load("missions/rpc") -const { registerInstanceProxyRoutes } = await load("server/http-server") -let child, closed, output = "", endpoint, manager, bridge, plugin, removeBridge, client, workspace, stage = "provider" -let hold = false, held = false -const releases = new Set() -// Journey modules add deterministic model plans: (turn) => { calls } | { text } | { fail } | { hold } | undefined. -const scenarios = [], holds = new Map() -const contentText = content => typeof content === "string" ? content : (content ?? []).map(part => part.text ?? "").join("") -const provider = createServer(async (request, response) => { - try { - let raw = ""; for await (const chunk of request) raw += chunk - const body = JSON.parse(raw), primary = request.headers["x-fixture-kind"] === "primary" - let answer = { text: "Done" } - if (primary) { - const messages = body.messages ?? [], tools = (body.tools ?? []).map(t => t.function.name) - const calls = messages.flatMap(m => m.tool_calls ?? []).map(t => t.function.name) - const turn = { sessionID: request.headers["x-fixture-session"], messages, tools, calls, all: JSON.stringify(messages), - first: contentText(messages.find(m => m.role === "user")?.content) } - let planned - for (const scenario of scenarios) if ((planned = await scenario(turn)) !== undefined) break - const name = planned ? undefined : ["read", "shell", "mission_inspect", "mission_report"].find(name => !calls.includes(name)) - answer = planned ?? (name ? { calls: [{ name, args: name === "read" ? { filePath: path.join(project, "input.txt") } - : name === "shell" ? { command: "echo native-recurring-useful-work", description: "Isolated useful shell" } - : name === "mission_inspect" ? {} : { outcome: "completed", summary: "Native read and shell completed", final: true } }] } : { text: "Done" }) - evidence.providerCalls.push({ sessionID: turn.sessionID, model: body.model, at: Date.now(), tools, - name: answer.calls ? answer.calls.map(c => c.name).join("+") : answer.fail ? "provider-error" : planned ? answer.text : "done" }) - if (hold || answer.hold) { - held = true - await new Promise(resolve => { (answer.hold ? holds.set(answer.hold, resolve) : releases.add(resolve)); response.once("close", resolve) }) - if (response.destroyed) return - } - for (const call of answer.calls ?? []) assert.ok(tools.includes(call.name), `Ordinary/native tool ${call.name} unavailable: ${tools.join(",")}`) - } - if (answer.fail) { // Non-retryable provider error (HTTP 400 invalid_request_error). - response.writeHead(400, { "content-type": "application/json" }) - return response.end(JSON.stringify({ error: { message: "FIXTURE_PROVIDER_FAILURE", type: "invalid_request_error" } })) - } - response.setHeader("content-type", body.stream ? "text/event-stream" : "application/json") - if (!body.stream) return response.end(JSON.stringify({ id: "fixture", choices: [{ message: { role: "assistant", content: "Fixture" }, finish_reason: "stop" }] })) - const calls = (answer.calls ?? []).map((call, index) => ({ index, id: call.id ?? `call_${randomUUID().replaceAll("-", "")}`, - type: "function", function: { name: call.name, arguments: JSON.stringify(call.args) } })) - for (const [delta, finish_reason] of [[calls.length ? { role: "assistant", tool_calls: calls } : { role: "assistant", content: answer.text ?? "Done" }, null], [{}, calls.length ? "tool_calls" : "stop"]]) - response.write(`data: ${JSON.stringify({ id: "fixture", object: "chat.completion.chunk", model: body.model, - choices: [{ index: 0, delta, finish_reason }] })}\n\n`) - response.end("data: [DONE]\n\n") - } catch (error) { evidence.providerError = error.message; response.destroy(error) } -}) -async function until(predicate, timeout = 90_000, interval = 250) { - const end = Date.now() + timeout - while (Date.now() < end) { - if (evidence.providerError) throw new Error(evidence.providerError) - if (await predicate()) return - if (child?.exitCode !== null && child?.exitCode !== undefined) throw new Error("Owned service exited") - await delay(interval) - } - throw new Error(`Timeout: ${stage}`) -} -async function waitForMissions() { - await until(async () => { - const { data } = await client.plugin.list({ location: { directory: project } }) - const missions = data.find(plugin => plugin.id === "codenomad.missions") - if (missions?.state.status === "failed") throw new Error("Native Missions fixture plugin failed to activate") - return missions?.state.status === "active" - }) -} -async function start() { - output = "" - child = spawn(cli, ["serve", "--hostname", "127.0.0.1", "--port", "0", "--print-logs"], { env, cwd: root, windowsHide: true }) - closed = new Promise(resolve => child.once("close", resolve)) - child.stdout.on("data", data => { output += data }); child.stderr.on("data", data => { output += data }) - await until(() => /http:\/\/127\.0\.0\.1:\d+/.test(output)) - endpoint = { url: output.match(/http:\/\/127\.0\.0\.1:\d+/)[0], auth: { type: "basic", username: "opencode", password: env.OPENCODE_SERVER_PASSWORD } } - const info = await (await fetch(`${endpoint.url}/api/info`, { headers: { authorization: `Basic ${Buffer.from(`opencode:${env.OPENCODE_SERVER_PASSWORD}`).toString("base64")}` } })).json() - assert.equal(info.pid, child.pid) - rememberRuntime(endpoint, { version: info.version, pid: info.pid, discovery: "info" }) - // Fixture-owned read-only observer bound to this exact service; independent of the backend. - client = OpenCode.make({ baseUrl: endpoint.url, headers: { Authorization: `Basic ${Buffer.from(`opencode:${env.OPENCODE_SERVER_PASSWORD}`).toString("base64")}` } }) - evidence.serviceStarts ??= []; evidence.serviceStarts.push({ pid: info.pid, version: info.version }) - if (evidence.serviceStarts.length > 1) await waitForMissions() -} -async function stop() { - assert.equal((await client.server.info()).pid, child.pid, "Exact owned PID before stop") - child.kill(); await Promise.race([closed, delay(10_000).then(() => { throw new Error("Owned service stop timeout") })]) - evidence.stoppedPIDs ??= []; evidence.stoppedPIDs.push(child.pid) -} -const yaml = path.join(root, "profile.yaml") -await writeFile(yaml, "server:\n environmentVariables: {}\n") -const profileScope = { channel: "native-fixture", configIdentity: yaml, key: createHash("sha256").update(`native-fixture\0${yaml}`).digest("hex") } -const settings = { getProfileScope: () => profileScope, configYamlPathForAuthority: () => yaml, - getOwner: () => ({ environmentVariables: {} }), readEnvironmentForAdmission: async () => ({}) } -const human = { sessionId: "isolated-human", username: "fixture-human" } -const auth = { isAuthEnabled: () => true, isLoopbackRequest: () => true, getCookieName: () => "session", - getSessionFromHeaders: headers => headers.cookie === "session=isolated-human" ? human : null, - getSessionFromRequest: request => request.headers.cookie === "session=isolated-human" ? human : null } -async function openBackend() { - manager = new WorkspaceManager({ rootDir: root, logger: pino({ level: "silent" }), eventBus: new EventBus(), settings, - binaryResolver: { resolveDefault: () => ({ path: cli, label: "Isolated recurring" }) }, - hostServiceLifecycleFactory: () => ({ discover: async () => endpoint, ensure: async () => endpoint }) }) - workspace = (await manager.create(project)).workspace - const connection = await manager.getSharedServiceConnection(workspace.id) - const paths = await resolveDesktopPluginPaths(connection, { kind: "host", platform: process.platform, binary: cli }) - assert.equal(paths.config, env.OPENCODE_CONFIG_DIR) - const registration = createAutomationBridgeRegistration("http://127.0.0.1:1"), fence = new WorktreeDeletionFence() - bridge = Fastify({ logger: { level: "warn" } }) - registerAutomationPluginRoute(bridge, { workspaceManager: manager, worktreeDeletionFence: fence, authManager: auth, - bridgeToken: registration.token, settings, nativeParent: {}, developerCdp: {} }) - registerMissionRecurrenceCreate(bridge, { workspaceManager: manager, worktreeDeletionFence: fence, auth, settings, bridgeToken: registration.token }) - for (const register of [registerMissionRecurrenceControl, registerMissionRecurrenceManual]) - register(bridge, { manager, fence, auth, settings, bridgeToken: registration.token }) - // Production instance proxy, including the InterruptionDock human-answer route. - registerInstanceProxyRoutes(bridge, { workspaceManager: manager, worktreeDeletionFence: fence, logger: pino({ level: "silent" }), - humanAnswers: { auth, manager, settings, bridgeToken: registration.token } }) - await bridge.listen({ host: "127.0.0.1", port: 0 }) - registration.url = `http://127.0.0.1:${bridge.server.address().port}/api/opencode-plugin/automation` - removeBridge = await publishAutomationBridge(registration) - plugin = new DesktopPluginLifecycle("missions"); await plugin.start(paths) - await waitForMissions() -} -async function closeBackend() { - await plugin?.stop(); plugin = undefined - await removeBridge?.(); removeBridge = undefined - await bridge?.close(); bridge = undefined - await manager?.shutdown(); manager = undefined // Drops connections only; never stops the owned service. -} -const location = { directory: project } -const rpc = () => client.rpc(CODENOMAD_MISSIONS_RPC) -const snapshot = async id => (await rpc().recurrenceSnapshot({}, { location })).schedules.find(s => s.id === id) -async function http(suffix, payload) { - const response = await bridge.inject({ method: "POST", url: `/api/workspaces/${workspace.id}/missions/recurrence${suffix}`, - headers: { cookie: "session=isolated-human" }, payload }) - assert.equal(response.statusCode, 200, response.body) - return response.json() -} -async function create(title, due, options = {}) { - const selected = { agent: "fixture-worker", model: { providerID: "fixture", id: "fixture" } } - const template = options.template ?? "custom" - const result = await http("", { requestID: `create_${randomUUID().replaceAll("-", "")}`, title, - instructions: options.instructions ?? "Read input.txt, run an echo shell, inspect the mission and submit a final completed mission_report.", - clock: { time: new Date(due).toISOString().slice(11,16), zone: "UTC" }, template, - profiles: { coordinator: selected, roles: Object.fromEntries((template === "wayfinder" - ? ["cartographer", "research", "prototype", "grilling", "decision"] : ["specialist"]).map(role => [role, selected])) }, - taskMode: "native", watchedConversationIDs: options.watched ?? [] }) - assert.equal(result.schedule.state, "paused") - return result.schedule.id -} -async function control(id, action) { - const s = await snapshot(id) - return http(`/${id}/${action === "run-now" ? "run-now" : "control"}`, { - requestID: `control_${randomUUID().replaceAll("-", "")}`, expectedRevision: s.revision, ...(action === "run-now" ? {} : { action }) }) -} -async function runNow(id) { - const payload = { requestID: `control_${randomUUID().replaceAll("-", "")}`, expectedRevision: (await snapshot(id)).revision } - return { payload, result: await http(`/${id}/run-now`, payload) } -} -// Coordinator start messages per passage, read from the isolated native API. -async function passageStarts(sessionID) { - const all = (await client.message.list({ sessionID, limit: 100 })).data - return all.filter(m => m.type === "user" || m.type === "synthetic").map(m => ({ id: m.id, type: m.type })) -} -const sessions = async () => (await client.session.list({ limit: { limit: 100 } })).data - .map(s => ({ id: s.id, parentID: s.parentID ?? null, created: s.time?.created })) -const done = sessionID => evidence.providerCalls.some(c => c.sessionID === sessionID && c.name === "done") -async function journeyD() { - stage = "D Pause Stop" - const due = Math.ceil((Date.now() + 75_000) / 60_000) * 60_000 - const id = await create("Paused before due", due) - const D = evidence.journeys.D = { id, dueAt: due } - await control(id, "play"); D.running = await snapshot(id) - await control(id, "pause"); D.paused = await snapshot(id) - assert.equal(D.paused.state, "paused"); assert.equal(D.paused.nextDueAt, null) - await delay(Math.max(0, due - Date.now()) + 30_000) - D.afterDue = await snapshot(id) - assert.equal(D.afterDue.pending, null); assert.equal(D.afterDue.history.length, 0) - D.rootSessionsCreatedAfterDue = (await sessions()).filter(s => !s.parentID && s.created >= due).map(s => s.id) - assert.deepEqual(D.rootSessionsCreatedAfterDue, [], "no passage session after the cancelled due time") - await control(id, "stop"); D.stopped = await snapshot(id) - assert.equal(D.stopped.state, "stopped"); assert.deepEqual(D.stopped.actions, []) - const refused = await bridge.inject({ method: "POST", url: `/api/workspaces/${workspace.id}/missions/recurrence/${id}/control`, - headers: { cookie: "session=isolated-human" }, payload: { requestID: `control_${randomUUID().replaceAll("-", "")}`, - expectedRevision: D.stopped.revision, action: "resume" } }) - D.resumeAfterStop = refused.statusCode; assert.notEqual(refused.statusCode, 200, "Stop is terminal") - D.result = "passed" -} -try { - await new Promise(resolve => provider.listen(0, "127.0.0.1", resolve)) - const hooks = path.join(root, "provider-hook"); await mkdir(hooks) - await writeFile(path.join(hooks, "index.ts"), `export default { id: 'recurring.fixture', async setup(ctx) { - await ctx.session.hook('http.request', event => { event.request.headers.set('x-fixture-kind', event.kind); event.request.headers.set('x-fixture-session', event.sessionID) }) - } }`) - env.OPENCODE_CONFIG_CONTENT = JSON.stringify({ model: "fixture/fixture", update: "disable", snapshots: false, - permissions: [{ action: "*", resource: "*", effect: "allow" }], agents: { "fixture-worker": { mode: "all", description: "Deterministic native fixture worker" } }, plugins: [hooks], providers: { fixture: { - package: "@opencode/ai/providers/openai-compatible", settings: { baseURL: `http://127.0.0.1:${provider.address().port}/v1`, apiKey: "fixture" }, models: { fixture: {} } } } }) - await writeFile(path.join(env.OPENCODE_CONFIG_DIR, "opencode.json"), "{}\n") - await start(); await openBackend() - // Event-driven settlement: the archive must follow family quiescence well before - // the hourly Job ceiling. The real service clock cannot be compressed for tomorrow. - const SETTLE = 150_000, SLOW = 1_000 - const nextMinute = lead => Math.ceil((Date.now() + lead) / 60_000) * 60_000 - const quiet = sessionID => client.session.wait({ sessionID }, { signal: AbortSignal.timeout(60_000) }) - if (journeys.includes("A")) { - stage = "A daily useful work" - const due = nextMinute(75_000) - const id = await create("Native daily useful work", due) - const A = evidence.journeys.A = { id, dueAt: due, paused: await snapshot(id) } - await control(id, "play") - A.played = await snapshot(id); assert.equal(A.played.state, "running"); assert.equal(A.played.nextDueAt, due) - await closeBackend() // No backend, presence or bridge during the passage; only the read-only observer. - A.backendClosedAt = Date.now() - await until(async () => (A.pending = await snapshot(id)).pending?.conversationID, 180_000) - A.pendingObservedAt = Date.now() - const sessionID = A.pending.pending.conversationID - await until(() => done(sessionID), 180_000) - A.workDoneAt = Date.now() - await quiet(sessionID); A.quiescentAt = Date.now() - stage = "A event-driven archive" - await until(async () => (A.settled = await snapshot(id)).history.length === 1, SETTLE, SLOW) - A.settledObservedAt = Date.now(); A.archiveLatencyMs = A.settledObservedAt - A.quiescentAt - assert.equal(A.settled.latestResult.outcome, "completed") - assert.equal(A.settled.pending, null) - assert.equal(A.settled.state, "running", "the same Job stays armed for the next civil day") - assert.equal(A.settled.nextDueAt, due + 86_400_000) - A.starts = await passageStarts(sessionID); assert.equal(A.starts.length, 1) - A.toolsUsed = evidence.providerCalls.filter(c => c.sessionID === sessionID).map(c => c.name) - A.sessions = await sessions() - A.result = "passed" - if (journeys.length > 1) await openBackend() - } - if (journeys.includes("B")) { - stage = "B restart pending" - const id = await create("Native restart reconcile", nextMinute(6 * 3_600_000)) - await control(id, "play"); hold = true - await control(id, "run-now"); await until(() => held) - const B = evidence.journeys.B = { id, before: await snapshot(id) } - const sessionID = B.before.pending.conversationID - B.startsBefore = await passageStarts(sessionID) - await closeBackend(); await stop(); hold = false; held = false; for (const release of releases) release(); releases.clear() - await start(); B.restartedAt = Date.now() - B.interrupted = await snapshot(id) - assert.equal(B.interrupted.state, "interrupted"); assert.equal(B.interrupted.interruptionReason, "service-restart") - assert.equal(B.interrupted.pending.passageID, B.before.pending.passageID) - // This owned standalone serve leaves the cut claim parked. Resume observes - // it; age and an empty process-local active set cannot prove termination. - await delay(20_000) - B.nativeAfterRestart = { calls: evidence.providerCalls.filter(c => c.sessionID === sessionID).length, done: done(sessionID), - active: Object.keys(await client.session.active()).includes(sessionID) } - assert.equal(B.nativeAfterRestart.active, false) - await openBackend() - await control(id, "resume"); B.resumedAt = Date.now() - stage = "B old claim remains uncertain" - await until(async () => (B.after = await snapshot(id)).pending?.status === "uncertain" && B.after.lastError?.code === "settlement-failed", SETTLE, SLOW) - for (let sample = 0; sample < 3; sample++) { - B.after = await snapshot(id) - assert.equal(B.after.pending.passageID, B.before.pending.passageID) - assert.equal(B.after.pending.status, "uncertain") - assert.equal(B.after.history.length, 0) - assert.equal(B.after.latestResult, null) - assert.equal(B.after.state, "running") - await delay(250) - } - B.starts = await passageStarts(sessionID); assert.equal(B.starts.length, 1, "Resume never sends a second coordinator message") - assert.deepEqual(B.starts.map(m => m.id), B.startsBefore.map(m => m.id)) - B.callsAfterResume = evidence.providerCalls.filter(c => c.sessionID === sessionID).length - assert.equal(B.callsAfterResume, B.nativeAfterRestart.calls, "Missions does not send a replacement or continuation prompt") - await control(id, "stop") - B.result = "passed" - } - if (journeys.includes("C")) { - stage = "C repeated Run now on one schedule" - const id = await create("Native manual useful work", nextMinute(6 * 3_600_000)) - await control(id, "play") - const C = evidence.journeys.C = { id, passages: [] } - for (let n = 0; n < 2; n++) { - const { payload } = await runNow(id) - let pending - await until(async () => (pending = await snapshot(id)).pending?.conversationID) - const sessionID = pending.pending.conversationID - if (n === 0) { - // Exact duplicate request (same requestID/expectedRevision): no second passage. - const replay = await bridge.inject({ method: "POST", url: `/api/workspaces/${workspace.id}/missions/recurrence/${id}/run-now`, - headers: { cookie: "session=isolated-human" }, payload }) - C.duplicate = { status: replay.statusCode, body: (() => { try { return replay.json() } catch { return replay.body.slice(0, 200) } })() } - } - await until(() => done(sessionID), 180_000) - await quiet(sessionID); const quiescentAt = Date.now() - let after - await until(async () => (after = await snapshot(id)).history.length === n + 1, SETTLE, SLOW) - const item = { passageID: pending.pending.passageID, sessionID, archiveLatencyMs: Date.now() - quiescentAt, - outcome: after.latestResult.outcome, starts: await passageStarts(sessionID), - tools: evidence.providerCalls.filter(c => c.sessionID === sessionID).map(c => c.name) } - assert.equal(after.latestResult.passageID, item.passageID); assert.equal(item.outcome, "completed") - assert.equal(item.starts.length, 1) - C.passages.push(item) - } - assert.notEqual(C.passages[0].passageID, C.passages[1].passageID) - assert.notEqual(C.passages[0].sessionID, C.passages[1].sessionID) - C.rootSessions = (await sessions()).filter(s => !s.parentID).map(s => s.id) - assert.equal(C.rootSessions.filter(s => C.passages.some(p => p.sessionID === s)).length, 2) - C.final = await snapshot(id) - await control(id, "stop") - C.result = "passed" - } - if (journeys.includes("D")) await journeyD() - if (journeys.includes("G")) { - // Paused schedule: only the settlement-only observer Job may archive; no Play/Resume. - stage = "G paused Run now" - const id = await create("Native paused Run now", nextMinute(6 * 3_600_000)) - const G = evidence.journeys.G = { id, paused: await snapshot(id) } - assert.equal(G.paused.state, "paused") - const { result } = await runNow(id); G.accepted = result - await until(async () => (G.pending = await snapshot(id)).pending?.conversationID) - const sessionID = G.pending.pending.conversationID - assert.equal(G.pending.state, "paused") - await until(() => done(sessionID), 180_000) - await quiet(sessionID); G.quiescentAt = Date.now() - stage = "G observer archive without Play/Resume" - await until(async () => (G.settled = await snapshot(id)).history.length === 1, SETTLE, SLOW) - G.settledObservedAt = Date.now(); G.archiveLatencyMs = G.settledObservedAt - G.quiescentAt - assert.equal(G.settled.latestResult.passageID, G.pending.pending.passageID) - assert.equal(G.settled.latestResult.outcome, "completed") - assert.equal(G.settled.pending, null); assert.equal(G.settled.state, "paused", "Run now never plays the schedule") - assert.equal(G.settled.nextDueAt, null) - G.starts = await passageStarts(sessionID); assert.equal(G.starts.length, 1) - G.tools = evidence.providerCalls.filter(c => c.sessionID === sessionID).map(c => c.name) - await control(id, "stop") - G.result = "passed" - } - if (/[ELFWQN]/.test(journeys)) { - const { runJourneys } = await import("./recurring-simple-native/journeys.mjs") - await runJourneys({ journeys, evidence, scenarios, holds, client, project, env, create, control, runNow, snapshot, - passageStarts, sessions, until, quiet, nextMinute, SETTLE, SLOW, bridge: () => bridge, workspace: () => workspace, - setStage: value => { stage = value } }) - } - evidence.outcome = "passed" -} catch (error) { - evidence.outcome = "failed"; evidence.failedStage = stage; evidence.error = error.message; process.exitCode = 1 - evidence.nativeErrors = output.split("\n").filter(line => /ERROR|WARN|Error:|Cause:|recurrence|codenomad\.missions|job/i.test(line)).slice(-40) - .map(line => line.replaceAll(env.OPENCODE_SERVER_PASSWORD, "[redacted]")) -} finally { - // Finish evidence even when settlement times out; read only this fixture's DB, - // which an early failure may not have created. Cleanup must never be skipped. - if (existsSync(env.OPENCODE_DB)) { - try { - const { DatabaseSync } = await import("node:sqlite") - const db = new DatabaseSync(env.OPENCODE_DB, { readOnly: true }) - try { - evidence.nativePassages = db.prepare("SELECT id,parent_id,project_id,directory FROM session_v2").all().map(s => ({ ...s, - starts: db.prepare("SELECT id,type FROM session_message WHERE session_id=? AND type IN ('user','synthetic')").all(s.id) })) - } finally { db.close() } - } catch (error) { evidence.nativePassagesError = error.message } - } - hold = false; for (const release of releases) release() - await closeBackend().catch(error => { evidence.backendCleanupError = error.message }) - if (child && child.exitCode === null && child.signalCode === null) { - const pid = child.pid - await stopFixtureChild(child, closed).then(() => { evidence.stoppedPIDs.push(pid) }) - .catch(error => { evidence.serviceCleanupError = error.message; process.exitCode = 1 }) - } - provider.closeAllConnections(); await new Promise(resolve => provider.close(resolve)) - // Native log may contain credentials: retain bounded error labels, never raw logs. - await writeFile(path.join(root, "qualification.json"), JSON.stringify(evidence, null, 2)) - console.log(JSON.stringify({ root, cliVersion: version, outcome: evidence.outcome, failedStage: evidence.failedStage, error: evidence.error }, null, 2)) -} diff --git a/scripts/test-release-workspace-version.mjs b/scripts/test-release-workspace-version.mjs index f110ae4404..dd6065c160 100644 --- a/scripts/test-release-workspace-version.mjs +++ b/scripts/test-release-workspace-version.mjs @@ -19,8 +19,8 @@ assert.equal(readFileSync(path.join(root, "packages/tauri-app/src-tauri/Cargo.to .match(/\[package\][\s\S]*?^version\s*=\s*"([^"]+)"/m)?.[1], manifest.version, "Cargo package version") assert.equal(readFileSync(path.join(root, "packages/tauri-app/Cargo.lock"), "utf8") .match(/name = "codenomad-tauri"\r?\nversion = "([^"]+)"/)?.[1], manifest.version, "Cargo lock version") -// The UI consumes Missions panel-page reads, introduced after the 1.0.x servers. -assert.equal(readJson(path.join(root, "packages/cloudflare/release-config.json")).minServerVersion, "1.1.0", "Remote UI server floor") +// The UI consumes the conversation permissions API. +assert.equal(readJson(path.join(root, "packages/cloudflare/release-config.json")).minServerVersion, "1.2.0", "Remote UI server floor") const directory = mkdtempSync(path.join(tmpdir(), "codenomad-release-version-")) function npm(args) { @@ -48,7 +48,7 @@ try { writeFileSync(path.join(directory, workspace, "package.json"), JSON.stringify(target)) } - for (const version of ["1.1.0", "1.1.0-dev-20261108-689f73b6"]) { + for (const version of [manifest.version, `${manifest.version}-dev-20261124-1d6c3888`]) { npm(["version", version, "--workspaces", "--include-workspace-root", "--no-git-tag-version", "--allow-same-version", "--offline"]) const lock = readJson(path.join(directory, "package-lock.json")) for (const workspace of ["", ...workspaces]) { diff --git a/scripts/test-session-permission-mode-native.mjs b/scripts/test-session-permission-mode-native.mjs new file mode 100644 index 0000000000..940eac43f5 --- /dev/null +++ b/scripts/test-session-permission-mode-native.mjs @@ -0,0 +1,360 @@ +// No discovery or shared daemon. Invoke with an absolute OpenCode executable. +import assert from "node:assert/strict" +import path from "node:path" +import { mkdir, writeFile } from "node:fs/promises" +import Fastify from "fastify" +import pino from "pino" +import { register } from "tsx/esm/api" +import { setTimeout as delay } from "node:timers/promises" +import { runIsolated } from "./test-opencode-location-native.mjs" + +// Use the same module instance as the relay's native event attribution map. +const { import: tsImport } = register({ namespace: "session-permission-mode-native" }) +const rule = (action, resource, effect) => ({ action, resource, effect }) +const config = { permissions: [ + rule("read", "*", "allow"), rule("shell", "*", "allow"), rule("shell", "rm *", "deny"), +] } + +await runIsolated(process.argv[2], async ({ client, connection: native, root }) => { + const { registerInstanceProxyRoutes } = await tsImport("../packages/server/src/server/http-server.ts", import.meta.url) + const { registerSessionPermissionModeRoutes } = await tsImport("../packages/server/src/server/routes/session-permission-mode.ts", import.meta.url) + const { connectSessionPermissionRefresh } = await tsImport("../packages/server/src/server/routes/session-permission-refresh.ts", import.meta.url) + const { SessionPermissionModes } = await tsImport("../packages/server/src/permissions/session-mode.ts", import.meta.url) + const { nativeEventConnections } = await tsImport("../packages/server/src/workspaces/opencode-service.ts", import.meta.url) + const { WorktreeDeletionFence } = await tsImport("../packages/server/src/workspaces/worktree-session-evacuation.ts", import.meta.url) + const { SessionCleanupFence } = await tsImport("../packages/server/src/server/session-cleanup-fence.ts", import.meta.url) + const { resolveConfigLocation } = await tsImport("../packages/server/src/config/location.ts", import.meta.url) + const { SettingsService } = await tsImport("../packages/server/src/settings/service.ts", import.meta.url) + const { EventBus } = await tsImport("../packages/server/src/events/bus.ts", import.meta.url) + const logger = pino({ level: "silent" }) + const profile = path.join(root, "codenomad-profile") + await mkdir(profile) + const profileLocation = resolveConfigLocation(profile) + const bus = new EventBus() + const settings = new SettingsService(profileLocation, bus, logger) + const modes = new SessionPermissionModes(settings) + const worktreeDeletionFence = new WorktreeDeletionFence(), cleanup = new SessionCleanupFence() + const app = Fastify() + const configPath = path.join(root, "config", "opencode.json") + await writeFile(configPath, JSON.stringify(config)) + await client.location.reload({ location: { directory: root } }) + const location = await client.location.get({ location: { directory: root } }) + const directory = location.directory + const otherDirectory = path.join(directory, "other") + await mkdir(otherDirectory) + const otherLocation = await client.location.get({ location: { directory: otherDirectory } }) + const workspaces = Object.fromEntries(["a", "b"].map(id => [id, { id, path: directory }])) + const owns = candidate => [directory, otherLocation.directory].some(owned => path.resolve(candidate) === path.resolve(owned)) + let modeWriteGate, proxyAdmission + const connection = { + ...native, + profile: async () => "modern", + client: { ...client, session: { ...client.session, update: async (input, options) => { + if (input.sessionID === modeWriteGate?.sessionID) { + modeWriteGate.started() + await modeWriteGate.released + } + return client.session.update(input, options) + } } }, + } + const workspaceManager = { + get: id => workspaces[id], + getSharedServiceConnection: async () => connection, + getSharedServiceClient: async () => client, + getInstanceAuthorizationHeader: () => undefined, + getSessionEnvironment: async () => ({}), + getServiceDirectory: () => directory, + getServiceWslDistro: () => undefined, + getWorktreeIdentityForPath: async (id, candidate) => { + if (id === "b") proxyAdmission?.() + return owns(candidate) ? directory : undefined + }, + ownsDirectory: async (_id, candidate) => owns(candidate), + ownsLocation: async (_id, candidate) => owns(candidate.directory), + ownsPath: async () => true, + } + registerInstanceProxyRoutes(app, { workspaceManager, logger, worktreeDeletionFence, sessionCleanup: cleanup, permissionModes: modes }) + registerSessionPermissionModeRoutes(app, { workspaceManager, modes, cleanup, worktreeDeletionFence }) + const create = async (payload = {}, query = "") => { + const reply = await app.inject({ method: "POST", url: `/workspaces/a/instance/api/session${query}`, payload }) + assert.equal(reply.statusCode, 200, reply.body) + return reply.json().data + } + const mode = async (instance, sessionID, next) => { + const reply = await app.inject({ method: next ? "PUT" : "GET", url: `/api/workspaces/${instance}/sessions/${sessionID}/permission-mode`, + ...(next ? { payload: { mode: next } } : {}) }) + assert.equal(reply.statusCode, 200, reply.body) + return reply.json().mode + } + const initial = rule("external_directory", "*", "deny") + const appended = rule("read", "other.txt", "deny") + const expected = [rule("edit", "*", "ask"), rule("shell", "*", "ask"), rule("shell", "*", "ask"), rule("shell", "rm *", "deny")] + const options = { headers: { "x-opencode-directory": encodeURIComponent(directory) }, signal: AbortSignal.timeout(45_000) } + try { + const original = await create({ permissions: [initial] }) + assert.deepEqual(original.permissions, [initial]) + assert.equal(await mode("a", original.id), "autonomous") + await client.session.remove({ sessionID: original.id }, options) + await client.session.import({ info: original, messages: [ + { id: "msg_permission_fixture", type: "user", text: "Fork fixture", time: { created: original.time.created } }, + ] }, options) + const setting = value => settings.mergePatchOwner("config", "ui", { settings: { newConversationPermissions: value } }) + setting("supervised") + const created = await create({ permissions: [initial] }) + assert.deepEqual(created.permissions, [initial, ...expected]) + assert.equal(await mode("b", created.id), "supervised") + assert.equal(await mode("b", original.id), "autonomous") + const elsewhere = await create({ location: { directory: otherLocation.directory } }, `?directory=${encodeURIComponent(directory)}`) + assert.equal(elsewhere.location.directory, otherLocation.directory, "the create body owns the config and placement") + assert.equal(await mode("a", elsewhere.id), "supervised") + const read = () => client.session.get({ sessionID: original.id }, options) + const nativePermission = (sessionID, action, resource, extra) => + client.permission.create({ sessionID, action, resources: [resource], agent: "build", ...extra }, options) + assert.equal((await nativePermission(created.id, "shell", "rm fixture")).effect, "deny") + assert.equal((await nativePermission(created.id, "read", "fixture.txt")).effect, "allow") + const localDeny = rule("shell", "echo blocked", "deny") + const deniedAtCreation = await create({ permissions: [localDeny] }) + assert.deepEqual(deniedAtCreation.permissions, [localDeny, ...expected, localDeny]) + assert.equal((await nativePermission(deniedAtCreation.id, "shell", "echo blocked")).effect, "deny") + assert.equal(await mode("a", deniedAtCreation.id, "autonomous"), "autonomous") + assert.deepEqual((await client.session.get({ sessionID: deniedAtCreation.id }, options)).permissions, [localDeny]) + assert.equal(await mode("a", deniedAtCreation.id, "supervised"), "supervised") + assert.equal((await nativePermission(deniedAtCreation.id, "shell", "echo blocked")).effect, "deny") + const observed = new AbortController() + const stream = client.event.subscribe({ signal: AbortSignal.any([observed.signal, options.signal]) })[Symbol.asyncIterator]() + try { + assert.equal((await stream.next()).value.type, "server.connected") + const settledEvent = (async () => { + for (;;) { + const { value, done } = await stream.next() + if (done) return + if (value.type === "session.permissions" && value.data.sessionID === original.id) return value + } + })() + void settledEvent.catch(() => {}) + assert.deepEqual(await Promise.all([mode("a", original.id, "supervised"), mode("b", original.id, "supervised")]), + ["supervised", "supervised"]) + assert.deepEqual((await settledEvent)?.data.permissions, [initial, ...expected]) + } finally { observed.abort(); await stream.return?.() } + assert.deepEqual((await read()).permissions, [initial, ...expected]) + const child = await client.session.create({ parentID: original.id }, options) + assert.deepEqual(child.permissions, [initial, ...expected]) + const fork = await client.session.fork({ sessionID: original.id }, options) + assert.equal(fork.fork?.sessionID, original.id) + assert.deepEqual(fork.permissions, [initial, ...expected]) + assert.equal(await mode("a", child.id), "supervised") + assert.equal(await mode("b", fork.id), "supervised") + const proxyFork = await app.inject({ method: "POST", url: `/workspaces/a/instance/api/session/${original.id}/fork`, payload: {} }) + assert.equal(proxyFork.statusCode, 200, proxyFork.body) + const forked = proxyFork.json().data + assert.deepEqual(forked.permissions, [initial, ...expected]) + assert.ok(modes.refreshTargets(undefined).targets.some(target => target.id === forked.id), "proxy records the fork before replying") + const secondChild = await client.session.create({ parentID: original.id }, options) + assert.equal(await mode("b", secondChild.id, "autonomous"), "autonomous") + assert.deepEqual((await client.session.get({ sessionID: secondChild.id }, options)).permissions, [initial, ...expected]) + assert.deepEqual((await read()).permissions, [initial]) + const newChild = await client.session.create({ parentID: original.id }, options) + assert.deepEqual(newChild.permissions, [initial]) + await mode("a", original.id, "supervised") + const save = await nativePermission(original.id, "shell", "echo saved", { save: ["echo saved"] }) + assert.equal(save.effect, "ask") + await client.permission.reply({ sessionID: original.id, requestID: save.id, decision: "always" }, options) + assert.equal((await nativePermission(original.id, "shell", "echo saved")).effect, "allow") + const pending = await nativePermission(original.id, "edit", path.join(directory, "fixture.txt")) + assert.equal(pending.effect, "ask") + await client.session.update({ sessionID: original.id, permissions: [initial, ...expected, appended] }, options) + assert.equal(await mode("b", original.id, "autonomous"), "autonomous") + assert.deepEqual((await read()).permissions, [initial, appended]) + assert.equal(await mode("a", original.id), "autonomous") + assert.deepEqual((await client.session.get({ sessionID: child.id })).permissions, [initial, ...expected]) + assert.equal(await mode("a", child.id), "autonomous") + assert.equal(await mode("a", forked.id), "supervised") + await client.session.update({ sessionID: forked.id, permissions: [initial, ...expected, appended] }, options) + assert.equal(await mode("b", forked.id, "autonomous"), "autonomous") + assert.deepEqual((await client.session.get({ sessionID: forked.id }, options)).permissions, [initial, appended]) + assert.deepEqual((await read()).permissions, [initial, appended]) + assert.ok((await client.permission.list({ sessionID: original.id }, options)).some(request => request.id === pending.id)) + await client.permission.reply({ sessionID: original.id, requestID: pending.id, decision: "reject" }, options) + + const started = Promise.withResolvers(), gate = Promise.withResolvers(), admitted = Promise.withResolvers() + modeWriteGate = { sessionID: original.id, started: started.resolve, released: gate.promise } + proxyAdmission = admitted.resolve + const changing = mode("a", original.id, "supervised") + const proxyDeny = rule("shell", "echo proxy-race", "deny") + let patch + try { + await Promise.race([started.promise, changing.then(() => assert.fail("mode write did not reach gate"))]) + patch = app.inject({ method: "PATCH", url: `/workspaces/b/instance/api/session/${original.id}`, + payload: { permissions: [initial, appended, proxyDeny] } }).then(reply => reply) + await Promise.race([admitted.promise, patch.then(reply => assert.fail(`proxy failed admission: ${reply.statusCode}`))]) + assert.equal(await Promise.race([patch.then(() => "answered"), delay(350, "waiting")]), "waiting", + "the native PATCH must wait for the in-flight mode update") + } finally { + gate.resolve() + await Promise.allSettled([changing, patch]) + modeWriteGate = proxyAdmission = undefined + } + const patched = await patch + assert.equal(patched.statusCode, 204, patched.body) + assert.equal(await changing, "supervised") + assert.deepEqual((await read()).permissions, [initial, appended, proxyDeny]) + assert.equal((await nativePermission(original.id, "shell", proxyDeny.resource)).effect, "deny") + console.log("PASS: same-backend native PATCH waits for the in-flight mode write and retains its deny") + + const stopRefresh = connectSessionPermissionRefresh(bus, workspaceManager, modes, worktreeDeletionFence, cleanup, logger) + const watching = new AbortController() + const refreshStream = client.event.subscribe({ signal: AbortSignal.any([watching.signal, options.signal]), + types: ["config.updated", "session.permissions", "session.created", "session.forked", "session.deleted"] })[Symbol.asyncIterator]() + try { + assert.equal((await refreshStream.next()).value.type, "server.connected") + const nextEvent = async (type, sessionID) => { + for (;;) { + const { value: event, done } = await refreshStream.next() + if (done) assert.fail("native permission event did not arrive") + nativeEventConnections.set(event, connection) + bus.publish({ type: "instance.event", event, instanceId: "a" }) + if (event.type === type && (!sessionID || event.data.sessionID === sessionID)) return event + } + } + const nextPermissions = async (sessionID = created.id) => (await nextEvent("session.permissions", sessionID)).data.permissions + const load = session => client.session.get({ sessionID: session.id }, options) + const send = session => app.inject({ method: "POST", url: `/workspaces/a/instance/api/session/${session.id}/prompt`, + payload: { text: "Permission mode fixture", resume: false } }) + const recorded = session => modes.refreshTargets(undefined).targets.some(target => target.id === session.id) + + const revisedChild = await client.session.create({ parentID: created.id }, options) + await nextEvent("session.created", revisedChild.id) + assert.equal(await mode("a", revisedChild.id), "supervised") + assert.ok(recorded(revisedChild)) + const deny = rule("shell", "echo refresh-fixture", "deny") + await writeFile(configPath, JSON.stringify({ permissions: [...config.permissions, deny] })) + const refreshed = new Set() + while (refreshed.size < 2) { + const { data } = await nextEvent("session.permissions") + if (data.sessionID !== created.id && data.sessionID !== revisedChild.id) continue + assert.deepEqual(data.permissions, [initial, ...expected, deny]) + refreshed.add(data.sessionID) + } + assert.equal((await nativePermission(created.id, "shell", deny.resource)).effect, "deny") + assert.equal((await nativePermission(revisedChild.id, "shell", deny.resource)).effect, "deny") + console.log("PASS: a config deny becomes effective on the root and recorded child") + + const explicit = await client.session.create({ parentID: created.id, permissions: [initial, ...expected, deny] }, options) + await nextEvent("session.created", explicit.id) + assert.equal((await nativePermission(explicit.id, "shell", deny.resource)).effect, "deny") + assert.equal(await mode("b", explicit.id, "autonomous"), "autonomous") + assert.deepEqual((await load(created)).permissions, [initial]) + assert.deepEqual((await load(explicit)).permissions, explicit.permissions) + assert.equal((await nativePermission(explicit.id, "shell", deny.resource)).effect, "deny") + const ask = await nativePermission(explicit.id, "shell", "echo explicitly configured") + assert.equal(ask.effect, "ask") + await client.permission.reply({ sessionID: explicit.id, requestID: ask.id, decision: "reject" }, options) + console.log("PASS: P1, an explicitly supplied array identical to the parent's stays intact, including its deny and ask") + + const refuseRemoval = async session => { + const reply = await app.inject({ method: "PUT", url: `/api/workspaces/b/sessions/${session.id}/permission-mode`, + payload: { mode: "autonomous" } }) + assert.equal(reply.statusCode, 409, reply.body) + assert.equal(reply.json().code, "PERMISSION_BLOCK_UNVERIFIED") + } + const history = await load(explicit) + assert.ok(recorded(explicit)) + await client.session.remove({ sessionID: explicit.id }, options) + await client.session.import({ info: history, messages: [ + { id: "msg_permission_child_history", type: "user", text: "Fork fixture", time: { created: history.time.created } }, + ] }, options) + await writeFile(configPath, JSON.stringify(config)) + await client.location.reload({ location: { directory } }) + const proxyCopy = await app.inject({ method: "POST", url: `/workspaces/a/instance/api/session/${explicit.id}/fork`, payload: {} }) + assert.equal(proxyCopy.statusCode, 200, proxyCopy.body) + const directFork = proxyCopy.json().data + assert.deepEqual(directFork.permissions, history.permissions) + assert.ok(recorded(directFork)) + await refuseRemoval(directFork) + assert.deepEqual((await load(directFork)).permissions, history.permissions) + assert.equal((await nativePermission(directFork.id, "shell", deny.resource)).effect, "deny") + console.log("PASS: Autonomous refuses to remove a fork's explicit copied deny") + + const nativeFork = await client.session.fork({ sessionID: directFork.id }, options) + await nextEvent("session.forked", nativeFork.id) + assert.ok((await load(nativeFork)).time.updated > nativeFork.time.created, "copying history updates the fork timestamp") + assert.equal(await mode("b", nativeFork.id), "supervised") + assert.ok(recorded(nativeFork)) + const newDeny = rule("shell", "echo additive fork refresh", "deny") + await writeFile(configPath, JSON.stringify({ permissions: [...config.permissions, newDeny] })) + await client.location.reload({ location: { directory } }) + const prompt = await send(nativeFork) + assert.equal(prompt.statusCode, 200, prompt.body) + const copied = [...history.permissions, newDeny] + assert.deepEqual((await load(nativeFork)).permissions, copied) + for (const rule of [deny, newDeny]) { + assert.equal((await nativePermission(nativeFork.id, "shell", rule.resource)).effect, "deny") + } + await refuseRemoval(nativeFork) + assert.deepEqual((await load(nativeFork)).permissions, copied) + console.log("PASS: a fork of an unowned fork admits a prompt and its refresh only adds denies") + + assert.equal(await mode("a", nativeFork.id, "supervised"), "supervised") + const layered = (await load(nativeFork)).permissions + assert.deepEqual(layered.slice(0, copied.length), copied) + assert.ok(layered.length > copied.length) + assert.equal(await mode("b", nativeFork.id, "autonomous"), "supervised") + assert.deepEqual((await load(nativeFork)).permissions, copied) + assert.equal((await nativePermission(nativeFork.id, "shell", deny.resource)).effect, "deny") + await refuseRemoval(nativeFork) + console.log("PASS: a distinct Supervised block is removable without removing the fork's copy") + + await writeFile(configPath, JSON.stringify({ permissions: [...config.permissions, deny] })) + await client.location.reload({ location: { directory } }) + assert.equal(await mode("a", revisedChild.id), "autonomous") + assert.equal(await mode("a", revisedChild.id, "supervised"), "supervised") + + const independentDeny = rule("shell", "echo independent deny", "deny") + const denyParent = await create({ permissions: [independentDeny] }) + const supplied = [appended, ...expected, deny, independentDeny] + const delayedEventChild = await client.session.create({ parentID: denyParent.id, permissions: supplied }, options) + await client.session.update({ sessionID: denyParent.id, title: "Renamed after creation" }, options) + await nextEvent("session.created", delayedEventChild.id) + assert.ok((await load(denyParent)).time.updated > delayedEventChild.time.created) + assert.equal((await nativePermission(delayedEventChild.id, "shell", independentDeny.resource)).effect, "deny") + assert.equal(await mode("b", delayedEventChild.id, "autonomous"), "autonomous") + assert.deepEqual((await load(delayedEventChild)).permissions, supplied) + assert.equal((await nativePermission(delayedEventChild.id, "shell", independentDeny.resource)).effect, "deny") + console.log("PASS: P1 delayed variant, a child-only deny survives a family mode change after source rename") + + const unknown = await send(fork) + assert.equal(unknown.statusCode, 200, unknown.body) + await refuseRemoval(fork) + assert.deepEqual((await load(fork)).permissions, fork.permissions) + console.log("PASS: unknown fork ownership only refuses rule removal; prompts still work") + + await client.session.remove({ sessionID: explicit.id }, options) + await nextEvent("session.deleted", explicit.id) + for (let i = 0; i < 50 && recorded(explicit); i++) await delay(20) + assert.ok(!recorded(explicit), "deletion removes the stored child copy") + + const insertedShell = rule("shell", "echo inserted", "deny") + const insertedEdit = rule("edit", path.join(directory, "private.txt"), "deny") + const prefix = [initial, insertedShell, insertedEdit] + const otherClientRules = [...prefix, ...expected, deny, appended] + await client.session.update({ sessionID: created.id, permissions: otherClientRules }, options) + const unprojected = await nativePermission(created.id, "shell", insertedShell.resource) + assert.equal(unprojected.effect, "ask") + await client.permission.reply({ sessionID: created.id, requestID: unprojected.id, decision: "reject" }, options) + assert.deepEqual(await nextPermissions(), otherClientRules) + assert.deepEqual(await nextPermissions(), [...prefix, ...expected, deny, insertedShell, insertedEdit, appended]) + for (const inserted of [insertedShell, insertedEdit]) { + assert.equal((await nativePermission(created.id, inserted.action, inserted.resource)).effect, "deny") + } + assert.equal(await mode("a", created.id, "autonomous"), "autonomous") + assert.deepEqual((await client.session.get({ sessionID: created.id })).permissions, [...prefix, appended]) + console.log("PASS: native permission event makes inserted shell and edit denies effective and autonomous retains them") + } finally { + watching.abort() + await refreshStream.return?.() + await stopRefresh() + } + + console.log("PASS: native root default, config deny/read, two clients and SSE, saved approval, family mode and pending request") + } finally { await app.close() } +}) diff --git a/scripts/test-session-pruning-native.mjs b/scripts/test-session-pruning-native.mjs index 8b3ddc71f9..98812edc61 100644 --- a/scripts/test-session-pruning-native.mjs +++ b/scripts/test-session-pruning-native.mjs @@ -126,7 +126,7 @@ env.OPENCODE_CONFIG_CONTENT = JSON.stringify({ }, models: { fixture: {} } } }, plugins: [path.join(root, "plugin")], // Runtimes with optional blob storage externalize tool files; others ignore the key. - experimental: { media_blob: true, ...(splitParts ? { part_rows: true } : {}) }, + experimental: { media_blob: true, part_rows: splitParts }, }) function start() { const child = spawn(cli, ["serve", "--hostname", "127.0.0.1", "--port", "0", "--log-level", "debug", "--print-logs"], { cwd: root, env, windowsHide: true }) @@ -217,12 +217,7 @@ try { const next = await proxy.shell.output({ id: shell.data.id, location: { directory: root }, cursor: output.data.cursor }) assert((output.data.output + next.data.output).includes("background-contract-fixture")) } finally { await proxy.shell.remove({ id: shell.data.id, location: { directory: root } }) } - const { createOpencodePermissionReplier } = await tsImport("../packages/server/src/permissions/opencode-replier.ts", import.meta.url) - const yolo = createOpencodePermissionReplier({ workspaceManager: { - get: () => ({ path: root }), getSharedServiceClient: async () => client, - ownsLocation: async (_id, location) => path.resolve(location.directory) === path.resolve(root) && location.workspaceID === undefined, - } }) - for (const mode of ["ui", "yolo", "reject"]) { + for (const mode of ["once", "reject"]) { primaryCount = 0 probeName = "permission_probe" try { @@ -237,14 +232,13 @@ try { console.error("Permission fixture", mode, primaryCount, JSON.stringify((await proxy.message.list({ sessionID, limit: 8 })).data)) throw error } - if (mode === "yolo") await yolo({ instanceId: "native", sessionId: sessionID, permissionId: pending.id }) - else await proxy.permission.reply({ sessionID, requestID: pending.id, decision: mode === "reject" ? "reject" : "once" }) + await proxy.permission.reply({ sessionID, requestID: pending.id, decision: mode }) await wait() assert(!(await proxy.permission.request.list({ location: { directory: root } })).data.some(item => item.id === pending.id)) } finally { probeName = "prune_probe" } } console.log("PASS: real proxy voice-off/on prompt, command, session Shell, pending inbox delivery/cancel, interrupt/wait") - console.log("PASS: real native permissions through UI and server Yolo, including rejection") + console.log("PASS: real native permission replies through the UI proxy") }, }) primaryCount = 0 diff --git a/scripts/test-subagent-nesting-native.mjs b/scripts/test-subagent-nesting-native.mjs index e71ce3dded..95b5bc2493 100644 --- a/scripts/test-subagent-nesting-native.mjs +++ b/scripts/test-subagent-nesting-native.mjs @@ -30,7 +30,7 @@ const provider = createServer(async (request, response) => { // Launch one General subagent when offered the tool; conclude once its launch is acknowledged (a tool // message) or the child reports in a later `` message. const last = body.messages?.at(-1) - const concluded = last?.role === "tool" || JSON.stringify(last?.content ?? "").includes("